@thisisagile/easy-express 15.26.1 → 15.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/chunk-G54PL2JB.mjs +43 -0
  2. package/dist/chunk-G54PL2JB.mjs.map +1 -0
  3. package/dist/chunk-RL5ICAHT.mjs +19 -0
  4. package/dist/chunk-RL5ICAHT.mjs.map +1 -0
  5. package/dist/express/AuthError.mjs +5 -11
  6. package/dist/express/AuthError.mjs.map +1 -1
  7. package/dist/express/CorrelationHandler.mjs +2 -1
  8. package/dist/express/CorrelationHandler.mjs.map +1 -1
  9. package/dist/express/ErrorHandler.mjs +8 -4
  10. package/dist/express/ErrorHandler.mjs.map +1 -1
  11. package/dist/express/ExpressProvider.mjs +12 -4
  12. package/dist/express/ExpressProvider.mjs.map +1 -1
  13. package/dist/express/NotFoundHandler.mjs +2 -1
  14. package/dist/express/NotFoundHandler.mjs.map +1 -1
  15. package/dist/express/RequestContextHandler.mjs +2 -1
  16. package/dist/express/RequestContextHandler.mjs.map +1 -1
  17. package/dist/express/SecurityHandler.mjs +8 -30
  18. package/dist/express/SecurityHandler.mjs.map +1 -1
  19. package/dist/index.js +208 -5
  20. package/dist/index.js.map +1 -1
  21. package/dist/types/NamespaceContext.mjs +3 -2
  22. package/dist/types/NamespaceContext.mjs.map +1 -1
  23. package/package.json +5 -4
  24. package/dist/express/AuthError.js +0 -43
  25. package/dist/express/AuthError.js.map +0 -1
  26. package/dist/express/CorrelationHandler.js +0 -33
  27. package/dist/express/CorrelationHandler.js.map +0 -1
  28. package/dist/express/ErrorHandler.js +0 -41
  29. package/dist/express/ErrorHandler.js.map +0 -1
  30. package/dist/express/ExpressProvider.js +0 -108
  31. package/dist/express/ExpressProvider.js.map +0 -1
  32. package/dist/express/NotFoundHandler.js +0 -32
  33. package/dist/express/NotFoundHandler.js.map +0 -1
  34. package/dist/express/RequestContextHandler.js +0 -30
  35. package/dist/express/RequestContextHandler.js.map +0 -1
  36. package/dist/express/SecurityHandler.js +0 -76
  37. package/dist/express/SecurityHandler.js.map +0 -1
  38. package/dist/express/index.js +0 -35
  39. package/dist/express/index.js.map +0 -1
  40. package/dist/types/NamespaceContext.js +0 -40
  41. package/dist/types/NamespaceContext.js.map +0 -1
  42. package/dist/types/index.js +0 -23
  43. package/dist/types/index.js.map +0 -1
@@ -0,0 +1,43 @@
1
+ import {
2
+ authError
3
+ } from "./chunk-RL5ICAHT.mjs";
4
+
5
+ // src/express/SecurityHandler.ts
6
+ import passport from "passport";
7
+ import { ExtractJwt, Strategy as JwtStrategy } from "passport-jwt";
8
+ import { ctx, Environment, HttpStatus, ifFalse } from "@thisisagile/easy";
9
+ var checkLabCoat = () => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));
10
+ var checkToken = () => passport.authenticate("jwt", { session: false, failWithError: true });
11
+ var checkScope = (scope) => (req, res, next) => next(ifFalse(req.user?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));
12
+ var checkUseCase = (uc) => (req, res, next) => next(ifFalse(req.user?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));
13
+ var wrapSecretOrKeyProvider = (p) => p ? (request, rawJwtToken, done) => p(request, rawJwtToken).then((t) => done(null, t)).catch((e) => done(e)) : void 0;
14
+ var security = ({ jwtStrategyOptions } = {}) => {
15
+ jwtStrategyOptions ??= {};
16
+ if ("secretOrKeyProvider" in jwtStrategyOptions)
17
+ jwtStrategyOptions.secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);
18
+ else if (!("secretOrKey" in jwtStrategyOptions))
19
+ jwtStrategyOptions.secretOrKey = ctx.env.get("tokenPublicKey");
20
+ const strategy = new JwtStrategy(
21
+ {
22
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
23
+ passReqToCallback: true,
24
+ ...jwtStrategyOptions
25
+ },
26
+ (req, payload, done) => {
27
+ ctx.request.token = payload;
28
+ ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? "";
29
+ done(null, payload);
30
+ }
31
+ );
32
+ passport.use(strategy);
33
+ return passport.initialize();
34
+ };
35
+
36
+ export {
37
+ checkLabCoat,
38
+ checkToken,
39
+ checkScope,
40
+ checkUseCase,
41
+ security
42
+ };
43
+ //# sourceMappingURL=chunk-G54PL2JB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/express/SecurityHandler.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n"],"mappings":";;;;;AACA,OAAO,cAAc;AACrB,SAAS,YAAY,YAAY,mBAAmB;AAIpD,SAAS,KAAK,aAAa,YAAY,eAAe;AA2B/C,IAAM,eAAe,MAAsB,CAAC,KAAK,KAAK,SAAS,KAAK,QAAQ,YAAY,IAAI,OAAO,IAAI,IAAI,IAAI,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAElJ,IAAM,aAAa,MAAsB,SAAS,aAAa,OAAO,EAAE,SAAS,OAAO,eAAe,KAAK,CAAC;AAE7G,IAAM,aACX,CAAC,UACD,CAAC,KAAK,KAAK,SACT,KAAK,QAAS,IAAI,MAAc,QAAQ,SAAS,MAAM,EAAE,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAEzF,IAAM,eACX,CAAC,OACD,CAAC,KAAK,KAAK,SACT,KAAK,QAAS,IAAI,MAAc,UAAU,SAAS,GAAG,EAAE,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAE/F,IAAM,0BAA0B,CAAC,MAC/B,IACI,CAAC,SAAS,aAAa,SACrB,EAAE,SAAS,WAAW,EACnB,KAAK,OAAK,KAAK,MAAM,CAAC,CAAC,EACvB,MAAM,OAAK,KAAK,CAAC,CAAC,IACvB;AAEC,IAAM,WAAW,CAAC,EAAE,mBAAmB,IAAqB,CAAC,MAAmE;AACrI,yBAAuB,CAAC;AACxB,MAAI,yBAAyB;AAC3B,IAAC,mBAA2B,sBAAsB,wBAAwB,mBAAmB,mBAAmB;AAAA,WACzG,EAAE,iBAAiB;AAAqB,uBAAmB,cAAc,IAAI,IAAI,IAAI,gBAAgB;AAE9G,QAAM,WAAW,IAAI;AAAA,IACnB;AAAA,MACE,gBAAgB,WAAW,4BAA4B;AAAA,MACvD,mBAAmB;AAAA,MACnB,GAAG;AAAA,IACL;AAAA,IACA,CAAC,KAAc,SAAc,SAAwC;AACnE,UAAI,QAAQ,QAAQ;AACpB,UAAI,QAAQ,MAAM,WAAW,4BAA4B,EAAE,GAAG,KAAK;AACnE,WAAK,MAAM,OAAO;AAAA,IACpB;AAAA,EACF;AAEA,WAAS,IAAI,QAAQ;AACrB,SAAO,SAAS,WAAW;AAC7B;","names":[]}
@@ -0,0 +1,19 @@
1
+ // src/express/AuthError.ts
2
+ import { isError } from "@thisisagile/easy";
3
+ var AuthError = class extends Error {
4
+ status;
5
+ constructor({ name, status }) {
6
+ super(name);
7
+ this.name = "AuthenticationError";
8
+ this.status = status;
9
+ }
10
+ };
11
+ var authError = (status) => new AuthError(status);
12
+ var isAuthError = (e) => isError(e) && e.name === "AuthenticationError";
13
+
14
+ export {
15
+ AuthError,
16
+ authError,
17
+ isAuthError
18
+ };
19
+ //# sourceMappingURL=chunk-RL5ICAHT.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/express/AuthError.ts"],"sourcesContent":["import { HttpStatus, isError } from '@thisisagile/easy';\n\nexport class AuthError extends Error {\n status: number;\n\n constructor({ name, status }: HttpStatus) {\n super(name);\n this.name = 'AuthenticationError';\n this.status = status;\n }\n}\n\nexport const authError = (status: HttpStatus): AuthError => new AuthError(status);\n\nexport const isAuthError = (e?: unknown): e is AuthError => isError(e) && e.name === 'AuthenticationError';\n"],"mappings":";AAAA,SAAqB,eAAe;AAE7B,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC;AAAA,EAEA,YAAY,EAAE,MAAM,OAAO,GAAe;AACxC,UAAM,IAAI;AACV,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,IAAM,YAAY,CAAC,WAAkC,IAAI,UAAU,MAAM;AAEzE,IAAM,cAAc,CAAC,MAAgC,QAAQ,CAAC,KAAK,EAAE,SAAS;","names":[]}
@@ -1,14 +1,8 @@
1
- import { isError } from "@thisisagile/easy";
2
- class AuthError extends Error {
3
- status;
4
- constructor({ name, status }) {
5
- super(name);
6
- this.name = "AuthenticationError";
7
- this.status = status;
8
- }
9
- }
10
- const authError = (status) => new AuthError(status);
11
- const isAuthError = (e) => isError(e) && e.name === "AuthenticationError";
1
+ import {
2
+ AuthError,
3
+ authError,
4
+ isAuthError
5
+ } from "../chunk-RL5ICAHT.mjs";
12
6
  export {
13
7
  AuthError,
14
8
  authError,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/AuthError.ts"],"sourcesContent":["import { HttpStatus, isError } from '@thisisagile/easy';\n\nexport class AuthError extends Error {\n status: number;\n\n constructor({ name, status }: HttpStatus) {\n super(name);\n this.name = 'AuthenticationError';\n this.status = status;\n }\n}\n\nexport const authError = (status: HttpStatus): AuthError => new AuthError(status);\n\nexport const isAuthError = (e?: unknown): e is AuthError => isError(e) && e.name === 'AuthenticationError';\n"],"mappings":"AAAA,SAAqB,eAAe;AAE7B,MAAM,kBAAkB,MAAM;AAAA,EACnC;AAAA,EAEA,YAAY,EAAE,MAAM,OAAO,GAAe;AACxC,UAAM,IAAI;AACV,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,MAAM,YAAY,CAAC,WAAkC,IAAI,UAAU,MAAM;AAEzE,MAAM,cAAc,CAAC,MAAgC,QAAQ,CAAC,KAAK,EAAE,SAAS;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,5 +1,6 @@
1
+ // src/express/CorrelationHandler.ts
1
2
  import { ctx, HttpHeader, toUuid } from "@thisisagile/easy";
2
- const correlation = (req, res, next) => {
3
+ var correlation = (req, res, next) => {
3
4
  res.setHeader(HttpHeader.Correlation, ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid());
4
5
  next();
5
6
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/CorrelationHandler.ts"],"sourcesContent":["import express from 'express';\nimport { ctx, HttpHeader, toUuid } from '@thisisagile/easy';\n\nexport const correlation = (req: express.Request, res: express.Response, next: express.NextFunction): void => {\n res.setHeader(HttpHeader.Correlation, (ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid()));\n next();\n};\n"],"mappings":"AACA,SAAS,KAAK,YAAY,cAAc;AAEjC,MAAM,cAAc,CAAC,KAAsB,KAAuB,SAAqC;AAC5G,MAAI,UAAU,WAAW,aAAc,IAAI,QAAQ,gBAAgB,KAAK,OAAO,WAAW,WAAW,KAAK,OAAO,CAAE;AACnH,OAAK;AACP;","names":[]}
1
+ {"version":3,"sources":["../../src/express/CorrelationHandler.ts"],"sourcesContent":["import express from 'express';\nimport { ctx, HttpHeader, toUuid } from '@thisisagile/easy';\n\nexport const correlation = (req: express.Request, res: express.Response, next: express.NextFunction): void => {\n res.setHeader(HttpHeader.Correlation, (ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid()));\n next();\n};\n"],"mappings":";AACA,SAAS,KAAK,YAAY,cAAc;AAEjC,IAAM,cAAc,CAAC,KAAsB,KAAuB,SAAqC;AAC5G,MAAI,UAAU,WAAW,aAAc,IAAI,QAAQ,gBAAgB,KAAK,OAAO,WAAW,WAAW,KAAK,OAAO,CAAE;AACnH,OAAK;AACP;","names":[]}
@@ -1,4 +1,8 @@
1
- import { isAuthError } from "./AuthError";
1
+ import {
2
+ isAuthError
3
+ } from "../chunk-RL5ICAHT.mjs";
4
+
5
+ // src/express/ErrorHandler.ts
2
6
  import {
3
7
  asString,
4
8
  choose,
@@ -16,14 +20,14 @@ import {
16
20
  toResult,
17
21
  tryTo
18
22
  } from "@thisisagile/easy";
19
- const toResponse = (status, errors = []) => ({
23
+ var toResponse = (status, errors = []) => ({
20
24
  status,
21
25
  body: rest.toError(status, errors)
22
26
  });
23
- const toBody = ({ origin, options }) => {
27
+ var toBody = ({ origin, options }) => {
24
28
  return choose(origin).type(isAuthError, (ae) => toResponse(toHttpStatus(ae.status), [toResult(ae.message)])).type(isDoesNotExist, (e) => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)])).type(isError, (e) => toResponse(HttpStatus.InternalServerError, [toResult(e.message)])).type(isResults, (r) => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results)).type(isResponse, (r) => toResponse(HttpStatus.InternalServerError, r.body.error?.errors)).type(isException, (e) => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)])).type(isText, (t) => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))])).else(() => toResponse(HttpStatus.InternalServerError, [toResult("Unknown error")]));
25
29
  };
26
- const error = (e, req, res, _next) => {
30
+ var error = (e, req, res, _next) => {
27
31
  let response;
28
32
  tryTo(() => toOriginatedError(e)).map((oe) => toBody(oe)).accept((r) => response = r).accept((r) => ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : void 0).accept((r) => ctx.request.lastErrorStack = r.status.isServerError ? e.stack : void 0).recover(() => response).accept((r) => res.status(r.status.status).json(r.body));
29
33
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/ErrorHandler.ts"],"sourcesContent":["import express from 'express';\nimport { isAuthError } from './AuthError';\nimport {\n asString,\n choose,\n ctx,\n HttpStatus,\n isDoesNotExist,\n isError,\n isException,\n isResponse,\n isResults,\n isText,\n OriginatedError,\n Response,\n rest,\n Result,\n toHttpStatus,\n toOriginatedError,\n toResult,\n tryTo,\n} from '@thisisagile/easy';\n\nconst toResponse = (status: HttpStatus, errors: Result[] = []): Response => ({\n status,\n body: rest.toError(status, errors),\n});\n\nconst toBody = ({ origin, options }: OriginatedError): Response => {\n return (\n choose(origin)\n .type(isAuthError, ae => toResponse(toHttpStatus(ae.status), [toResult(ae.message)]))\n .type(isDoesNotExist, e => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)]))\n // This service breaks with an error\n .type(isError, e => toResponse(HttpStatus.InternalServerError, [toResult(e.message)]))\n // This service fails\n .type(isResults, r => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results))\n // Underlying service fails\n .type(isResponse, r => toResponse(HttpStatus.InternalServerError, r.body.error?.errors))\n .type(isException, e => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)]))\n // This service fails with a string\n .type(isText, t => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))]))\n .else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]))\n );\n};\n\nexport const error = (e: Error, req: express.Request, res: express.Response, _next: express.NextFunction): void => {\n let response: Response;\n tryTo(() => toOriginatedError(e))\n .map(oe => toBody(oe))\n .accept(r => (response = r))\n .accept(r => (ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : undefined))\n .accept(r => (ctx.request.lastErrorStack = r.status.isServerError ? e.stack : undefined))\n .recover(() => response)\n .accept(r => res.status(r.status.status).json(r.body));\n};\n"],"mappings":"AACA,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,aAAa,CAAC,QAAoB,SAAmB,CAAC,OAAiB;AAAA,EAC3E;AAAA,EACA,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACnC;AAEA,MAAM,SAAS,CAAC,EAAE,QAAQ,QAAQ,MAAiC;AACjE,SACE,OAAO,MAAM,EACV,KAAK,aAAa,QAAM,WAAW,aAAa,GAAG,MAAM,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,EACnF,KAAK,gBAAgB,OAAK,WAAW,SAAS,cAAc,WAAW,UAAU,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,EAEnH,KAAK,SAAS,OAAK,WAAW,WAAW,qBAAqB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,EAEpF,KAAK,WAAW,OAAK,WAAW,SAAS,WAAW,WAAW,YAAY,EAAE,OAAO,CAAC,EAErF,KAAK,YAAY,OAAK,WAAW,WAAW,qBAAqB,EAAE,KAAK,OAAO,MAAM,CAAC,EACtF,KAAK,aAAa,OAAK,WAAW,SAAS,WAAW,WAAW,YAAY,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,EAE/G,KAAK,QAAQ,OAAK,WAAW,SAAS,WAAW,WAAW,YAAY,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,EAChG,KAAK,MAAM,WAAW,WAAW,qBAAqB,CAAC,SAAS,eAAe,CAAC,CAAC,CAAC;AAEzF;AAEO,MAAM,QAAQ,CAAC,GAAU,KAAsB,KAAuB,UAAsC;AACjH,MAAI;AACJ,QAAM,MAAM,kBAAkB,CAAC,CAAC,EAC7B,IAAI,QAAM,OAAO,EAAE,CAAC,EACpB,OAAO,OAAM,WAAW,CAAE,EAC1B,OAAO,OAAM,IAAI,QAAQ,YAAY,EAAE,OAAO,gBAAgB,EAAE,KAAK,OAAO,OAAO,CAAC,GAAG,UAAU,MAAU,EAC3G,OAAO,OAAM,IAAI,QAAQ,iBAAiB,EAAE,OAAO,gBAAgB,EAAE,QAAQ,MAAU,EACvF,QAAQ,MAAM,QAAQ,EACtB,OAAO,OAAK,IAAI,OAAO,EAAE,OAAO,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC;AACzD;","names":[]}
1
+ {"version":3,"sources":["../../src/express/ErrorHandler.ts"],"sourcesContent":["import express from 'express';\nimport { isAuthError } from './AuthError';\nimport {\n asString,\n choose,\n ctx,\n HttpStatus,\n isDoesNotExist,\n isError,\n isException,\n isResponse,\n isResults,\n isText,\n OriginatedError,\n Response,\n rest,\n Result,\n toHttpStatus,\n toOriginatedError,\n toResult,\n tryTo,\n} from '@thisisagile/easy';\n\nconst toResponse = (status: HttpStatus, errors: Result[] = []): Response => ({\n status,\n body: rest.toError(status, errors),\n});\n\nconst toBody = ({ origin, options }: OriginatedError): Response => {\n return (\n choose(origin)\n .type(isAuthError, ae => toResponse(toHttpStatus(ae.status), [toResult(ae.message)]))\n .type(isDoesNotExist, e => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)]))\n // This service breaks with an error\n .type(isError, e => toResponse(HttpStatus.InternalServerError, [toResult(e.message)]))\n // This service fails\n .type(isResults, r => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results))\n // Underlying service fails\n .type(isResponse, r => toResponse(HttpStatus.InternalServerError, r.body.error?.errors))\n .type(isException, e => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)]))\n // This service fails with a string\n .type(isText, t => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))]))\n .else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]))\n );\n};\n\nexport const error = (e: Error, req: express.Request, res: express.Response, _next: express.NextFunction): void => {\n let response: Response;\n tryTo(() => toOriginatedError(e))\n .map(oe => toBody(oe))\n .accept(r => (response = r))\n .accept(r => (ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : undefined))\n .accept(r => (ctx.request.lastErrorStack = r.status.isServerError ? e.stack : undefined))\n .recover(() => response)\n .accept(r => res.status(r.status.status).json(r.body));\n};\n"],"mappings":";;;;;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,IAAM,aAAa,CAAC,QAAoB,SAAmB,CAAC,OAAiB;AAAA,EAC3E;AAAA,EACA,MAAM,KAAK,QAAQ,QAAQ,MAAM;AACnC;AAEA,IAAM,SAAS,CAAC,EAAE,QAAQ,QAAQ,MAAiC;AACjE,SACE,OAAO,MAAM,EACV,KAAK,aAAa,QAAM,WAAW,aAAa,GAAG,MAAM,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,EACnF,KAAK,gBAAgB,OAAK,WAAW,SAAS,cAAc,WAAW,UAAU,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,EAEnH,KAAK,SAAS,OAAK,WAAW,WAAW,qBAAqB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,EAEpF,KAAK,WAAW,OAAK,WAAW,SAAS,WAAW,WAAW,YAAY,EAAE,OAAO,CAAC,EAErF,KAAK,YAAY,OAAK,WAAW,WAAW,qBAAqB,EAAE,KAAK,OAAO,MAAM,CAAC,EACtF,KAAK,aAAa,OAAK,WAAW,SAAS,WAAW,WAAW,YAAY,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,EAE/G,KAAK,QAAQ,OAAK,WAAW,SAAS,WAAW,WAAW,YAAY,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,EAChG,KAAK,MAAM,WAAW,WAAW,qBAAqB,CAAC,SAAS,eAAe,CAAC,CAAC,CAAC;AAEzF;AAEO,IAAM,QAAQ,CAAC,GAAU,KAAsB,KAAuB,UAAsC;AACjH,MAAI;AACJ,QAAM,MAAM,kBAAkB,CAAC,CAAC,EAC7B,IAAI,QAAM,OAAO,EAAE,CAAC,EACpB,OAAO,OAAM,WAAW,CAAE,EAC1B,OAAO,OAAM,IAAI,QAAQ,YAAY,EAAE,OAAO,gBAAgB,EAAE,KAAK,OAAO,OAAO,CAAC,GAAG,UAAU,MAAU,EAC3G,OAAO,OAAM,IAAI,QAAQ,iBAAiB,EAAE,OAAO,gBAAgB,EAAE,QAAQ,MAAU,EACvF,QAAQ,MAAM,QAAQ,EACtB,OAAO,OAAK,IAAI,OAAO,EAAE,OAAO,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC;AACzD;","names":[]}
@@ -1,5 +1,13 @@
1
+ import {
2
+ checkLabCoat,
3
+ checkScope,
4
+ checkToken,
5
+ checkUseCase
6
+ } from "../chunk-G54PL2JB.mjs";
7
+ import "../chunk-RL5ICAHT.mjs";
8
+
9
+ // src/express/ExpressProvider.ts
1
10
  import express from "express";
2
- import { checkLabCoat, checkScope, checkToken, checkUseCase } from "./SecurityHandler";
3
11
  import {
4
12
  HttpStatus,
5
13
  isEmpty,
@@ -11,7 +19,7 @@ import {
11
19
  toReq,
12
20
  toVerbOptions
13
21
  } from "@thisisagile/easy";
14
- class ExpressProvider {
22
+ var ExpressProvider = class {
15
23
  constructor(app = express()) {
16
24
  this.app = app;
17
25
  this.app.set("trust proxy", ["loopback", "linklocal", "uniquelocal"]);
@@ -74,8 +82,8 @@ class ExpressProvider {
74
82
  text(res, data) {
75
83
  res.send(data);
76
84
  }
77
- }
78
- const service = (name) => new Service(name, new ExpressProvider());
85
+ };
86
+ var service = (name) => new Service(name, new ExpressProvider());
79
87
  export {
80
88
  ExpressProvider,
81
89
  service
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/ExpressProvider.ts"],"sourcesContent":["import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n HttpStatus,\n isEmpty,\n PageList,\n Resource,\n rest,\n Route,\n RouteRequires,\n routes,\n Service,\n toList,\n toOriginatedError,\n toReq,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n"],"mappings":"AAAA,OAAO,aAA2E;AAClF,SAAS,cAAc,YAAY,YAAY,oBAAoB;AACnE;AAAA,EAIE;AAAA,EACA;AAAA,EAGA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIA,MAAM,gBAAuC;AAAA,EAClD,YAAsB,MAAe,QAAQ,GAAG;AAA1B;AACpB,SAAK,IAAI,IAAI,eAAe,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,EACtE;AAAA,EAEA,MAAM,CAAC,YAA2B;AAChC,SAAK,IAAI,IAAI,OAAO;AAAA,EACtB;AAAA,EAEA,QAAQ,CAACA,UAAkB,aAA6B;AACtD,UAAM,EAAE,OAAO,WAAW,WAAW,IAAI,OAAO,QAAQ;AACxD,UAAM,SAAS,QAAQ,OAAO,EAAE,aAAa,KAAK,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M;AAC9B,QAAI,KAAK,QAAQ,KAAK,IAAI;AAC1B,QAAI,QAAQ,MAAM;AAAS,UAAI,UAAU,QAAQ,MAAM,MAAM,QAAQ,MAAM,MAAM,CAAC;AAElF,KAAE,KAAa,QAAQ,KAAK,IAAI,KAAK,KAAK,MAAM,KAAK,QAAQ,OAAO;AAAA,EACtE;AAAA;AAAA,EAIU,KAAK,KAAe,QAAiB,SAAsC;AACnF,QAAI,WAAW,UAAU,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,KAAK,OAAO,QAAQ,MAAM,OAAY,MAAM,GAAI,QAA0B,OAAQ,QAA0B,IAAI,CAAC;AAAA,IAC5H;AAAA,EACF;AAAA,EAEU,OAAO,KAAe,QAAuB;AACrD,QAAI,IAAI,MAAM;AAAA,EAChB;AAAA,EAEU,KAAK,KAAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,MAAM,UAAU,CAAC,SAA0B,IAAI,QAAQ,MAAM,IAAI,gBAAgB,CAAC;","names":["service","middleware"]}
1
+ {"version":3,"sources":["../../src/express/ExpressProvider.ts"],"sourcesContent":["import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n HttpStatus,\n isEmpty,\n PageList,\n Resource,\n rest,\n Route,\n RouteRequires,\n routes,\n Service,\n toList,\n toOriginatedError,\n toReq,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n"],"mappings":";;;;;;;;;AAAA,OAAO,aAA2E;AAElF;AAAA,EAIE;AAAA,EACA;AAAA,EAGA;A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QAAI,SAAS;AAAO,iBAAW,KAAK,WAAW,SAAS,KAAK,CAAC;AAC9D,QAAI,SAAS;AAAI,iBAAW,KAAK,aAAa,SAAS,EAAE,CAAC;AAC1D,WAAO;AAAA,EACT;AAAA,EAEU,SACR,CAAC,UAAoB,SAAuB,aAC5C,CAAC,KAAc,KAAe,SAC5B,SAAS,MAAM,GAAG,CAAC,EAChB,KAAK,CAAC,MAAW,KAAK,WAAW,KAAK,GAAG,cAAc,OAAO,CAAC,CAAC,EAChE,MAAM,WAAS,KAAK,kBAAkB,OAAO,OAAO,CAAC,CAAC;AAAA,EAEnD,WAAW,KAAe,QAAiB,SAAsC;AACzF,QAAI,OAAO,QAAQ,KAAK,MAAM;AAC9B,QAAI,KAAK,QAAQ,KAAK,IAAI;AAC1B,QAAI,QAAQ,MAAM;AAAS,UAAI,UAAU,QAAQ,MAAM,MAAM,QAAQ,MAAM,MAAM,CAAC;AAElF,KAAE,KAAa,QAAQ,KAAK,IAAI,KAAK,KAAK,MAAM,KAAK,QAAQ,OAAO;AAAA,EACtE;AAAA;AAAA,EAIU,KAAK,KAAe,QAAiB,SAAsC;AACnF,QAAI,WAAW,UAAU,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,KAAK,OAAO,QAAQ,MAAM,OAAY,MAAM,GAAI,QAA0B,OAAQ,QAA0B,IAAI,CAAC;AAAA,IAC5H;AAAA,EACF;AAAA,EAEU,OAAO,KAAe,QAAuB;AACrD,QAAI,IAAI,MAAM;AAAA,EAChB;AAAA,EAEU,KAAK,KAAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,IAAM,UAAU,CAAC,SAA0B,IAAI,QAAQ,MAAM,IAAI,gBAAgB,CAAC;","names":["service","middleware"]}
@@ -1,5 +1,6 @@
1
+ // src/express/NotFoundHandler.ts
1
2
  import { Exception, toOriginatedError } from "@thisisagile/easy";
2
- const notFound = (req, res, next) => {
3
+ var notFound = (req, res, next) => {
3
4
  next(toOriginatedError(Exception.DoesNotExist));
4
5
  };
5
6
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/NotFoundHandler.ts"],"sourcesContent":["import { NextFunction, Request, Response } from 'express';\nimport { Exception, toOriginatedError } from '@thisisagile/easy';\n\nexport const notFound = (req: Request, res: Response, next: NextFunction): void => {\n next(toOriginatedError(Exception.DoesNotExist));\n};\n"],"mappings":"AACA,SAAS,WAAW,yBAAyB;AAEtC,MAAM,WAAW,CAAC,KAAc,KAAe,SAA6B;AACjF,OAAK,kBAAkB,UAAU,YAAY,CAAC;AAChD;","names":[]}
1
+ {"version":3,"sources":["../../src/express/NotFoundHandler.ts"],"sourcesContent":["import { NextFunction, Request, Response } from 'express';\nimport { Exception, toOriginatedError } from '@thisisagile/easy';\n\nexport const notFound = (req: Request, res: Response, next: NextFunction): void => {\n next(toOriginatedError(Exception.DoesNotExist));\n};\n"],"mappings":";AACA,SAAS,WAAW,yBAAyB;AAEtC,IAAM,WAAW,CAAC,KAAc,KAAe,SAA6B;AACjF,OAAK,kBAAkB,UAAU,YAAY,CAAC;AAChD;","names":[]}
@@ -1,5 +1,6 @@
1
+ // src/express/RequestContextHandler.ts
1
2
  import { ctx } from "@thisisagile/easy";
2
- const requestContext = (req, res, next) => ctx.request.create(() => next());
3
+ var requestContext = (req, res, next) => ctx.request.create(() => next());
3
4
  export {
4
5
  requestContext
5
6
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/RequestContextHandler.ts"],"sourcesContent":["import express from 'express';\nimport { ctx } from '@thisisagile/easy';\n\nexport const requestContext = (req: express.Request, res: express.Response, next: express.NextFunction): void => ctx.request.create(() => next());\n"],"mappings":"AACA,SAAS,WAAW;AAEb,MAAM,iBAAiB,CAAC,KAAsB,KAAuB,SAAqC,IAAI,QAAQ,OAAO,MAAM,KAAK,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../src/express/RequestContextHandler.ts"],"sourcesContent":["import express from 'express';\nimport { ctx } from '@thisisagile/easy';\n\nexport const requestContext = (req: express.Request, res: express.Response, next: express.NextFunction): void => ctx.request.create(() => next());\n"],"mappings":";AACA,SAAS,WAAW;AAEb,IAAM,iBAAiB,CAAC,KAAsB,KAAuB,SAAqC,IAAI,QAAQ,OAAO,MAAM,KAAK,CAAC;","names":[]}
@@ -1,33 +1,11 @@
1
- import passport from "passport";
2
- import { ExtractJwt, Strategy as JwtStrategy } from "passport-jwt";
3
- import { authError } from "./AuthError";
4
- import { ctx, Environment, HttpStatus, ifFalse } from "@thisisagile/easy";
5
- const checkLabCoat = () => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));
6
- const checkToken = () => passport.authenticate("jwt", { session: false, failWithError: true });
7
- const checkScope = (scope) => (req, res, next) => next(ifFalse(req.user?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));
8
- const checkUseCase = (uc) => (req, res, next) => next(ifFalse(req.user?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));
9
- const wrapSecretOrKeyProvider = (p) => p ? (request, rawJwtToken, done) => p(request, rawJwtToken).then((t) => done(null, t)).catch((e) => done(e)) : void 0;
10
- const security = ({ jwtStrategyOptions } = {}) => {
11
- jwtStrategyOptions ??= {};
12
- if ("secretOrKeyProvider" in jwtStrategyOptions)
13
- jwtStrategyOptions.secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);
14
- else if (!("secretOrKey" in jwtStrategyOptions))
15
- jwtStrategyOptions.secretOrKey = ctx.env.get("tokenPublicKey");
16
- const strategy = new JwtStrategy(
17
- {
18
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
19
- passReqToCallback: true,
20
- ...jwtStrategyOptions
21
- },
22
- (req, payload, done) => {
23
- ctx.request.token = payload;
24
- ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? "";
25
- done(null, payload);
26
- }
27
- );
28
- passport.use(strategy);
29
- return passport.initialize();
30
- };
1
+ import {
2
+ checkLabCoat,
3
+ checkScope,
4
+ checkToken,
5
+ checkUseCase,
6
+ security
7
+ } from "../chunk-G54PL2JB.mjs";
8
+ import "../chunk-RL5ICAHT.mjs";
31
9
  export {
32
10
  checkLabCoat,
33
11
  checkScope,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/SecurityHandler.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n"],"mappings":"AACA,OAAO,cAAc;AACrB,SAAS,YAAY,YAAY,mBAAmB;AAGpD,SAAS,iBAAiB;AAC1B,SAAS,KAAK,aAAa,YAAY,eAAe;AA2B/C,MAAM,eAAe,MAAsB,CAAC,KAAK,KAAK,SAAS,KAAK,QAAQ,YAAY,IAAI,OAAO,IAAI,IAAI,IAAI,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAElJ,MAAM,aAAa,MAAsB,SAAS,aAAa,OAAO,EAAE,SAAS,OAAO,eAAe,KAAK,CAAC;AAE7G,MAAM,aACX,CAAC,UACD,CAAC,KAAK,KAAK,SACT,KAAK,QAAS,IAAI,MAAc,QAAQ,SAAS,MAAM,EAAE,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAEzF,MAAM,eACX,CAAC,OACD,CAAC,KAAK,KAAK,SACT,KAAK,QAAS,IAAI,MAAc,UAAU,SAAS,GAAG,EAAE,GAAG,UAAU,WAAW,SAAS,CAAC,CAAC;AAE/F,MAAM,0BAA0B,CAAC,MAC/B,IACI,CAAC,SAAS,aAAa,SACrB,EAAE,SAAS,WAAW,EACnB,KAAK,OAAK,KAAK,MAAM,CAAC,CAAC,EACvB,MAAM,OAAK,KAAK,CAAC,CAAC,IACvB;AAEC,MAAM,WAAW,CAAC,EAAE,mBAAmB,IAAqB,CAAC,MAAmE;AACrI,yBAAuB,CAAC;AACxB,MAAI,yBAAyB;AAC3B,IAAC,mBAA2B,sBAAsB,wBAAwB,mBAAmB,mBAAmB;AAAA,WACzG,EAAE,iBAAiB;AAAqB,uBAAmB,cAAc,IAAI,IAAI,IAAI,gBAAgB;AAE9G,QAAM,WAAW,IAAI;AAAA,IACnB;AAAA,MACE,gBAAgB,WAAW,4BAA4B;AAAA,MACvD,mBAAmB;AAAA,MACnB,GAAG;AAAA,IACL;AAAA,IACA,CAAC,KAAc,SAAc,SAAwC;AACnE,UAAI,QAAQ,QAAQ;AACpB,UAAI,QAAQ,MAAM,WAAW,4BAA4B,EAAE,GAAG,KAAK;AACnE,WAAK,MAAM,OAAO;AAAA,IACpB;AAAA,EACF;AAEA,WAAS,IAAI,QAAQ;AACrB,SAAO,SAAS,WAAW;AAC7B;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.js CHANGED
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
6
12
  var __copyProps = (to, from, except, desc) => {
7
13
  if (from && typeof from === "object" || typeof from === "function") {
8
14
  for (let key of __getOwnPropNames(from))
@@ -11,15 +17,212 @@ var __copyProps = (to, from, except, desc) => {
11
17
  }
12
18
  return to;
13
19
  };
14
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
15
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
16
31
  var src_exports = {};
32
+ __export(src_exports, {
33
+ AuthError: () => AuthError,
34
+ ExpressProvider: () => ExpressProvider,
35
+ NamespaceContext: () => NamespaceContext,
36
+ authError: () => authError,
37
+ checkLabCoat: () => checkLabCoat,
38
+ checkScope: () => checkScope,
39
+ checkToken: () => checkToken,
40
+ checkUseCase: () => checkUseCase,
41
+ correlation: () => correlation,
42
+ error: () => error,
43
+ isAuthError: () => isAuthError,
44
+ notFound: () => notFound,
45
+ requestContext: () => requestContext,
46
+ security: () => security,
47
+ service: () => service
48
+ });
17
49
  module.exports = __toCommonJS(src_exports);
18
- __reExport(src_exports, require("./express"), module.exports);
19
- __reExport(src_exports, require("./types"), module.exports);
50
+
51
+ // src/express/AuthError.ts
52
+ var import_easy = require("@thisisagile/easy");
53
+ var AuthError = class extends Error {
54
+ status;
55
+ constructor({ name, status }) {
56
+ super(name);
57
+ this.name = "AuthenticationError";
58
+ this.status = status;
59
+ }
60
+ };
61
+ var authError = (status) => new AuthError(status);
62
+ var isAuthError = (e) => (0, import_easy.isError)(e) && e.name === "AuthenticationError";
63
+
64
+ // src/express/CorrelationHandler.ts
65
+ var import_easy2 = require("@thisisagile/easy");
66
+ var correlation = (req, res, next) => {
67
+ res.setHeader(import_easy2.HttpHeader.Correlation, import_easy2.ctx.request.correlationId = req?.header(import_easy2.HttpHeader.Correlation) ?? (0, import_easy2.toUuid)());
68
+ next();
69
+ };
70
+
71
+ // src/express/ErrorHandler.ts
72
+ var import_easy3 = require("@thisisagile/easy");
73
+ var toResponse = (status, errors = []) => ({
74
+ status,
75
+ body: import_easy3.rest.toError(status, errors)
76
+ });
77
+ var toBody = ({ origin, options }) => {
78
+ return (0, import_easy3.choose)(origin).type(isAuthError, (ae) => toResponse((0, import_easy3.toHttpStatus)(ae.status), [(0, import_easy3.toResult)(ae.message)])).type(import_easy3.isDoesNotExist, (e) => toResponse(options?.onNotFound ?? import_easy3.HttpStatus.NotFound, [(0, import_easy3.toResult)(e.reason ?? e.message)])).type(import_easy3.isError, (e) => toResponse(import_easy3.HttpStatus.InternalServerError, [(0, import_easy3.toResult)(e.message)])).type(import_easy3.isResults, (r) => toResponse(options?.onError ?? import_easy3.HttpStatus.BadRequest, r.results)).type(import_easy3.isResponse, (r) => toResponse(import_easy3.HttpStatus.InternalServerError, r.body.error?.errors)).type(import_easy3.isException, (e) => toResponse(options?.onError ?? import_easy3.HttpStatus.BadRequest, [(0, import_easy3.toResult)(e.reason ?? e.message)])).type(import_easy3.isText, (t) => toResponse(options?.onError ?? import_easy3.HttpStatus.BadRequest, [(0, import_easy3.toResult)((0, import_easy3.asString)(t))])).else(() => toResponse(import_easy3.HttpStatus.InternalServerError, [(0, import_easy3.toResult)("Unknown error")]));
79
+ };
80
+ var error = (e, req, res, _next) => {
81
+ let response;
82
+ (0, import_easy3.tryTo)(() => (0, import_easy3.toOriginatedError)(e)).map((oe) => toBody(oe)).accept((r) => response = r).accept((r) => import_easy3.ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : void 0).accept((r) => import_easy3.ctx.request.lastErrorStack = r.status.isServerError ? e.stack : void 0).recover(() => response).accept((r) => res.status(r.status.status).json(r.body));
83
+ };
84
+
85
+ // src/express/ExpressProvider.ts
86
+ var import_express = __toESM(require("express"));
87
+
88
+ // src/express/SecurityHandler.ts
89
+ var import_passport = __toESM(require("passport"));
90
+ var import_passport_jwt = require("passport-jwt");
91
+ var import_easy4 = require("@thisisagile/easy");
92
+ var checkLabCoat = () => (req, res, next) => next((0, import_easy4.ifFalse)(import_easy4.Environment.Dev.equals(import_easy4.ctx.env.name), authError(import_easy4.HttpStatus.Forbidden)));
93
+ var checkToken = () => import_passport.default.authenticate("jwt", { session: false, failWithError: true });
94
+ var checkScope = (scope) => (req, res, next) => next((0, import_easy4.ifFalse)(req.user?.scopes?.includes(scope.id), authError(import_easy4.HttpStatus.Forbidden)));
95
+ var checkUseCase = (uc) => (req, res, next) => next((0, import_easy4.ifFalse)(req.user?.usecases?.includes(uc.id), authError(import_easy4.HttpStatus.Forbidden)));
96
+ var wrapSecretOrKeyProvider = (p) => p ? (request, rawJwtToken, done) => p(request, rawJwtToken).then((t) => done(null, t)).catch((e) => done(e)) : void 0;
97
+ var security = ({ jwtStrategyOptions } = {}) => {
98
+ jwtStrategyOptions ??= {};
99
+ if ("secretOrKeyProvider" in jwtStrategyOptions)
100
+ jwtStrategyOptions.secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);
101
+ else if (!("secretOrKey" in jwtStrategyOptions))
102
+ jwtStrategyOptions.secretOrKey = import_easy4.ctx.env.get("tokenPublicKey");
103
+ const strategy = new import_passport_jwt.Strategy(
104
+ {
105
+ jwtFromRequest: import_passport_jwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
106
+ passReqToCallback: true,
107
+ ...jwtStrategyOptions
108
+ },
109
+ (req, payload, done) => {
110
+ import_easy4.ctx.request.token = payload;
111
+ import_easy4.ctx.request.jwt = import_passport_jwt.ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? "";
112
+ done(null, payload);
113
+ }
114
+ );
115
+ import_passport.default.use(strategy);
116
+ return import_passport.default.initialize();
117
+ };
118
+
119
+ // src/express/ExpressProvider.ts
120
+ var import_easy5 = require("@thisisagile/easy");
121
+ var ExpressProvider = class {
122
+ constructor(app = (0, import_express.default)()) {
123
+ this.app = app;
124
+ this.app.set("trust proxy", ["loopback", "linklocal", "uniquelocal"]);
125
+ }
126
+ use = (handler) => {
127
+ this.app.use(handler);
128
+ };
129
+ route = (service2, resource) => {
130
+ const { route, endpoints, middleware } = (0, import_easy5.routes)(resource);
131
+ const router = import_express.default.Router({ mergeParams: true });
132
+ if (!(0, import_easy5.isEmpty)(middleware))
133
+ router.all(route.route(service2.name), middleware);
134
+ endpoints.forEach(({ endpoint, verb, requires, middleware: middleware2 }) => {
135
+ console.log(verb.verb.code, route.route(service2.name));
136
+ router[verb.verb.toString()](
137
+ route.route(service2.name),
138
+ ...this.addSecurityMiddleware(requires),
139
+ ...middleware2,
140
+ this.handle(endpoint, verb.options, requires)
141
+ );
142
+ });
143
+ this.app.use(router);
144
+ };
145
+ listen = (port, message = `Service is listening on port ${port}.`) => {
146
+ this.app.listen(port, () => {
147
+ console.log(message);
148
+ });
149
+ };
150
+ addSecurityMiddleware(requires) {
151
+ const middleware = [];
152
+ if (requires.labCoat)
153
+ middleware.push(checkLabCoat());
154
+ if (requires.token)
155
+ middleware.push(checkToken());
156
+ if (requires.scope)
157
+ middleware.push(checkScope(requires.scope));
158
+ if (requires.uc)
159
+ middleware.push(checkUseCase(requires.uc));
160
+ return middleware;
161
+ }
162
+ handle = (endpoint, options, requires) => (req, res, next) => endpoint((0, import_easy5.toReq)(req)).then((r) => this.toResponse(res, r, (0, import_easy5.toVerbOptions)(options))).catch((error2) => next((0, import_easy5.toOriginatedError)(error2, options)));
163
+ toResponse(res, result, options) {
164
+ res.status(options.onOk.status);
165
+ res.type(options.type.code);
166
+ if (options.cache.enabled)
167
+ res.setHeader(options.cache.name, options.cache.value());
168
+ (this[options.type.name] ?? this.json)(res, result, options);
169
+ }
170
+ // Handling responses depending on content type
171
+ json(res, result, options) {
172
+ if (import_easy5.HttpStatus.NoContent.equals(options.onOk)) {
173
+ res.send();
174
+ } else {
175
+ res.json(import_easy5.rest.toData(options.onOk, (0, import_easy5.toList)(result), result?.total, result?.meta));
176
+ }
177
+ }
178
+ stream(res, result) {
179
+ res.end(result);
180
+ }
181
+ text(res, data) {
182
+ res.send(data);
183
+ }
184
+ };
185
+ var service = (name) => new import_easy5.Service(name, new ExpressProvider());
186
+
187
+ // src/express/NotFoundHandler.ts
188
+ var import_easy6 = require("@thisisagile/easy");
189
+ var notFound = (req, res, next) => {
190
+ next((0, import_easy6.toOriginatedError)(import_easy6.Exception.DoesNotExist));
191
+ };
192
+
193
+ // src/express/RequestContextHandler.ts
194
+ var import_easy7 = require("@thisisagile/easy");
195
+ var requestContext = (req, res, next) => import_easy7.ctx.request.create(() => next());
196
+
197
+ // src/types/NamespaceContext.ts
198
+ var import_cls_hooked = require("cls-hooked");
199
+ var import_easy8 = require("@thisisagile/easy");
200
+ var NamespaceContext = class extends import_easy8.BaseRequestContext {
201
+ namespace = (0, import_cls_hooked.createNamespace)("context");
202
+ get(key) {
203
+ return this.namespace.get(key);
204
+ }
205
+ set(key, value) {
206
+ return this.namespace.set(key, value);
207
+ }
208
+ create = (f) => this.namespace.run(f);
209
+ };
20
210
  // Annotate the CommonJS export names for ESM import in node:
21
211
  0 && (module.exports = {
22
- ...require("./express"),
23
- ...require("./types")
212
+ AuthError,
213
+ ExpressProvider,
214
+ NamespaceContext,
215
+ authError,
216
+ checkLabCoat,
217
+ checkScope,
218
+ checkToken,
219
+ checkUseCase,
220
+ correlation,
221
+ error,
222
+ isAuthError,
223
+ notFound,
224
+ requestContext,
225
+ security,
226
+ service
24
227
  });
25
228
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './express';\nexport * from './types';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,wBAAc,sBAAd;AACA,wBAAc,oBADd;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/express/AuthError.ts","../src/express/CorrelationHandler.ts","../src/express/ErrorHandler.ts","../src/express/ExpressProvider.ts","../src/express/SecurityHandler.ts","../src/express/NotFoundHandler.ts","../src/express/RequestContextHandler.ts","../src/types/NamespaceContext.ts"],"sourcesContent":["export * from './express';\nexport * from './types';\n","import { HttpStatus, isError } from '@thisisagile/easy';\n\nexport class AuthError extends Error {\n status: number;\n\n constructor({ name, status }: HttpStatus) {\n super(name);\n this.name = 'AuthenticationError';\n this.status = status;\n }\n}\n\nexport const authError = (status: HttpStatus): AuthError => new AuthError(status);\n\nexport const isAuthError = (e?: unknown): e is AuthError => isError(e) && e.name === 'AuthenticationError';\n","import express from 'express';\nimport { ctx, HttpHeader, toUuid } from '@thisisagile/easy';\n\nexport const correlation = (req: express.Request, res: express.Response, next: express.NextFunction): void => {\n res.setHeader(HttpHeader.Correlation, (ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid()));\n next();\n};\n","import express from 'express';\nimport { isAuthError } from './AuthError';\nimport {\n asString,\n choose,\n ctx,\n HttpStatus,\n isDoesNotExist,\n isError,\n isException,\n isResponse,\n isResults,\n isText,\n OriginatedError,\n Response,\n rest,\n Result,\n toHttpStatus,\n toOriginatedError,\n toResult,\n tryTo,\n} from '@thisisagile/easy';\n\nconst toResponse = (status: HttpStatus, errors: Result[] = []): Response => ({\n status,\n body: rest.toError(status, errors),\n});\n\nconst toBody = ({ origin, options }: OriginatedError): Response => {\n return (\n choose(origin)\n .type(isAuthError, ae => toResponse(toHttpStatus(ae.status), [toResult(ae.message)]))\n .type(isDoesNotExist, e => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)]))\n // This service breaks with an error\n .type(isError, e => toResponse(HttpStatus.InternalServerError, [toResult(e.message)]))\n // This service fails\n .type(isResults, r => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results))\n // Underlying service fails\n .type(isResponse, r => toResponse(HttpStatus.InternalServerError, r.body.error?.errors))\n .type(isException, e => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)]))\n // This service fails with a string\n .type(isText, t => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))]))\n .else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]))\n );\n};\n\nexport const error = (e: Error, req: express.Request, res: express.Response, _next: express.NextFunction): void => {\n let response: Response;\n tryTo(() => toOriginatedError(e))\n .map(oe => toBody(oe))\n .accept(r => (response = r))\n .accept(r => (ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : undefined))\n .accept(r => (ctx.request.lastErrorStack = r.status.isServerError ? e.stack : undefined))\n .recover(() => response)\n .accept(r => res.status(r.status.status).json(r.body));\n};\n","import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n HttpStatus,\n isEmpty,\n PageList,\n Resource,\n rest,\n Route,\n RouteRequires,\n routes,\n Service,\n toList,\n toOriginatedError,\n toReq,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n","import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n","import { NextFunction, Request, Response } from 'express';\nimport { Exception, toOriginatedError } from '@thisisagile/easy';\n\nexport const notFound = (req: Request, res: Response, next: NextFunction): void => {\n next(toOriginatedError(Exception.DoesNotExist));\n};\n","import express from 'express';\nimport { ctx } from '@thisisagile/easy';\n\nexport const requestContext = (req: express.Request, res: express.Response, next: express.NextFunction): void => ctx.request.create(() => next());\n","import { createNamespace } from 'cls-hooked';\nimport { BaseRequestContext } from '@thisisagile/easy';\n\nexport class NamespaceContext extends BaseRequestContext {\n protected readonly namespace = createNamespace('context');\n\n public get<T>(key: string): T {\n return this.namespace.get(key) as T;\n }\n\n public set<T>(key: string, value: T): T {\n return this.namespace.set(key, value);\n }\n\n public readonly create = (f: () => void): void => this.namespace.run(f);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAoC;AAE7B,IAAM,YAAN,cAAw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service","middleware","error","import_easy","import_easy","import_easy"]}
@@ -1,6 +1,7 @@
1
+ // src/types/NamespaceContext.ts
1
2
  import { createNamespace } from "cls-hooked";
2
3
  import { BaseRequestContext } from "@thisisagile/easy";
3
- class NamespaceContext extends BaseRequestContext {
4
+ var NamespaceContext = class extends BaseRequestContext {
4
5
  namespace = createNamespace("context");
5
6
  get(key) {
6
7
  return this.namespace.get(key);
@@ -9,7 +10,7 @@ class NamespaceContext extends BaseRequestContext {
9
10
  return this.namespace.set(key, value);
10
11
  }
11
12
  create = (f) => this.namespace.run(f);
12
- }
13
+ };
13
14
  export {
14
15
  NamespaceContext
15
16
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/NamespaceContext.ts"],"sourcesContent":["import { createNamespace } from 'cls-hooked';\nimport { BaseRequestContext } from '@thisisagile/easy';\n\nexport class NamespaceContext extends BaseRequestContext {\n protected readonly namespace = createNamespace('context');\n\n public get<T>(key: string): T {\n return this.namespace.get(key) as T;\n }\n\n public set<T>(key: string, value: T): T {\n return this.namespace.set(key, value);\n }\n\n public readonly create = (f: () => void): void => this.namespace.run(f);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AAE5B,MAAM,yBAAyB,mBAAmB;AAAA,EACpC,YAAY,gBAAgB,SAAS;AAAA,EAEjD,IAAO,KAAgB;AAC5B,WAAO,KAAK,UAAU,IAAI,GAAG;AAAA,EAC/B;AAAA,EAEO,IAAO,KAAa,OAAa;AACtC,WAAO,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACtC;AAAA,EAEgB,SAAS,CAAC,MAAwB,KAAK,UAAU,IAAI,CAAC;AACxE;","names":[]}
1
+ {"version":3,"sources":["../../src/types/NamespaceContext.ts"],"sourcesContent":["import { createNamespace } from 'cls-hooked';\nimport { BaseRequestContext } from '@thisisagile/easy';\n\nexport class NamespaceContext extends BaseRequestContext {\n protected readonly namespace = createNamespace('context');\n\n public get<T>(key: string): T {\n return this.namespace.get(key) as T;\n }\n\n public set<T>(key: string, value: T): T {\n return this.namespace.set(key, value);\n }\n\n public readonly create = (f: () => void): void => this.namespace.run(f);\n}\n"],"mappings":";AAAA,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AAE5B,IAAM,mBAAN,cAA+B,mBAAmB;AAAA,EACpC,YAAY,gBAAgB,SAAS;AAAA,EAEjD,IAAO,KAAgB;AAC5B,WAAO,KAAK,UAAU,IAAI,GAAG;AAAA,EAC/B;AAAA,EAEO,IAAO,KAAa,OAAa;AACtC,WAAO,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACtC;AAAA,EAEgB,SAAS,CAAC,MAAwB,KAAK,UAAU,IAAI,CAAC;AACxE;","names":[]}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@thisisagile/easy-express",
3
- "version": "15.26.1",
3
+ "version": "15.27.0",
4
4
  "description": "Straightforward library for building domain-driven microservice architectures",
5
5
  "author": "Sander Hoogendoorn",
6
6
  "license": "MIT",
7
7
  "main": "dist/index.js",
8
8
  "module": "dist/index.mjs",
9
- "types": "dist/index",
9
+ "types": "dist/index.d.ts",
10
10
  "repository": {
11
11
  "type": "git",
12
12
  "url": "git@github.com:thisisagile/easy.git"
@@ -25,6 +25,7 @@
25
25
  "test": "yarn g:jest --coverage",
26
26
  "prepack": "yarn g:copy-readme"
27
27
  },
28
+ "sideEffects": false,
28
29
  "files": [
29
30
  "dist",
30
31
  "src"
@@ -33,7 +34,7 @@
33
34
  "access": "public"
34
35
  },
35
36
  "devDependencies": {
36
- "@thisisagile/easy-test": "15.26.1",
37
+ "@thisisagile/easy-test": "15.27.0",
37
38
  "@types/cls-hooked": "^4.3.8",
38
39
  "@types/form-urlencoded": "^4.4.0",
39
40
  "@types/jsonwebtoken": "^9.0.6",
@@ -43,7 +44,7 @@
43
44
  "@types/validator": "^13.11.9"
44
45
  },
45
46
  "dependencies": {
46
- "@thisisagile/easy": "^15.26.1",
47
+ "@thisisagile/easy": "^15.27.0",
47
48
  "@types/express": "^4.17.21",
48
49
  "cls-hooked": "^4.2.2",
49
50
  "express": "^4.19.2",
@@ -1,43 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var AuthError_exports = {};
20
- __export(AuthError_exports, {
21
- AuthError: () => AuthError,
22
- authError: () => authError,
23
- isAuthError: () => isAuthError
24
- });
25
- module.exports = __toCommonJS(AuthError_exports);
26
- var import_easy = require("@thisisagile/easy");
27
- class AuthError extends Error {
28
- status;
29
- constructor({ name, status }) {
30
- super(name);
31
- this.name = "AuthenticationError";
32
- this.status = status;
33
- }
34
- }
35
- const authError = (status) => new AuthError(status);
36
- const isAuthError = (e) => (0, import_easy.isError)(e) && e.name === "AuthenticationError";
37
- // Annotate the CommonJS export names for ESM import in node:
38
- 0 && (module.exports = {
39
- AuthError,
40
- authError,
41
- isAuthError
42
- });
43
- //# sourceMappingURL=AuthError.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/AuthError.ts"],"sourcesContent":["import { HttpStatus, isError } from '@thisisagile/easy';\n\nexport class AuthError extends Error {\n status: number;\n\n constructor({ name, status }: HttpStatus) {\n super(name);\n this.name = 'AuthenticationError';\n this.status = status;\n }\n}\n\nexport const authError = (status: HttpStatus): AuthError => new AuthError(status);\n\nexport const isAuthError = (e?: unknown): e is AuthError => isError(e) && e.name === 'AuthenticationError';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAoC;AAE7B,MAAM,kBAAkB,MAAM;AAAA,EACnC;AAAA,EAEA,YAAY,EAAE,MAAM,OAAO,GAAe;AACxC,UAAM,IAAI;AACV,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEO,MAAM,YAAY,CAAC,WAAkC,IAAI,UAAU,MAAM;AAEzE,MAAM,cAAc,CAAC,UAAgC,qBAAQ,CAAC,KAAK,EAAE,SAAS;","names":[]}
@@ -1,33 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var CorrelationHandler_exports = {};
20
- __export(CorrelationHandler_exports, {
21
- correlation: () => correlation
22
- });
23
- module.exports = __toCommonJS(CorrelationHandler_exports);
24
- var import_easy = require("@thisisagile/easy");
25
- const correlation = (req, res, next) => {
26
- res.setHeader(import_easy.HttpHeader.Correlation, import_easy.ctx.request.correlationId = req?.header(import_easy.HttpHeader.Correlation) ?? (0, import_easy.toUuid)());
27
- next();
28
- };
29
- // Annotate the CommonJS export names for ESM import in node:
30
- 0 && (module.exports = {
31
- correlation
32
- });
33
- //# sourceMappingURL=CorrelationHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/CorrelationHandler.ts"],"sourcesContent":["import express from 'express';\nimport { ctx, HttpHeader, toUuid } from '@thisisagile/easy';\n\nexport const correlation = (req: express.Request, res: express.Response, next: express.NextFunction): void => {\n res.setHeader(HttpHeader.Correlation, (ctx.request.correlationId = req?.header(HttpHeader.Correlation) ?? toUuid()));\n next();\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,kBAAwC;AAEjC,MAAM,cAAc,CAAC,KAAsB,KAAuB,SAAqC;AAC5G,MAAI,UAAU,uBAAW,aAAc,gBAAI,QAAQ,gBAAgB,KAAK,OAAO,uBAAW,WAAW,SAAK,oBAAO,CAAE;AACnH,OAAK;AACP;","names":[]}
@@ -1,41 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var ErrorHandler_exports = {};
20
- __export(ErrorHandler_exports, {
21
- error: () => error
22
- });
23
- module.exports = __toCommonJS(ErrorHandler_exports);
24
- var import_AuthError = require("./AuthError");
25
- var import_easy = require("@thisisagile/easy");
26
- const toResponse = (status, errors = []) => ({
27
- status,
28
- body: import_easy.rest.toError(status, errors)
29
- });
30
- const toBody = ({ origin, options }) => {
31
- return (0, import_easy.choose)(origin).type(import_AuthError.isAuthError, (ae) => toResponse((0, import_easy.toHttpStatus)(ae.status), [(0, import_easy.toResult)(ae.message)])).type(import_easy.isDoesNotExist, (e) => toResponse(options?.onNotFound ?? import_easy.HttpStatus.NotFound, [(0, import_easy.toResult)(e.reason ?? e.message)])).type(import_easy.isError, (e) => toResponse(import_easy.HttpStatus.InternalServerError, [(0, import_easy.toResult)(e.message)])).type(import_easy.isResults, (r) => toResponse(options?.onError ?? import_easy.HttpStatus.BadRequest, r.results)).type(import_easy.isResponse, (r) => toResponse(import_easy.HttpStatus.InternalServerError, r.body.error?.errors)).type(import_easy.isException, (e) => toResponse(options?.onError ?? import_easy.HttpStatus.BadRequest, [(0, import_easy.toResult)(e.reason ?? e.message)])).type(import_easy.isText, (t) => toResponse(options?.onError ?? import_easy.HttpStatus.BadRequest, [(0, import_easy.toResult)((0, import_easy.asString)(t))])).else(() => toResponse(import_easy.HttpStatus.InternalServerError, [(0, import_easy.toResult)("Unknown error")]));
32
- };
33
- const error = (e, req, res, _next) => {
34
- let response;
35
- (0, import_easy.tryTo)(() => (0, import_easy.toOriginatedError)(e)).map((oe) => toBody(oe)).accept((r) => response = r).accept((r) => import_easy.ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : void 0).accept((r) => import_easy.ctx.request.lastErrorStack = r.status.isServerError ? e.stack : void 0).recover(() => response).accept((r) => res.status(r.status.status).json(r.body));
36
- };
37
- // Annotate the CommonJS export names for ESM import in node:
38
- 0 && (module.exports = {
39
- error
40
- });
41
- //# sourceMappingURL=ErrorHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/ErrorHandler.ts"],"sourcesContent":["import express from 'express';\nimport { isAuthError } from './AuthError';\nimport {\n asString,\n choose,\n ctx,\n HttpStatus,\n isDoesNotExist,\n isError,\n isException,\n isResponse,\n isResults,\n isText,\n OriginatedError,\n Response,\n rest,\n Result,\n toHttpStatus,\n toOriginatedError,\n toResult,\n tryTo,\n} from '@thisisagile/easy';\n\nconst toResponse = (status: HttpStatus, errors: Result[] = []): Response => ({\n status,\n body: rest.toError(status, errors),\n});\n\nconst toBody = ({ origin, options }: OriginatedError): Response => {\n return (\n choose(origin)\n .type(isAuthError, ae => toResponse(toHttpStatus(ae.status), [toResult(ae.message)]))\n .type(isDoesNotExist, e => toResponse(options?.onNotFound ?? HttpStatus.NotFound, [toResult(e.reason ?? e.message)]))\n // This service breaks with an error\n .type(isError, e => toResponse(HttpStatus.InternalServerError, [toResult(e.message)]))\n // This service fails\n .type(isResults, r => toResponse(options?.onError ?? HttpStatus.BadRequest, r.results))\n // Underlying service fails\n .type(isResponse, r => toResponse(HttpStatus.InternalServerError, r.body.error?.errors))\n .type(isException, e => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(e.reason ?? e.message)]))\n // This service fails with a string\n .type(isText, t => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(t))]))\n .else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]))\n );\n};\n\nexport const error = (e: Error, req: express.Request, res: express.Response, _next: express.NextFunction): void => {\n let response: Response;\n tryTo(() => toOriginatedError(e))\n .map(oe => toBody(oe))\n .accept(r => (response = r))\n .accept(r => (ctx.request.lastError = r.status.isServerError ? r.body.error?.errors[0]?.message : undefined))\n .accept(r => (ctx.request.lastErrorStack = r.status.isServerError ? e.stack : undefined))\n .recover(() => response)\n .accept(r => res.status(r.status.status).json(r.body));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAA4B;AAC5B,kBAmBO;AAEP,MAAM,aAAa,CAAC,QAAoB,SAAmB,CAAC,OAAiB;AAAA,EAC3E;AAAA,EACA,MAAM,iBAAK,QAAQ,QAAQ,MAAM;AACnC;AAEA,MAAM,SAAS,CAAC,EAAE,QAAQ,QAAQ,MAAiC;AACjE,aACE,oBAAO,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C;AACzD;","names":[]}
@@ -1,108 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var ExpressProvider_exports = {};
30
- __export(ExpressProvider_exports, {
31
- ExpressProvider: () => ExpressProvider,
32
- service: () => service
33
- });
34
- module.exports = __toCommonJS(ExpressProvider_exports);
35
- var import_express = __toESM(require("express"));
36
- var import_SecurityHandler = require("./SecurityHandler");
37
- var import_easy = require("@thisisagile/easy");
38
- class ExpressProvider {
39
- constructor(app = (0, import_express.default)()) {
40
- this.app = app;
41
- this.app.set("trust proxy", ["loopback", "linklocal", "uniquelocal"]);
42
- }
43
- use = (handler) => {
44
- this.app.use(handler);
45
- };
46
- route = (service2, resource) => {
47
- const { route, endpoints, middleware } = (0, import_easy.routes)(resource);
48
- const router = import_express.default.Router({ mergeParams: true });
49
- if (!(0, import_easy.isEmpty)(middleware))
50
- router.all(route.route(service2.name), middleware);
51
- endpoints.forEach(({ endpoint, verb, requires, middleware: middleware2 }) => {
52
- console.log(verb.verb.code, route.route(service2.name));
53
- router[verb.verb.toString()](
54
- route.route(service2.name),
55
- ...this.addSecurityMiddleware(requires),
56
- ...middleware2,
57
- this.handle(endpoint, verb.options, requires)
58
- );
59
- });
60
- this.app.use(router);
61
- };
62
- listen = (port, message = `Service is listening on port ${port}.`) => {
63
- this.app.listen(port, () => {
64
- console.log(message);
65
- });
66
- };
67
- addSecurityMiddleware(requires) {
68
- const middleware = [];
69
- if (requires.labCoat)
70
- middleware.push((0, import_SecurityHandler.checkLabCoat)());
71
- if (requires.token)
72
- middleware.push((0, import_SecurityHandler.checkToken)());
73
- if (requires.scope)
74
- middleware.push((0, import_SecurityHandler.checkScope)(requires.scope));
75
- if (requires.uc)
76
- middleware.push((0, import_SecurityHandler.checkUseCase)(requires.uc));
77
- return middleware;
78
- }
79
- handle = (endpoint, options, requires) => (req, res, next) => endpoint((0, import_easy.toReq)(req)).then((r) => this.toResponse(res, r, (0, import_easy.toVerbOptions)(options))).catch((error) => next((0, import_easy.toOriginatedError)(error, options)));
80
- toResponse(res, result, options) {
81
- res.status(options.onOk.status);
82
- res.type(options.type.code);
83
- if (options.cache.enabled)
84
- res.setHeader(options.cache.name, options.cache.value());
85
- (this[options.type.name] ?? this.json)(res, result, options);
86
- }
87
- // Handling responses depending on content type
88
- json(res, result, options) {
89
- if (import_easy.HttpStatus.NoContent.equals(options.onOk)) {
90
- res.send();
91
- } else {
92
- res.json(import_easy.rest.toData(options.onOk, (0, import_easy.toList)(result), result?.total, result?.meta));
93
- }
94
- }
95
- stream(res, result) {
96
- res.end(result);
97
- }
98
- text(res, data) {
99
- res.send(data);
100
- }
101
- }
102
- const service = (name) => new import_easy.Service(name, new ExpressProvider());
103
- // Annotate the CommonJS export names for ESM import in node:
104
- 0 && (module.exports = {
105
- ExpressProvider,
106
- service
107
- });
108
- //# sourceMappingURL=ExpressProvider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/ExpressProvider.ts"],"sourcesContent":["import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';\nimport { checkLabCoat, checkScope, checkToken, checkUseCase } from './SecurityHandler';\nimport {\n AppProvider,\n Endpoint,\n Handler,\n HttpStatus,\n isEmpty,\n PageList,\n Resource,\n rest,\n Route,\n RouteRequires,\n routes,\n Service,\n toList,\n toOriginatedError,\n toReq,\n toVerbOptions,\n VerbOptions,\n} from '@thisisagile/easy';\n\nexport type ExpressVerb = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\nexport class ExpressProvider implements AppProvider {\n constructor(protected app: Express = express()) {\n this.app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);\n }\n\n use = (handler: Handler): void => {\n this.app.use(handler);\n };\n\n route = (service: Service, resource: Resource): void => {\n const { route, endpoints, middleware } = routes(resource);\n const router = express.Router({ mergeParams: true });\n if (!isEmpty(middleware)) router.all(route.route(service.name), middleware);\n\n endpoints.forEach(({ endpoint, verb, requires, middleware }: Route) => {\n console.log(verb.verb.code, route.route(service.name));\n router[verb.verb.toString() as ExpressVerb](\n route.route(service.name),\n ...this.addSecurityMiddleware(requires),\n ...middleware,\n this.handle(endpoint, verb.options, requires)\n );\n });\n\n this.app.use(router);\n };\n\n listen = (port: number, message = `Service is listening on port ${port}.`): void => {\n this.app.listen(port, () => {\n console.log(message);\n });\n };\n\n protected addSecurityMiddleware(requires: RouteRequires): RequestHandler[] {\n const middleware: RequestHandler[] = [];\n if (requires.labCoat) middleware.push(checkLabCoat());\n if (requires.token) middleware.push(checkToken());\n if (requires.scope) middleware.push(checkScope(requires.scope));\n if (requires.uc) middleware.push(checkUseCase(requires.uc));\n return middleware;\n }\n\n protected handle =\n (endpoint: Endpoint, options?: VerbOptions, requires?: RouteRequires): RequestHandler =>\n (req: Request, res: Response, next: NextFunction) =>\n endpoint(toReq(req))\n .then((r: any) => this.toResponse(res, r, toVerbOptions(options)))\n .catch(error => next(toOriginatedError(error, options)));\n\n protected toResponse(res: Response, result: unknown, options: Required<VerbOptions>): void {\n res.status(options.onOk.status);\n res.type(options.type.code);\n if (options.cache.enabled) res.setHeader(options.cache.name, options.cache.value());\n\n ((this as any)[options.type.name] ?? this.json)(res, result, options);\n }\n\n // Handling responses depending on content type\n\n protected json(res: Response, result: unknown, options: Required<VerbOptions>): void {\n if (HttpStatus.NoContent.equals(options.onOk)) {\n res.send();\n } else {\n res.json(rest.toData(options.onOk, toList<any>(result), (result as PageList<any>)?.total, (result as PageList<any>)?.meta));\n }\n }\n\n protected stream(res: Response, result: unknown): void {\n res.end(result);\n }\n\n protected text(res: Response, data: unknown): void {\n res.send(data);\n }\n}\n\nexport const service = (name: string): Service => new Service(name, new ExpressProvider());\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAkF;AAClF,6BAAmE;AACnE,kBAkBO;AAIA,MAAM,gBAAuC;AAAA,EAClD,YAAsB,UAAe,eAAAA,SAAQ,GAAG;AAA1B;AACpB,SAAK,IAAI,IAAI,eAAe,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,EACtE;AAAA,EAEA,MAAM,CAAC,YAA2B;AAChC,SAAK,IAAI,IAAI,OAAO;AAAA,EACtB;AAAA,EAEA,QAAQ,CAACC,UAAkB,aAA6B;AACtD,UAAM,EAAE,OAAO,WAAW,WAAW,QAAI,oBAAO,QAAQ;AACxD,UAAM,SAAS,eAAAD,QAAQ,OAAO,EAAE,aAAa,KAAK,CAAC;AACnD,QAAI,KAAC,qBAAQ,UAAU;AAAG,aAAO,IAAI,MAAM,MAAMC,SAAQ,IAAI,GAAG,UAAU;AAE1E,cAAU,QAAQ,CAAC,EAAE,UAAU,MAAM,UAAU,YAAAC,YAAW,MAAa;AACrE,cAAQ,IAAI,KAAK,KA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,KAAK,QAAQ,OAAO;AAAA,EACtE;AAAA;AAAA,EAIU,KAAK,KAAe,QAAiB,SAAsC;AACnF,QAAI,uBAAW,UAAU,OAAO,QAAQ,IAAI,GAAG;AAC7C,UAAI,KAAK;AAAA,IACX,OAAO;AACL,UAAI,KAAK,iBAAK,OAAO,QAAQ,UAAM,oBAAY,MAAM,GAAI,QAA0B,OAAQ,QAA0B,IAAI,CAAC;AAAA,IAC5H;AAAA,EACF;AAAA,EAEU,OAAO,KAAe,QAAuB;AACrD,QAAI,IAAI,MAAM;AAAA,EAChB;AAAA,EAEU,KAAK,KAAe,MAAqB;AACjD,QAAI,KAAK,IAAI;AAAA,EACf;AACF;AAEO,MAAM,UAAU,CAAC,SAA0B,IAAI,oBAAQ,MAAM,IAAI,gBAAgB,CAAC;","names":["express","service","middleware"]}
@@ -1,32 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var NotFoundHandler_exports = {};
20
- __export(NotFoundHandler_exports, {
21
- notFound: () => notFound
22
- });
23
- module.exports = __toCommonJS(NotFoundHandler_exports);
24
- var import_easy = require("@thisisagile/easy");
25
- const notFound = (req, res, next) => {
26
- next((0, import_easy.toOriginatedError)(import_easy.Exception.DoesNotExist));
27
- };
28
- // Annotate the CommonJS export names for ESM import in node:
29
- 0 && (module.exports = {
30
- notFound
31
- });
32
- //# sourceMappingURL=NotFoundHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/NotFoundHandler.ts"],"sourcesContent":["import { NextFunction, Request, Response } from 'express';\nimport { Exception, toOriginatedError } from '@thisisagile/easy';\n\nexport const notFound = (req: Request, res: Response, next: NextFunction): void => {\n next(toOriginatedError(Exception.DoesNotExist));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,kBAA6C;AAEtC,MAAM,WAAW,CAAC,KAAc,KAAe,SAA6B;AACjF,WAAK,+BAAkB,sBAAU,YAAY,CAAC;AAChD;","names":[]}
@@ -1,30 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var RequestContextHandler_exports = {};
20
- __export(RequestContextHandler_exports, {
21
- requestContext: () => requestContext
22
- });
23
- module.exports = __toCommonJS(RequestContextHandler_exports);
24
- var import_easy = require("@thisisagile/easy");
25
- const requestContext = (req, res, next) => import_easy.ctx.request.create(() => next());
26
- // Annotate the CommonJS export names for ESM import in node:
27
- 0 && (module.exports = {
28
- requestContext
29
- });
30
- //# sourceMappingURL=RequestContextHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/RequestContextHandler.ts"],"sourcesContent":["import express from 'express';\nimport { ctx } from '@thisisagile/easy';\n\nexport const requestContext = (req: express.Request, res: express.Response, next: express.NextFunction): void => ctx.request.create(() => next());\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,kBAAoB;AAEb,MAAM,iBAAiB,CAAC,KAAsB,KAAuB,SAAqC,gBAAI,QAAQ,OAAO,MAAM,KAAK,CAAC;","names":[]}
@@ -1,76 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var SecurityHandler_exports = {};
30
- __export(SecurityHandler_exports, {
31
- checkLabCoat: () => checkLabCoat,
32
- checkScope: () => checkScope,
33
- checkToken: () => checkToken,
34
- checkUseCase: () => checkUseCase,
35
- security: () => security
36
- });
37
- module.exports = __toCommonJS(SecurityHandler_exports);
38
- var import_passport = __toESM(require("passport"));
39
- var import_passport_jwt = require("passport-jwt");
40
- var import_AuthError = require("./AuthError");
41
- var import_easy = require("@thisisagile/easy");
42
- const checkLabCoat = () => (req, res, next) => next((0, import_easy.ifFalse)(import_easy.Environment.Dev.equals(import_easy.ctx.env.name), (0, import_AuthError.authError)(import_easy.HttpStatus.Forbidden)));
43
- const checkToken = () => import_passport.default.authenticate("jwt", { session: false, failWithError: true });
44
- const checkScope = (scope) => (req, res, next) => next((0, import_easy.ifFalse)(req.user?.scopes?.includes(scope.id), (0, import_AuthError.authError)(import_easy.HttpStatus.Forbidden)));
45
- const checkUseCase = (uc) => (req, res, next) => next((0, import_easy.ifFalse)(req.user?.usecases?.includes(uc.id), (0, import_AuthError.authError)(import_easy.HttpStatus.Forbidden)));
46
- const wrapSecretOrKeyProvider = (p) => p ? (request, rawJwtToken, done) => p(request, rawJwtToken).then((t) => done(null, t)).catch((e) => done(e)) : void 0;
47
- const security = ({ jwtStrategyOptions } = {}) => {
48
- jwtStrategyOptions ??= {};
49
- if ("secretOrKeyProvider" in jwtStrategyOptions)
50
- jwtStrategyOptions.secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);
51
- else if (!("secretOrKey" in jwtStrategyOptions))
52
- jwtStrategyOptions.secretOrKey = import_easy.ctx.env.get("tokenPublicKey");
53
- const strategy = new import_passport_jwt.Strategy(
54
- {
55
- jwtFromRequest: import_passport_jwt.ExtractJwt.fromAuthHeaderAsBearerToken(),
56
- passReqToCallback: true,
57
- ...jwtStrategyOptions
58
- },
59
- (req, payload, done) => {
60
- import_easy.ctx.request.token = payload;
61
- import_easy.ctx.request.jwt = import_passport_jwt.ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? "";
62
- done(null, payload);
63
- }
64
- );
65
- import_passport.default.use(strategy);
66
- return import_passport.default.initialize();
67
- };
68
- // Annotate the CommonJS export names for ESM import in node:
69
- 0 && (module.exports = {
70
- checkLabCoat,
71
- checkScope,
72
- checkToken,
73
- checkUseCase,
74
- security
75
- });
76
- //# sourceMappingURL=SecurityHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/SecurityHandler.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport passport from 'passport';\nimport { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';\nimport type { SecretOrKeyProvider, StrategyOptionsWithRequest } from 'passport-jwt';\nimport type { Algorithm } from 'jsonwebtoken';\nimport { authError } from './AuthError';\nimport { ctx, Environment, HttpStatus, ifFalse } from '@thisisagile/easy';\nimport type { Scope, UseCase } from '@thisisagile/easy';\n\ntype EasySecretOrKeyProvider = (request: Request, rawJwtToken: any) => Promise<string | Buffer>;\n\nexport interface SecurityOptions {\n /** Configuration for verifying JWTs */\n jwtStrategyOptions?: {\n /** The secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature.\n * REQUIRED unless secretOrKeyProvider is provided. Defaults to JWT_PUBLIC_KEY from the system environment. */\n secretOrKey?: string | Buffer;\n\n /** Should return a secret (symmetric) or PEM-encoded public key (asymmetric) for the given key and request combination.\n * REQUIRED unless secretOrKey is provided. Note it is up to the implementer to decode rawJwtToken. */\n secretOrKeyProvider?: EasySecretOrKeyProvider;\n\n /** If defined, the token issuer (iss) will be verified against this value. */\n issuer?: string;\n\n /** If defined, the token audience (aud) will be verified against this value. */\n audience?: string;\n\n /** If defined, the token algorithm (alg) must be in this list. */\n algorithms?: Algorithm[];\n };\n}\n\nexport const checkLabCoat = (): RequestHandler => (req, res, next) => next(ifFalse(Environment.Dev.equals(ctx.env.name), authError(HttpStatus.Forbidden)));\n\nexport const checkToken = (): RequestHandler => passport.authenticate('jwt', { session: false, failWithError: true });\n\nexport const checkScope =\n (scope: Scope): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.scopes?.includes(scope.id), authError(HttpStatus.Forbidden)));\n\nexport const checkUseCase =\n (uc: UseCase): RequestHandler =>\n (req, res, next) =>\n next(ifFalse((req.user as any)?.usecases?.includes(uc.id), authError(HttpStatus.Forbidden)));\n\nconst wrapSecretOrKeyProvider = (p?: EasySecretOrKeyProvider): SecretOrKeyProvider | undefined =>\n p\n ? (request, rawJwtToken, done) =>\n p(request, rawJwtToken)\n .then(t => done(null, t))\n .catch(e => done(e))\n : undefined;\n\nexport const security = ({ jwtStrategyOptions }: SecurityOptions = {}): ((req: Request, res: Response, next: NextFunction) => void) => {\n jwtStrategyOptions ??= {};\n if ('secretOrKeyProvider' in jwtStrategyOptions)\n (jwtStrategyOptions as any).secretOrKeyProvider = wrapSecretOrKeyProvider(jwtStrategyOptions.secretOrKeyProvider);\n else if (!('secretOrKey' in jwtStrategyOptions)) jwtStrategyOptions.secretOrKey = ctx.env.get('tokenPublicKey') as string;\n\n const strategy = new JwtStrategy(\n {\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n passReqToCallback: true,\n ...jwtStrategyOptions,\n } as StrategyOptionsWithRequest,\n (req: Request, payload: any, done: (err: any, user: any) => void) => {\n ctx.request.token = payload;\n ctx.request.jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req) ?? '';\n done(null, payload);\n }\n );\n\n passport.use(strategy);\n return passport.initialize();\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,sBAAqB;AACrB,0BAAoD;AAGpD,uBAA0B;AAC1B,kBAAsD;AA2B/C,MAAM,eAAe,MAAsB,CAAC,KAAK,KAAK,SAAS,SAAK,qBAAQ,wBAAY,IAAI,OAAO,gBAAI,IAAI,IAAI,OAAG,4BAAU,uBAAW,SAAS,CAAC,CAAC;AAElJ,MAAM,aAAa,MAAsB,gBAAAA,QAAS,aAAa,OAAO,EAAE,SAAS,OAAO,eAAe,KAAK,CAAC;AAE7G,MAAM,aACX,CAAC,UACD,CAAC,KAAK,KAAK,SACT,SAAK,qBAAS,IAAI,MAAc,QAAQ,SAAS,MAAM,EAAE,OAAG,4BAAU,uBAAW,SAAS,CAAC,CAAC;AAEzF,MAAM,eACX,CAAC,OACD,CAAC,KAAK,KAAK,SACT,SAAK,qBAAS,IAAI,MAAc,UAAU,SAAS,GAAG,EAAE,OAAG,4BAAU,uBAAW,SAAS,CAAC,CAAC;AAE/F,MAAM,0BAA0B,CAAC,MAC/B,IACI,CAAC,SAAS,aAAa,SACrB,EAAE,SAAS,WAAW,EACnB,KAAK,OAAK,KAAK,MAAM,CAAC,CAAC,EACvB,MAAM,OAAK,KAAK,CAAC,CAAC,IACvB;AAEC,MAAM,WAAW,CAAC,EAAE,mBAAmB,IAAqB,CAAC,MAAmE;AACrI,yBAAuB,CAAC;AACxB,MAAI,yBAAyB;AAC3B,IAAC,mBAA2B,sBAAsB,wBAAwB,mBAAmB,mBAAmB;AAAA,WACzG,EAAE,iBAAiB;AAAqB,uBAAmB,cAAc,gBAAI,IAAI,IAAI,gBAAgB;AAE9G,QAAM,WAAW,IAAI,oBAAAC;AAAA,IACnB;AAAA,MACE,gBAAgB,+BAAW,4BAA4B;AAAA,MACvD,mBAAmB;AAAA,MACnB,GAAG;AAAA,IACL;AAAA,IACA,CAAC,KAAc,SAAc,SAAwC;AACnE,sBAAI,QAAQ,QAAQ;AACpB,sBAAI,QAAQ,MAAM,+BAAW,4BAA4B,EAAE,GAAG,KAAK;AACnE,WAAK,MAAM,OAAO;AAAA,IACpB;AAAA,EACF;AAEA,kBAAAD,QAAS,IAAI,QAAQ;AACrB,SAAO,gBAAAA,QAAS,WAAW;AAC7B;","names":["passport","JwtStrategy"]}
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
- var express_exports = {};
17
- module.exports = __toCommonJS(express_exports);
18
- __reExport(express_exports, require("./AuthError"), module.exports);
19
- __reExport(express_exports, require("./CorrelationHandler"), module.exports);
20
- __reExport(express_exports, require("./ErrorHandler"), module.exports);
21
- __reExport(express_exports, require("./ExpressProvider"), module.exports);
22
- __reExport(express_exports, require("./NotFoundHandler"), module.exports);
23
- __reExport(express_exports, require("./RequestContextHandler"), module.exports);
24
- __reExport(express_exports, require("./SecurityHandler"), module.exports);
25
- // Annotate the CommonJS export names for ESM import in node:
26
- 0 && (module.exports = {
27
- ...require("./AuthError"),
28
- ...require("./CorrelationHandler"),
29
- ...require("./ErrorHandler"),
30
- ...require("./ExpressProvider"),
31
- ...require("./NotFoundHandler"),
32
- ...require("./RequestContextHandler"),
33
- ...require("./SecurityHandler")
34
- });
35
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/express/index.ts"],"sourcesContent":["export * from './AuthError';\nexport * from './CorrelationHandler';\nexport * from './ErrorHandler';\nexport * from './ExpressProvider';\nexport * from './NotFoundHandler';\nexport * from './RequestContextHandler';\nexport * from './SecurityHandler';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,4BAAc,wBAAd;AACA,4BAAc,iCADd;AAEA,4BAAc,2BAFd;AAGA,4BAAc,8BAHd;AAIA,4BAAc,8BAJd;AAKA,4BAAc,oCALd;AAMA,4BAAc,8BANd;","names":[]}
@@ -1,40 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var NamespaceContext_exports = {};
20
- __export(NamespaceContext_exports, {
21
- NamespaceContext: () => NamespaceContext
22
- });
23
- module.exports = __toCommonJS(NamespaceContext_exports);
24
- var import_cls_hooked = require("cls-hooked");
25
- var import_easy = require("@thisisagile/easy");
26
- class NamespaceContext extends import_easy.BaseRequestContext {
27
- namespace = (0, import_cls_hooked.createNamespace)("context");
28
- get(key) {
29
- return this.namespace.get(key);
30
- }
31
- set(key, value) {
32
- return this.namespace.set(key, value);
33
- }
34
- create = (f) => this.namespace.run(f);
35
- }
36
- // Annotate the CommonJS export names for ESM import in node:
37
- 0 && (module.exports = {
38
- NamespaceContext
39
- });
40
- //# sourceMappingURL=NamespaceContext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/types/NamespaceContext.ts"],"sourcesContent":["import { createNamespace } from 'cls-hooked';\nimport { BaseRequestContext } from '@thisisagile/easy';\n\nexport class NamespaceContext extends BaseRequestContext {\n protected readonly namespace = createNamespace('context');\n\n public get<T>(key: string): T {\n return this.namespace.get(key) as T;\n }\n\n public set<T>(key: string, value: T): T {\n return this.namespace.set(key, value);\n }\n\n public readonly create = (f: () => void): void => this.namespace.run(f);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAgC;AAChC,kBAAmC;AAE5B,MAAM,yBAAyB,+BAAmB;AAAA,EACpC,gBAAY,mCAAgB,SAAS;AAAA,EAEjD,IAAO,KAAgB;AAC5B,WAAO,KAAK,UAAU,IAAI,GAAG;AAAA,EAC/B;AAAA,EAEO,IAAO,KAAa,OAAa;AACtC,WAAO,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACtC;AAAA,EAEgB,SAAS,CAAC,MAAwB,KAAK,UAAU,IAAI,CAAC;AACxE;","names":[]}
@@ -1,23 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
- var types_exports = {};
17
- module.exports = __toCommonJS(types_exports);
18
- __reExport(types_exports, require("./NamespaceContext"), module.exports);
19
- // Annotate the CommonJS export names for ESM import in node:
20
- 0 && (module.exports = {
21
- ...require("./NamespaceContext")
22
- });
23
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["export * from './NamespaceContext';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,0BAAc,+BAAd;","names":[]}