@autofleet/zehut 4.0.1-beta-5973b326.0 → 4.1.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.
- package/README.md +34 -3
- package/lib/index.cjs +2 -2
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +36 -26
- package/lib/index.d.ts +36 -26
- package/lib/index.js +2 -2
- package/lib/index.js.map +1 -1
- package/package.json +7 -10
package/README.md
CHANGED
|
@@ -4,7 +4,38 @@ This package handles authorization and authentication for AutoFleet services.
|
|
|
4
4
|
|
|
5
5
|
## V4 migration
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
### Outbreak v2
|
|
8
|
+
When upgrading from V3 to V4, the tracing system has been de-duped to use outbreak v2.
|
|
9
|
+
Historically, `zehut` and `outbreak` both added a layer of `async_hooks`, which each had a context that could store data.
|
|
10
|
+
The 2 had a nearly identical API, but did not communicate with each other, nor did they share data.
|
|
11
|
+
This version removes the trace added by `zehut` and only uses the `outbreak` one. This means that the context of the trace is now spread onto the headers of any outgoing HTTP request.
|
|
12
|
+
In order to allow keeping data in the context, without having `outbreak` add it to the headers, a new context has been added to the `outbreak` traces - `nonHeaderContext`.
|
|
13
|
+
Using the `getUser` function will keep working regularly, but reading anything else from the context will work only if you read from the correct context.
|
|
9
14
|
|
|
10
|
-
|
|
15
|
+
```diff
|
|
16
|
+
- const { context } = zehut.getCurrentPayload();
|
|
17
|
+
- const user = context?.get('userObject');
|
|
18
|
+
+ const user = zehut.getUser();
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
If you need to read any other data from the context, you should now read and write to `nonHeaderContext`, unless you wish for the values to be sent through to the headers of any outgoing request/response.
|
|
22
|
+
```diff
|
|
23
|
+
const currentTrace = zehut.getCurrentPayload();
|
|
24
|
+
-const dataFromContext = currentTrace?.context?.get('DATA_FROM_CONTEXT');
|
|
25
|
+
+const dataFromContext = currentTrace?.nonHeaderContext?.get('DATA_FROM_CONTEXT');
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
### Logger
|
|
30
|
+
|
|
31
|
+
The tracing mechanism has been updated to reduce boilerplate code.
|
|
32
|
+
Now, when calling the `enableTracing` function, you can now pass in the instance of the `logger`, and drop the call for `logger.addContextMiddleware`.
|
|
33
|
+
|
|
34
|
+
```diff
|
|
35
|
+
-zehut.enableTracing();
|
|
36
|
+
-
|
|
37
|
+
-logger.addContextMiddleware(() => ({
|
|
38
|
+
- traceId: zehut.outbreak.getCurrentContext()?.context?.get('x-trace-id'),
|
|
39
|
+
-}));
|
|
40
|
+
+zehut.enableTracing({ logger });
|
|
41
|
+
```
|
package/lib/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var
|
|
2
|
-
exports.outbreak=
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var g=require('@autofleet/outbreak'),S=require('jsonwebtoken'),Ue=require('node-cache'),xe=require('object-hash'),b=require('moment'),B=require('@autofleet/network');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var g__namespace=/*#__PURE__*/_interopNamespace(g);var S__namespace=/*#__PURE__*/_interopNamespace(S);var Ue__default=/*#__PURE__*/_interopDefault(Ue);var xe__default=/*#__PURE__*/_interopDefault(xe);var b__default=/*#__PURE__*/_interopDefault(b);var B__default=/*#__PURE__*/_interopDefault(B);var {DEPRECATED_JWT_SECRET:ue,JWT_NEW_SECRET:pe,DEPRECATED_REFRESH_JWT_SECRET:me,REFRESH_JWT_SECRET:fe,DEPRECATION_UNIX_TIMESTAMP:le}=process.env,k=(s,e,r)=>{let o=b__default.default(parseInt(le,10)*1e3);try{let t;if(s){let{iat:i}=S__namespace.default.decode(s);t=b__default.default(i*1e3);}else t=b__default.default();return t.isBefore(o)?e:r}catch{return r}},Ee=s=>k(s,me,fe),C=s=>k(s,ue,pe);var w=s=>s.replace("Bearer ",""),_=(s,e)=>{let r=w(s);return S__namespace.verify(r,C(r))};var Pe="00000000-0000-0000-0000-000000000000",ge="ffffffff-ffff-ffff-ffff-ffffffffffff",h="[0-9a-f]",ye="[1-8]",he=new RegExp(`^(?:${h}{8}-${h}{4}-${ye}${h}{3}-[89ab]${h}{3}-${h}{12}|${Pe}|${ge})$`,"i");function j(s){return typeof s=="string"&&he.test(s)}var $=10,F=process.env.API_GATEWAY_URL||"https://api.autofleet.io",O=new B__default.default({serviceName:"IDENTITY_MS",retries:3,retryCondition:()=>true,cache:process.env.NODE_ENV!=="test"?{maxAge:$*1e3}:void 0}),A=new B__default.default({baseURL:F,serviceUrl:F,retries:3,retryCondition:()=>true,cache:process.env.NODE_ENV!=="test"?{maxAge:$*1e3}:void 0});var l="x-af-elevated-permissions",E="x-af-context-ids",f=new Ue__default.default({stdTTL:10}),J=(s,e)=>{let r={...s,fleets:{...s?.fleets},businessModels:{...s?.businessModels},demandSources:{...s?.demandSources}};for(let o of e)Object.keys(o).forEach(t=>{r[t]??={},Object.entries(o[t]).forEach(([i,n])=>{r[t][i]=(r[t][i]||[]).concat(n);});});return r},u=class{constructor(e,r,o,t){this.id=e;this.accountType=r;this.contextIds=t;this.privateElevatedPermissionsHash=new Map;this.appPermission={};this.emptyUser=!!e,o&&this.privateElevatedPermissionsHash.set(Symbol("initial"),o);}async getUserPermissions(){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let e=xe__default.default({id:this.id,contextIds:this.contextIds}),r=f.get(e);return r||({data:r}=await O.get(`/api/v1/users/${this.id}/authorization-payload`,{params:{contextIds:this.contextIds}}),f.set(e,r)),this.accountType=r.accountType,this.privatePermissions=r,this.privatePermissions}async useCustomPermissionLoader(e){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let r=this.id,o=f.get(r);if(o)return this.privatePermissions=o,o;let t=await e(this.id);return f.set(r,t),this.privatePermissions=t,this.privatePermissions}get businessModels(){return this.getUserProperty("businessModels")}get fleets(){return this.getUserProperty("fleets")}get demandSources(){return this.getUserProperty("demandSources")}getUserProperty(e){if(!this.privatePermissions)throw new Error(`Cannot get ${e} without calling (async) getUserPermissions before`);return Object.keys(this.privatePermissions[e]||{})}get elevatedPermissions(){return J(void 0,this.privateElevatedPermissionsHash.values())}get permissions(){if(!this.privatePermissions)throw new Error("Cannot get permissions without calling (async) getUserPermissions before");return J(this.privatePermissions,this.privateElevatedPermissionsHash.values())}elevatePermissions(e){let r=Symbol();Object.values(e).forEach(n=>{Object.keys(n).forEach(a=>{if(!j(a))throw new Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${a}`)});});let o=g.getCurrentContext();if(!o)throw new Error("Cannot find current user cross services trace");let t=JSON.parse(o.context[l]||"{}"),i=Object.assign(t,e);return this.privateElevatedPermissionsHash.set(r,i),o.context.set(l,JSON.stringify(this.elevatedPermissions)),()=>{this.privateElevatedPermissionsHash.delete(r),o.context.set(l,JSON.stringify(this.elevatedPermissions));}}async getUserPermissionsLegacy(){if(!this.id)return;if(this.privatePermissionsLegacy)return this.privatePermissionsLegacy;let{data:e}=await O.get(`/api/v1/users/${this.id}/authorization-payload-legacy`);return this.privatePermissionsLegacy=e,this.privatePermissionsLegacy}get permissionsLegacy(){if(!this.privatePermissionsLegacy)throw new Error("Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before");return this.privatePermissionsLegacy}async getUserAppPermissions(e,r){if(!this.id||!e||!r)return;let o=this.appPermission[e];if(o)return o;let t=`${this.id}:${e}`,i=f.get(t);if(i)return this.appPermission[e]=i,i;let{data:n}=await A.post(`/api/v1/apps/${e}/get-user-payload`,{userId:this.id},{headers:{"x-autofleet-apps-secret":r}});return f.set(t,n),this.appPermission[e]=n,this.appPermission[e]}};var W=async(s,e)=>{let{data:r}=await A.post("/api/v1/auth",{bearer:s,appId:e});return r};var P=class extends Error{constructor(){super(...arguments);this.name="AppDoesNotExist";this.message="app does not exist";}};var G="identity-ms",z="accessToken",m="userObject",U="x-af-user-id",H="X-IAF-ORIGIN-SERVICE",I="x-af-user-permissions",X=H.toLowerCase(),V="x-autofleet-apps-secret";var T=async(s,e)=>{let r=e[H]||e[X]||"";if(!Array.isArray(r)&&r.toLowerCase()===G)return;let{eagerLoadUserPermissions:o,eagerLoadUserPermissionsLegacy:t,customPermissionLoader:i}=s,n=e[U];if(!n||Array.isArray(n))return;let a=e[l]?.length>0?JSON.parse(e[l]):{},c=e?.[E]?.split(","),d=new u(n,"user",a,c);return o&&(i?await d.useCustomPermissionLoader(i):await d.getUserPermissions()),t&&await d.getUserPermissionsLegacy(),g.getCurrentContext().nonHeaderContext?.set(m,d),d};var Y=(s={})=>async(e,r,o)=>{try{let t=await T(s,e.headers);t&&(e.user=t,e.headers[I]=t),o();}catch{r.status(401).json({error:"cannot authenticate user"});}},Z=(s={})=>async(e,r,o)=>{let{eagerLoadUserPermissions:t,eagerLoadUserPermissionsLegacy:i,returnErrorIfNoToken:n}=s,a;if(e.headers.authorization){try{a=await _(e.headers.authorization);}catch(y){y instanceof S__namespace.default.TokenExpiredError?r.status(401).json({errors:["Access token expired"]}):y instanceof S__namespace.default.JsonWebTokenError?r.status(400).json({errors:[y.message]}):r.status(500).json({errors:["Server error while parsing token"]});return}let c=a?.user?.id;c&&(e.headers[U]=c);let d=e.headers?.[E]?.split(","),p=new u(c,a?.user?.accountType,void 0,d);(t||i)&&await Promise.all([t&&p.getUserPermissions(),i&&p.getUserPermissionsLegacy()]),e.user=p,g.getCurrentContext().nonHeaderContext?.set(m,p),e.headers[I]=p;}else if(n){r.status(401).json({errors:["No token provided"]});return}o();},Q=s=>async(e,r,o)=>{let{appId:t,clientSecret:i}=s,n;if(!e.headers.authorization){r.status(401).json({errors:["No token provided"]});return}try{if(n=await W(e.headers.authorization,t),!n)throw new P}catch(p){if(p instanceof S__namespace.default.TokenExpiredError){r.status(401).json({errors:["Access token expired"]});return}if([S__namespace.default.JsonWebTokenError,P].some(y=>p instanceof y)){r.status(400).json({errors:[p.message]});return}r.status(500).json({errors:["Server error while parsing token"]});return}let a=n?.userId;a&&(e.headers[U]=a);let c=new u(a);t&&(e.headers[V]=i,await c.getUserAppPermissions(t,i)),e.user=c;let d=g.getCurrentContext().nonHeaderContext;d?.set(m,c),d?.set(z,w(e.headers.authorization)),e.headers[I]=c,o();},q=async(s,e,r)=>{await s.user.getUserPermissions(),r();},ee=s=>s.headers.authorization?_(s.headers.authorization):null,se=async(s,e)=>{let r=new u(e);await r.getUserPermissions(),s??=g.newTrace(g.traceTypes.RABBIT),s.nonHeaderContext.set(m,r);},re=u;var N=(s,e,r)=>{s.addHook("onRequest",async(o,t)=>{try{let i=await T(e,o.headers);i&&s.decorateRequest("user",i);}catch{t.status(401).send({error:"cannot authenticate user"});}}),r();};N[Symbol.for("skip-override")]=true;var v=()=>g.getCurrentContext().nonHeaderContext?.get(m),L=()=>v()?.id,D=(s,e)=>!L()||Object.hasOwn(v().permissions[e],s),te=s=>D(s,"fleets"),oe=s=>D(s,"businessModels"),ie=s=>D(s,"demandSources");var R=class extends Error{constructor(r=null,o="UnauthorizedAccessError"){super(o);this.user=r;this.name="UnauthorizedAccessError";}};var x={NONE:"NONE",BASIC:"BASIC",JWT:"JWT"},ne={[x.NONE]:()=>{},[x.BASIC]:s=>{let{username:e,password:r}=s;return `Basic ${Buffer.from(`${e}:${r}`).toString("base64")}`},[x.JWT]:s=>{let{secret:e}=s;if(e)return `Bearer ${S__namespace.sign({},e,{expiresIn:10})}`}},ce=s=>{let e=s?.method;if(!(!e||!ne[e]))return ne[e](s)};var Re=g__namespace.getCurrentContext,As=({outbreakOptions:s={},logger:e}={})=>{g__namespace.default({headersPrefix:"x-af",contextMiddlewareGetter:e?.addContextMiddleware,...s});},{traceTypes:be,newTrace:Ce}=g__namespace;var Is={traceTypes:be,newTrace:Ce,User:re,middleware:Y,middlewareWithDecode:Z,eagerLoadPermissionsMiddleware:q,getCurrentPayload:Re,getDecodedBearer:ee,checkFleetPermission:te,checkBusinessModelPermission:oe,checkDemandSourcePermission:ie,isUserExist:L,getUser:v,UnauthorizedAccessError:R,appMiddleware:Q,createOrSetRabbitTrace:se,outbreak:g__namespace,AUTHORIZATION_METHODS:x,getAuthorizationHeader:ce,CONTEXTS_IDS_HEADER:E,authFromUserIdHeaderPlugin:N};
|
|
2
|
+
exports.outbreak=g__namespace;exports.AUTHORIZATION_METHODS=x;exports.CONTEXTS_IDS_HEADER=E;exports.UnauthorizedAccessError=R;exports.User=re;exports.appMiddleware=Q;exports.authFromUserIdHeaderPlugin=N;exports.checkBusinessModelPermission=oe;exports.checkDemandSourcePermission=ie;exports.checkFleetPermission=te;exports.createOrSetRabbitTrace=se;exports.default=Is;exports.eagerLoadPermissionsMiddleware=q;exports.enableTracing=As;exports.getAuthorizationHeader=ce;exports.getCurrentPayload=Re;exports.getDecodedBearer=ee;exports.getRefreshTokenSecret=Ee;exports.getTokenSecret=C;exports.getUser=v;exports.isUserExist=L;exports.middleware=Y;exports.middlewareWithDecode=Z;exports.newTrace=Ce;exports.traceTypes=be;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
package/lib/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/secret-getter.ts","../src/utils.ts","../src/services.ts","../src/user/ApiUser.ts","../src/app-auth.ts","../src/exceptions/appDoesNotExist.ts","../src/user/index.ts","../src/check-permission.ts","../src/errors.ts","../src/authorization.ts","../src/index.ts"],"names":["DEPRECATED_JWT_SECRET","JWT_NEW_SECRET","DEPRECATED_REFRESH_JWT_SECRET","REFRESH_JWT_SECRET","DEPRECATION_UNIX_TIMESTAMP","getRelevantSecret","token","deprecatedSecret","newSecret","deprecationTime","moment","unixTime","iat","jwt","getRefreshTokenSecret","getTokenSecret","getAuthFromBearer","bearer","decodeBearer","appSecret","N","EMPTY_UUID","FULL_UUID","VALID_CHARS_REGEX","UUID_VERSION_REGEX","UUID_REGEX","validateUUID","uuid","CACHE_LIFETIME_IN_SEC","apiGwUrl","IdentityNetwork","Network","AutofleetApiNetwork","ELEVATED_PERMISSIONS_HEADER","CONTEXTS_IDS_HEADER","userCache","NodeCache","mergePermissions","target","sources","permissions","source","entityType","entityId","perms","ApiUser","id","accountType","elevatedPermissions","contextIds","cacheKey","objectHash","data","customPermissionLoader","cachedResult","key","addedPermissions","elevationId","entityIds","currentUserTrace","getCurrentContext","currentElevation","newElevation","appId","clientSecret","currentAppPermission","decodeAppBearer","decoded","AppDoesNotExist","IDENTITY_MS","ACCESS_TOKEN","USER_OBJECT","USER_TRACING_HEADER","ORIGIN_HEADER","USER_PERMISSIONS_HEADER","LOWER_CASE_ORIGIN_HEADER","middleware","options","req","res","next","eagerLoadUserPermissions","eagerLoadUserPermissionsLegacy","userId","elevatedPermissionsFromHeader","userObject","middlewareWithDecode","returnErrorIfNoToken","e","TokenExpiredError","JsonWebTokenError","appMiddleware","Err","currentTraceContext","eagerLoadPermissionsMiddleware","getDecodedBearer","createOrSetRabbitTrace","trace","newTrace","traceTypes","user_default","getUser","isUserExist","checkFleetPermission","fleetId","checkBusinessModelPermission","businessModelId","checkDemandSourcePermission","demandSourceId","UnauthorizedAccessError","user","message","AUTHORIZATION_METHODS","AUTHORIZATION_ACTIONS","authorizationSettings","username","password","secret","se","getAuthorizationHeader","authorizationMethod","getCurrentPayload","y","enableTracing","outbreakOptions","logger","outbreak","index_default"],"mappings":"y4BAGA,IAAM,CACJ,qBAAAA,CAAAA,EAAAA,CAAuB,eAAAC,EACvB,CAAA,6BAAA,CAAAC,GAA+B,kBAAAC,CAAAA,EAAAA,CAC/B,0BAAAC,CAAAA,EACF,CAAI,CAAA,OAAA,CAAQ,IAENC,CAAoB,CAAA,CAACC,EAA2BC,CAA0BC,CAAAA,CAAAA,GAA8B,C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a,CACzIH,YAAA,CAAA,OAAA,CAAQ,CACf,aAAe,CAAA,MAAA,CACf,wBAAyBG,CAAQ,EAAA,oBAAA,CACjC,GAAGD,CACL,CAAC,EACH,EAEM,CAAE,UAAA,CAAAzB,GAAY,QAAAD,CAAAA,EAAS,EAAI4B,aA6BjC,IAAOC,EAAQ,CAAA,CACb,UAAA5B,CAAAA,EAAAA,CACA,SAAAD,EACA,CAAA,IAAA,CAAAE,EACA,UAAAxB,CAAAA,CAAAA,CACA,qBAAAU,CACA,CAAA,8BAAA,CAAAQ,CACA,CAAA,iBAAA,CAAA2B,EACA,CAAA,gBAAA,CAAA1B,EACA,oBAAAQ,CAAAA,CAAAA,CACA,6BAAAE,CACA,CAAA,2BAAA,CAAAE,EACA,WAAAL,CAAAA,CAAAA,CACA,OAAAD,CAAAA,CAAAA,CACA,uBAAAQ,CAAAA,CAAAA,CACA,cAAAlB,CACA,CAAA,sBAAA,CAAAK,EACA,QAAA8B,CAAAA,YAAAA,CACA,sBAAAd,CACA,CAAA,sBAAA,CAAAO,EACA,CAAA,mBAAA,CAAArF,CACF","file":"index.cjs","sourcesContent":["import jwt from 'jsonwebtoken';\nimport moment from 'moment';\n\nconst {\n DEPRECATED_JWT_SECRET, JWT_NEW_SECRET,\n DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET,\n DEPRECATION_UNIX_TIMESTAMP,\n} = process.env;\n\nconst getRelevantSecret = (token: string | undefined, deprecatedSecret: string, newSecret: string): string => {\n const deprecationTime = moment(parseInt(DEPRECATION_UNIX_TIMESTAMP, 10) * 1000);\n try {\n let unixTime: moment.Moment;\n if (token) {\n const { iat } = jwt.decode(token) as jwt.JwtPayload;\n unixTime = moment(iat * 1000);\n } else {\n unixTime = moment();\n }\n return unixTime.isBefore(deprecationTime) ? deprecatedSecret : newSecret;\n } catch (e) {\n return newSecret;\n }\n};\n\nexport const getRefreshTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET);\nexport const getTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_JWT_SECRET, JWT_NEW_SECRET);\n","import type { UUID } from 'node:crypto';\nimport * as jwt from 'jsonwebtoken';\nimport { getTokenSecret } from './secret-getter';\n\nconst CONTEXT_PROPS = ['fleetId', 'businessModelId', 'demandSourceId'];\nconst CONTEXT_MAP_PROPS = {\n fleet: 'fleets',\n business: 'businessModels',\n demand: 'demandSources',\n};\n\nexport const getAuthFromBearer = (bearer: string): string => bearer.replace('Bearer ', '');\n\nexport const decodeBearer = (bearer: string, appSecret?: string): any => {\n const token = getAuthFromBearer(bearer);\n const decoded = jwt.verify(token, appSecret || getTokenSecret(token));\n return decoded;\n};\n\nexport const parsePermissions = (contextId, decodedToken): any => {\n if (!decodedToken) { return []; }\n const { contexts } = decodedToken;\n const activeContext = contexts.find((context) => context.id === contextId);\n\n const permissionsValue = `${activeContext.permissions?.map((cp) => `${cp},`)}`;\n\n return {\n key: activeContext.entityId,\n value: permissionsValue,\n };\n};\n\nexport const getEntitiesFromContext = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n\n const attributes = {};\n contexts.forEach((context) => {\n const prop = CONTEXT_MAP_PROPS[context.subSystem || 'business'];\n\n const permissions = parsePermissions(context.id, decodedToken);\n // eslint-disable-next-line no-unused-expressions\n attributes[prop]\n ? attributes[prop][permissions.key] = permissions.value\n : attributes[prop] = { [permissions.key]: permissions.value };\n });\n\n return attributes;\n};\n\nexport const getContextAttributes = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n const attributes = {};\n contexts.forEach((context) => {\n CONTEXT_PROPS.forEach((prop) => {\n if (context[prop]) {\n const contextPropWrapped = [context[prop]];\n // eslint-disable-next-line no-unused-expressions\n attributes[prop]\n ? attributes[prop] = attributes[prop].concat(contextPropWrapped)\n : attributes[prop] = contextPropWrapped;\n }\n });\n });\n return attributes;\n};\n\nconst EMPTY_UUID = '00000000-0000-0000-0000-000000000000';\nconst FULL_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff';\nconst VALID_CHARS_REGEX = '[0-9a-f]';\nconst UUID_VERSION_REGEX = '[1-8]';\nconst UUID_REGEX = new RegExp(`^(?:${VALID_CHARS_REGEX}{8}-${VALID_CHARS_REGEX}{4}-${UUID_VERSION_REGEX}${VALID_CHARS_REGEX}{3}-[89ab]${VALID_CHARS_REGEX}{3}-${VALID_CHARS_REGEX}{12}|${EMPTY_UUID}|${FULL_UUID})$`, 'i');\nexport function validateUUID(uuid: unknown): uuid is UUID {\n return typeof uuid === 'string' && UUID_REGEX.test(uuid);\n}\n","import Network from '@autofleet/network';\n\nconst CACHE_LIFETIME_IN_SEC = 10;\nconst apiGwUrl = process.env.API_GATEWAY_URL || 'https://api.autofleet.io';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const IdentityNetwork = new Network({\n serviceName: 'IDENTITY_MS',\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n\nexport const AutofleetApiNetwork = new Network({\n baseURL: apiGwUrl,\n serviceUrl: apiGwUrl,\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n","import NodeCache from 'node-cache';\nimport objectHash from 'object-hash';\nimport { getCurrentContext } from '@autofleet/outbreak';\nimport { validateUUID } from '../utils';\nimport { AutofleetApiNetwork, IdentityNetwork } from '../services';\n\nexport type AccountType = 'client' | 'user' | 'service' | 'driver'\ninterface EntityPermissions {\n [key: string]: string[];\n}\n\nexport const ELEVATED_PERMISSIONS_HEADER = 'x-af-elevated-permissions';\nexport const CONTEXTS_IDS_HEADER = 'x-af-context-ids';\n\nexport interface UserPayload {\n businessModels: EntityPermissions;\n fleets: EntityPermissions;\n demandSources: EntityPermissions;\n businessAccounts?: EntityPermissions;\n accountType?: AccountType;\n contexts?: EntityPermissions;\n createdAt?: string;\n}\n\nexport interface PartialUserPayload {\n businessModels?: EntityPermissions;\n fleets?: EntityPermissions;\n demandSources?: EntityPermissions;\n vehicles?: EntityPermissions;\n drivers?: EntityPermissions;\n businessAccounts?: EntityPermissions;\n}\n\nexport type CustomPermissionLoader = (string) => Promise<UserPayload>;\n\nconst userCache = new NodeCache({ stdTTL: 10 });\n\nconst mergePermissions = (target: UserPayload, sources: Iterable<PartialUserPayload>): UserPayload => {\n const permissions: UserPayload = {\n ...target,\n fleets: { ...target?.fleets },\n businessModels: { ...target?.businessModels },\n demandSources: { ...target?.demandSources },\n // Clone other nested objects as needed\n };\n\n // eslint-disable-next-line no-restricted-syntax\n for (const source of sources) {\n Object.keys(source).forEach((entityType) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType] ??= {};\n Object.entries(source[entityType]!).forEach(([entityId, perms]) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType][entityId] = (permissions[entityType][entityId] || []).concat(perms);\n });\n });\n }\n\n return permissions;\n};\n\nexport default class ApiUser {\n private privatePermissions: UserPayload | undefined;\n\n private readonly privateElevatedPermissionsHash = new Map<symbol, PartialUserPayload | undefined>();\n\n private privatePermissionsLegacy: any;\n\n private readonly appPermission: {[key: string]: any; } = {};\n\n public readonly emptyUser: boolean;\n\n constructor(public id? : string, public accountType?: AccountType, elevatedPermissions?: PartialUserPayload, public contextIds?: string[]) {\n this.emptyUser = !!id;\n if (elevatedPermissions) {\n this.privateElevatedPermissionsHash.set(Symbol('initial'), elevatedPermissions);\n }\n }\n\n async getUserPermissions(): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n const cacheKey = objectHash({\n id: this.id,\n contextIds: this.contextIds,\n });\n\n let data = userCache.get<UserPayload>(cacheKey);\n\n if (!data) {\n ({ data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload`, { params: { contextIds: this.contextIds } }));\n userCache.set(cacheKey, data);\n }\n\n this.accountType = data.accountType;\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n async useCustomPermissionLoader(customPermissionLoader: any): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n\n const cacheKey = this.id;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.privatePermissions = cachedResult;\n return cachedResult;\n }\n\n const data = await customPermissionLoader(this.id);\n userCache.set(cacheKey, data);\n\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n get businessModels(): string[] | undefined {\n return this.getUserProperty('businessModels');\n }\n\n get fleets(): string[] | undefined {\n return this.getUserProperty('fleets');\n }\n\n get demandSources(): string[] | undefined {\n return this.getUserProperty('demandSources');\n }\n\n private getUserProperty(key: keyof UserPayload): string[] | undefined {\n if (!this.privatePermissions) {\n throw new Error(`Cannot get ${key} without calling (async) getUserPermissions before`);\n }\n return Object.keys(this.privatePermissions[key] || {});\n }\n\n get elevatedPermissions(): UserPayload {\n return mergePermissions(undefined, this.privateElevatedPermissionsHash.values());\n }\n\n get permissions(): UserPayload | undefined {\n if (!this.privatePermissions) {\n throw new Error('Cannot get permissions without calling (async) getUserPermissions before');\n }\n\n return mergePermissions(this.privatePermissions, this.privateElevatedPermissionsHash.values());\n }\n\n elevatePermissions(addedPermissions: PartialUserPayload): () => void {\n // @itayankri is concerned about memory consumption, so create a symbol with no description, to avoid assigning memory for the description string\n // eslint-disable-next-line symbol-description\n const elevationId = Symbol();\n\n // Validate that the added permissions are valid UUIDs\n Object.values(addedPermissions).forEach((entityIds) => {\n Object.keys(entityIds).forEach((entityId) => {\n if (!validateUUID(entityId)) {\n throw new Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${entityId}`);\n }\n });\n });\n\n const currentUserTrace = getCurrentContext();\n if (!currentUserTrace) {\n throw new Error('Cannot find current user cross services trace');\n }\n\n const currentElevation = JSON.parse(currentUserTrace.context[ELEVATED_PERMISSIONS_HEADER] || '{}');\n const newElevation = Object.assign(currentElevation, addedPermissions);\n this.privateElevatedPermissionsHash.set(elevationId, newElevation);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n return () => {\n this.privateElevatedPermissionsHash.delete(elevationId);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n };\n }\n\n async getUserPermissionsLegacy() {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissionsLegacy) {\n return this.privatePermissionsLegacy;\n }\n const { data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload-legacy`);\n\n this.privatePermissionsLegacy = data;\n return this.privatePermissionsLegacy;\n }\n\n get permissionsLegacy(): any {\n if (!this.privatePermissionsLegacy) {\n throw new Error('Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before');\n }\n return this.privatePermissionsLegacy;\n }\n\n async getUserAppPermissions(appId, clientSecret) {\n if (!this.id || !appId || !clientSecret) {\n return undefined;\n }\n const currentAppPermission = this.appPermission[appId];\n\n if (currentAppPermission) {\n return currentAppPermission;\n }\n\n const cacheKey = `${this.id}:${appId}`;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.appPermission[appId] = cachedResult;\n return cachedResult;\n }\n\n const { data } = await AutofleetApiNetwork.post(`/api/v1/apps/${appId}/get-user-payload`, {\n userId: this.id,\n }, {\n headers: {\n 'x-autofleet-apps-secret': clientSecret,\n },\n });\n\n userCache.set(cacheKey, data);\n this.appPermission[appId] = data;\n return this.appPermission[appId];\n }\n}\n","import { AutofleetApiNetwork } from './services';\n\nexport const decodeAppBearer = async (bearer: string, appId: string): Promise<any> => {\n const { data: decoded } = await AutofleetApiNetwork.post('/api/v1/auth', { bearer, appId });\n return decoded;\n};\n\nexport const getClientSecret = async (appId: string): Promise<any> => {\n const { data: secret } = await AutofleetApiNetwork.get(`/api/v1/auth/client-secret/${appId}`);\n return secret;\n};\n","export default class AppDoesNotExist extends Error {\n name = 'AppDoesNotExist';\n\n message = 'app does not exist';\n}\n","import { getCurrentContext, newTrace, traceTypes } from '@autofleet/outbreak';\nimport { TokenExpiredError, JsonWebTokenError } from 'jsonwebtoken';\nimport ApiUser, { CONTEXTS_IDS_HEADER, CustomPermissionLoader, ELEVATED_PERMISSIONS_HEADER } from './ApiUser';\nimport { decodeAppBearer } from '../app-auth';\nimport AppDoesNotExist from '../exceptions/appDoesNotExist';\nimport { decodeBearer, getAuthFromBearer } from '../utils';\n\nconst IDENTITY_MS = 'identity-ms';\nconst ACCESS_TOKEN = 'accessToken';\nexport const USER_OBJECT = 'userObject';\nconst USER_TRACING_HEADER = 'x-af-user-id';\nconst ORIGIN_HEADER = 'X-IAF-ORIGIN-SERVICE';\nconst USER_PERMISSIONS_HEADER = 'x-af-user-permissions';\nconst LOWER_CASE_ORIGIN_HEADER = ORIGIN_HEADER.toLowerCase();\n\nexport const middleware = (options: {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n customPermissionLoader?: CustomPermissionLoader;\n} = {}) => async (req, res, next): Promise<any> => {\n try {\n const originHeader: string = req.headers[ORIGIN_HEADER] || req.headers[LOWER_CASE_ORIGIN_HEADER] || '';\n if (originHeader.toLowerCase() === IDENTITY_MS) {\n return next();\n }\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n customPermissionLoader,\n } = options;\n const userId = req.headers[USER_TRACING_HEADER];\n if (!userId) {\n return next();\n }\n\n const elevatedPermissionsFromHeader = req.headers[ELEVATED_PERMISSIONS_HEADER]?.length > 0 ? JSON.parse(req.headers[ELEVATED_PERMISSIONS_HEADER]) : {};\n const contextIds = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n\n const userObject = new ApiUser(userId, 'user', elevatedPermissionsFromHeader, contextIds);\n if (eagerLoadUserPermissions) {\n if (customPermissionLoader) {\n await userObject.useCustomPermissionLoader(customPermissionLoader);\n } else {\n await userObject.getUserPermissions();\n }\n }\n\n if (eagerLoadUserPermissionsLegacy) {\n await userObject.getUserPermissionsLegacy();\n }\n\n req.user = userObject;\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n\n // Added in order to support outbreak.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n\n return next();\n } catch (e) {\n res.status(401);\n return res.json({\n error: 'cannot authenticate user',\n });\n }\n};\n\nexport const middlewareWithDecode = (options: {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n returnErrorIfNoToken?: boolean\n} = {}) => async (req, res, next): Promise<void> => {\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n returnErrorIfNoToken,\n } = options;\n let decoded;\n if (req.headers.authorization) {\n try {\n decoded = await decodeBearer(req.headers.authorization);\n } catch (e) {\n if (e instanceof TokenExpiredError) {\n res.status(401);\n res.json({\n errors: ['Access token expired'],\n });\n } else if (e instanceof JsonWebTokenError) {\n res.status(400);\n res.json({\n errors: [e.message],\n });\n } else {\n res.status(500);\n res.json({\n errors: ['Server error while parsing token'],\n });\n }\n return undefined;\n }\n const userId = decoded?.user?.id;\n\n if (userId) {\n req.headers[USER_TRACING_HEADER] = userId;\n }\n\n const contextIds = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n const userObject = new ApiUser(userId, decoded?.user?.accountType, undefined, contextIds);\n\n if (eagerLoadUserPermissions) {\n await userObject.getUserPermissions();\n }\n\n if (eagerLoadUserPermissionsLegacy) {\n await userObject.getUserPermissionsLegacy();\n }\n\n req.user = userObject;\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n\n // Added in order to support outbreak.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n } else if (returnErrorIfNoToken) {\n res.status(401);\n return res.json({\n errors: ['No token provided'],\n });\n }\n return next();\n};\n\nexport const appMiddleware = (options: {\n appId: string,\n clientSecret: string\n}) => async (req, res, next): Promise<void> => {\n const {\n appId,\n clientSecret,\n } = options;\n let decoded;\n\n if (!req.headers.authorization) {\n res.status(401);\n return res.json({\n errors: ['No token provided'],\n });\n }\n\n try {\n decoded = await decodeAppBearer(req.headers.authorization, appId);\n if (!decoded) {\n throw new AppDoesNotExist();\n }\n } catch (e) {\n if (e instanceof TokenExpiredError) {\n return res.status(401).json({\n errors: ['Access token expired'],\n });\n }\n if ([JsonWebTokenError, AppDoesNotExist].some((Err) => e instanceof Err)) {\n return res.status(400).json({\n errors: [e.message],\n });\n }\n return res.status(500).json({\n errors: ['Server error while parsing token'],\n });\n }\n const userId = decoded?.userId;\n if (userId) {\n req.headers[USER_OBJECT] = userId;\n }\n\n const userObject = new ApiUser(userId);\n\n if (appId) {\n req.headers['x-autofleet-apps-secret'] = clientSecret;\n // Won't work until we find a better solution for identity ms\n await userObject.getUserAppPermissions(appId, clientSecret);\n }\n\n req.user = userObject;\n const currentTraceContext = getCurrentContext().nonHeaderContext;\n currentTraceContext?.set(USER_OBJECT, userObject);\n currentTraceContext?.set(ACCESS_TOKEN, getAuthFromBearer(req.headers.authorization));\n\n // Added in order to support outbreak.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n\n return next();\n};\n\nexport const eagerLoadPermissionsMiddleware = async (req, res, next) => {\n await req.user.getUserPermissions();\n return next();\n};\n\nexport const getDecodedBearer = (req) => {\n if (req.headers.authorization) {\n return decodeBearer(req.headers.authorization);\n }\n\n return null;\n};\n\nexport const createOrSetRabbitTrace = async (trace: ReturnType<typeof newTrace> | undefined, userId: string | undefined) => {\n const userObject = new ApiUser(userId);\n\n await userObject.getUserPermissions();\n // eslint-disable-next-line no-param-reassign\n trace ??= newTrace(traceTypes.RABBIT);\n trace.nonHeaderContext.set(USER_OBJECT, userObject);\n};\n\nexport default ApiUser;\n","import { getCurrentContext } from '@autofleet/outbreak';\nimport ApiUser from './user/ApiUser';\nimport { USER_OBJECT } from './user';\n\nexport const getUser = () : ApiUser | undefined => getCurrentContext().nonHeaderContext?.get(USER_OBJECT) as ApiUser | undefined;\n\nexport const isUserExist = () => getUser()?.id;\n\nexport const checkFleetPermission = (fleetId: string) => !isUserExist() || Object.keys(getUser()!.permissions.fleets).includes(fleetId);\n\nexport const checkBusinessModelPermission = (businessModelId: string) => !isUserExist() || Object.keys(getUser()!.permissions.businessModels).includes(businessModelId);\n\nexport const checkDemandSourcePermission = (demandSourceId: string) => !isUserExist() || Object.keys(getUser()!.permissions.demandSources).includes(demandSourceId);\n","import type ApiUser from './user';\n\n// eslint-disable-next-line import/prefer-default-export\nexport class UnauthorizedAccessError extends Error {\n constructor(public user: ApiUser | null = null, message = 'UnauthorizedAccessError') {\n super(message);\n this.name = 'UnauthorizedAccessError';\n }\n}\n","import * as jwt from 'jsonwebtoken';\n\nexport const AUTHORIZATION_METHODS = {\n NONE: 'NONE',\n BASIC: 'BASIC',\n JWT: 'JWT',\n};\n\nconst AUTHORIZATION_ACTIONS = {\n [AUTHORIZATION_METHODS.NONE]: () => undefined,\n [AUTHORIZATION_METHODS.BASIC]: (authorizationSettings: any) => {\n const { username, password } = authorizationSettings;\n const encodedCredentials = Buffer.from(`${username}:${password}`).toString('base64');\n return `Basic ${encodedCredentials}`;\n },\n [AUTHORIZATION_METHODS.JWT]: (authorizationSettings: any) => {\n const { secret } = authorizationSettings;\n if (secret) {\n return `Bearer ${jwt.sign({}, secret, { expiresIn: 10 })}`;\n }\n return undefined;\n },\n};\n\nexport const getAuthorizationHeader = (authorizationSettings: { method: string } | undefined): string | undefined => {\n const authorizationMethod = authorizationSettings?.method;\n\n if (!authorizationMethod || !AUTHORIZATION_ACTIONS[authorizationMethod]) {\n return undefined;\n }\n\n return AUTHORIZATION_ACTIONS[authorizationMethod](authorizationSettings);\n};\n","import type { LoggerInstanceManager } from '@autofleet/logger';\nimport * as outbreak from '@autofleet/outbreak';\nimport User, {\n middleware,\n eagerLoadPermissionsMiddleware,\n middlewareWithDecode,\n getDecodedBearer,\n appMiddleware,\n createOrSetRabbitTrace,\n} from './user';\nimport { type UserPayload, CONTEXTS_IDS_HEADER } from './user/ApiUser';\nimport {\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n} from './check-permission';\nimport { UnauthorizedAccessError } from './errors';\nimport { getRefreshTokenSecret, getTokenSecret } from './secret-getter';\nimport { AUTHORIZATION_METHODS, getAuthorizationHeader } from './authorization';\n\nconst getCurrentPayload = outbreak.getCurrentContext;\n\ntype OutbreakOptions = Parameters<typeof outbreak.default>[0];\ntype LoggerWithContextMiddleware = Partial<Pick<LoggerInstanceManager, 'addContextMiddleware'>>;\nconst enableTracing = ({ outbreakOptions = {}, logger }: { outbreakOptions?: OutbreakOptions, logger?: LoggerWithContextMiddleware } = {}): void => {\n outbreak.default({\n headersPrefix: 'x-af',\n contextMiddlewareGetter: logger?.addContextMiddleware,\n ...outbreakOptions,\n });\n};\n\nconst { traceTypes, newTrace } = outbreak;\n\nexport {\n traceTypes,\n newTrace,\n enableTracing,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n getRefreshTokenSecret,\n getTokenSecret,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n type UserPayload,\n CONTEXTS_IDS_HEADER,\n};\n\nexport default {\n traceTypes,\n newTrace,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n CONTEXTS_IDS_HEADER,\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/secret-getter.ts","../src/utils.ts","../src/services.ts","../src/user/ApiUser.ts","../src/app-auth.ts","../src/exceptions/appDoesNotExist.ts","../src/user/const.ts","../src/user/common.ts","../src/user/index.ts","../src/user/fastify.ts","../src/check-permission.ts","../src/errors.ts","../src/authorization.ts","../src/index.ts"],"names":["DEPRECATED_JWT_SECRET","JWT_NEW_SECRET","DEPRECATED_REFRESH_JWT_SECRET","REFRESH_JWT_SECRET","DEPRECATION_UNIX_TIMESTAMP","getRelevantSecret","token","deprecatedSecret","newSecret","deprecationTime","moment","unixTime","iat","jwt","getRefreshTokenSecret","getTokenSecret","getAuthFromBearer","bearer","decodeBearer","appSecret","M","EMPTY_UUID","FULL_UUID","VALID_CHARS_REGEX","UUID_VERSION_REGEX","UUID_REGEX","validateUUID","uuid","CACHE_LIFETIME_IN_SEC","apiGwUrl","IdentityNetwork","Network","AutofleetApiNetwork","ELEVATED_PERMISSIONS_HEADER","CONTEXTS_IDS_HEADER","userCache","NodeCache","mergePermissions","target","sources","permissions","source","entityType","entityId","perms","ApiUser","id","accountType","elevatedPermissions","contextIds","cacheKey","objectHash","data","customPermissionLoader","cachedResult","key","addedPermissions","elevationId","entityIds","currentUserTrace","getCurrentContext","currentElevation","newElevation","appId","clientSecret","currentAppPermission","decodeAppBearer","decoded","AppDoesNotExist","IDENTITY_MS","ACCESS_TOKEN","USER_OBJECT","USER_TRACING_HEADER","ORIGIN_HEADER","USER_PERMISSIONS_HEADER","LOWER_CASE_ORIGIN_HEADER","AUTOFLEET_APPS_SECRET_HEADER","authFromUserIdHeader","options","headers","originHeader","eagerLoadUserPermissions","eagerLoadUserPermissionsLegacy","userId","elevatedPermissionsFromHeader","userObject","middleware","req","res","next","middlewareWithDecode","returnErrorIfNoToken","e","appMiddleware","Err","currentTraceContext","eagerLoadPermissionsMiddleware","getDecodedBearer","createOrSetRabbitTrace","trace","newTrace","traceTypes","user_default","authFromUserIdHeaderPlugin","fastify","done","request","reply","user","getUser","isUserExist","checkUserPermissions","checkFleetPermission","fleetId","checkBusinessModelPermission","businessModelId","checkDemandSourcePermission","demandSourceId","UnauthorizedAccessError","message","AUTHORIZATION_METHODS","AUTHORIZATION_ACTIONS","authorizationSettings","username","password","secret","ae","getAuthorizationHeader","authorizationMethod","getCurrentPayload","g","enableTracing","outbreakOptions","logger","outbreak","index_default"],"mappings":"s4BAGA,IAAM,CACJ,qBAAA,CAAAA,EAAuB,CAAA,cAAA,CAAAC,GACvB,6BAAAC,CAAAA,EAAAA,CAA+B,kBAAAC,CAAAA,EAAAA,CAC/B,0BAAAC,CAAAA,EACF,EAAI,OAAQ,CAAA,GAAA,CAENC,CAAoB,CAAA,CAACC,CAA2BC,CAAAA,CAAAA,CAA0BC,IAA8B,CAC5G,IAAMC,EAAkBC,kBAAO,CAAA,QAAA,CAASN,GAA4B,EAAE,CAAA,CAAI,GAAI,CAAA,CAC9E,GAAI,CACF,IAAIO,CACJ,CAAA,GAAIL,CAAO,CAAA,CACT,GAAM,CAAE,IAAAM,CAAI,CAAA,CAAIC,oBAAI,CAAA,MAAA,CAAOP,CAAK,CAAA,CAChCK,EAAWD,kBAAOE,CAAAA,CAAAA,CAAM,GAAI,EAC9B,CAAA,KACED,EAAWD,kBAAO,EAAA,CAEpB,OAAOC,CAAAA,CAAS,QAASF,CAAAA,CAAe,EAAIF,CAAmBC,CAAAA,CACjE,CAAY,KAAA,CACV,OAAOA,CACT,CACF,CAEaM,CAAAA,EAAAA,CAAyBR,CAA2BD,EAAAA,CAAAA,CAAkBC,CAAOJ,CAAAA,EAAAA,CAA+BC,EAAkB,CAC9HY,CAAAA,CAAAA,CAAkBT,GAA2BD,CAAkBC,CAAAA,CAAAA,CAAON,GAAuBC,EAAc,ECfjH,IAAMe,CAAAA,CAAqBC,CAA2BA,EAAAA,CAAAA,C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NEW_SECRET,\n DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET,\n DEPRECATION_UNIX_TIMESTAMP,\n} = process.env;\n\nconst getRelevantSecret = (token: string | undefined, deprecatedSecret: string, newSecret: string): string => {\n const deprecationTime = moment(parseInt(DEPRECATION_UNIX_TIMESTAMP, 10) * 1000);\n try {\n let unixTime: moment.Moment;\n if (token) {\n const { iat } = jwt.decode(token) as jwt.JwtPayload;\n unixTime = moment(iat * 1000);\n } else {\n unixTime = moment();\n }\n return unixTime.isBefore(deprecationTime) ? deprecatedSecret : newSecret;\n } catch (e) {\n return newSecret;\n }\n};\n\nexport const getRefreshTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET);\nexport const getTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_JWT_SECRET, JWT_NEW_SECRET);\n","import type { UUID } from 'node:crypto';\nimport * as jwt from 'jsonwebtoken';\nimport { getTokenSecret } from './secret-getter';\n\nconst CONTEXT_PROPS = ['fleetId', 'businessModelId', 'demandSourceId'];\nconst CONTEXT_MAP_PROPS = {\n fleet: 'fleets',\n business: 'businessModels',\n demand: 'demandSources',\n};\n\nexport const getAuthFromBearer = (bearer: string): string => bearer.replace('Bearer ', '');\n\nexport const decodeBearer = (bearer: string, appSecret?: string): any => {\n const token = getAuthFromBearer(bearer);\n const decoded = jwt.verify(token, appSecret || getTokenSecret(token));\n return decoded;\n};\n\nexport const parsePermissions = (contextId, decodedToken): any => {\n if (!decodedToken) { return []; }\n const { contexts } = decodedToken;\n const activeContext = contexts.find((context) => context.id === contextId);\n\n const permissionsValue = `${activeContext.permissions?.map((cp) => `${cp},`)}`;\n\n return {\n key: activeContext.entityId,\n value: permissionsValue,\n };\n};\n\nexport const getEntitiesFromContext = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n\n const attributes = {};\n contexts.forEach((context) => {\n const prop = CONTEXT_MAP_PROPS[context.subSystem || 'business'];\n\n const permissions = parsePermissions(context.id, decodedToken);\n attributes[prop] ||= {};\n attributes[prop][permissions.key] = permissions.value;\n });\n\n return attributes;\n};\n\nexport const getContextAttributes = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n const attributes = {};\n contexts.forEach((context) => {\n CONTEXT_PROPS.forEach((prop) => {\n if (context[prop]) {\n const contextPropWrapped = [context[prop]];\n attributes[prop] ||= [];\n attributes[prop] = attributes[prop].concat(contextPropWrapped);\n }\n });\n });\n return attributes;\n};\n\nconst EMPTY_UUID = '00000000-0000-0000-0000-000000000000';\nconst FULL_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff';\nconst VALID_CHARS_REGEX = '[0-9a-f]';\nconst UUID_VERSION_REGEX = '[1-8]';\nconst UUID_REGEX = new RegExp(\n `^(?:${VALID_CHARS_REGEX}{8}-${VALID_CHARS_REGEX}{4}-${UUID_VERSION_REGEX}${VALID_CHARS_REGEX}{3}-[89ab]${VALID_CHARS_REGEX}{3}-${VALID_CHARS_REGEX}{12}|${EMPTY_UUID}|${FULL_UUID})$`,\n 'i',\n);\nexport function validateUUID(uuid: unknown): uuid is UUID {\n return typeof uuid === 'string' && UUID_REGEX.test(uuid);\n}\n","import Network from '@autofleet/network';\n\nconst CACHE_LIFETIME_IN_SEC = 10;\nconst apiGwUrl = process.env.API_GATEWAY_URL || 'https://api.autofleet.io';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const IdentityNetwork = new Network({\n serviceName: 'IDENTITY_MS',\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n\nexport const AutofleetApiNetwork = new Network({\n baseURL: apiGwUrl,\n serviceUrl: apiGwUrl,\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n","import NodeCache from 'node-cache';\nimport objectHash from 'object-hash';\nimport { getCurrentContext } from '@autofleet/outbreak';\nimport { validateUUID } from '../utils';\nimport { AutofleetApiNetwork, IdentityNetwork } from '../services';\n\nexport type AccountType = 'client' | 'user' | 'service' | 'driver'\ninterface EntityPermissions {\n [key: string]: string[];\n}\n\nexport const ELEVATED_PERMISSIONS_HEADER = 'x-af-elevated-permissions';\nexport const CONTEXTS_IDS_HEADER = 'x-af-context-ids';\n\nexport interface UserPayload {\n businessModels: EntityPermissions;\n fleets: EntityPermissions;\n demandSources: EntityPermissions;\n businessAccounts?: EntityPermissions;\n accountType?: AccountType;\n contexts?: EntityPermissions;\n createdAt?: string;\n}\n\nexport interface PartialUserPayload {\n businessModels?: EntityPermissions;\n fleets?: EntityPermissions;\n demandSources?: EntityPermissions;\n vehicles?: EntityPermissions;\n drivers?: EntityPermissions;\n businessAccounts?: EntityPermissions;\n}\n\nconst userCache = new NodeCache({ stdTTL: 10 });\n\nconst mergePermissions = (target: UserPayload, sources: Iterable<PartialUserPayload>): UserPayload => {\n const permissions: UserPayload = {\n ...target,\n fleets: { ...target?.fleets },\n businessModels: { ...target?.businessModels },\n demandSources: { ...target?.demandSources },\n // Clone other nested objects as needed\n };\n\n // eslint-disable-next-line no-restricted-syntax\n for (const source of sources) {\n Object.keys(source).forEach((entityType) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType] ??= {};\n Object.entries(source[entityType]!).forEach(([entityId, perms]) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType][entityId] = (permissions[entityType][entityId] || []).concat(perms);\n });\n });\n }\n\n return permissions;\n};\n\nexport default class ApiUser {\n private privatePermissions: UserPayload | undefined;\n\n private readonly privateElevatedPermissionsHash = new Map<symbol, PartialUserPayload | undefined>();\n\n private privatePermissionsLegacy: any;\n\n private readonly appPermission: {[key: string]: any; } = {};\n\n public readonly emptyUser: boolean;\n\n constructor(public id? : string, public accountType?: AccountType, elevatedPermissions?: PartialUserPayload, public contextIds?: string[]) {\n this.emptyUser = !!id;\n if (elevatedPermissions) {\n this.privateElevatedPermissionsHash.set(Symbol('initial'), elevatedPermissions);\n }\n }\n\n public async getUserPermissions(): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n const cacheKey = objectHash({\n id: this.id,\n contextIds: this.contextIds,\n });\n\n let data = userCache.get<UserPayload>(cacheKey);\n\n if (!data) {\n ({ data } = await IdentityNetwork.get<UserPayload>(`/api/v1/users/${this.id}/authorization-payload`, { params: { contextIds: this.contextIds } }));\n userCache.set(cacheKey, data);\n }\n\n this.accountType = data.accountType;\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n public async useCustomPermissionLoader(customPermissionLoader: (userId: string) => UserPayload | PromiseLike<UserPayload>): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n\n const cacheKey = this.id;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.privatePermissions = cachedResult;\n return cachedResult;\n }\n\n const data = await customPermissionLoader(this.id);\n userCache.set(cacheKey, data);\n\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n public get businessModels(): string[] | undefined {\n return this.getUserProperty('businessModels');\n }\n\n public get fleets(): string[] | undefined {\n return this.getUserProperty('fleets');\n }\n\n public get demandSources(): string[] | undefined {\n return this.getUserProperty('demandSources');\n }\n\n private getUserProperty(key: keyof UserPayload): string[] | undefined {\n if (!this.privatePermissions) {\n throw new Error(`Cannot get ${key} without calling (async) getUserPermissions before`);\n }\n return Object.keys(this.privatePermissions[key] || {});\n }\n\n public get elevatedPermissions(): UserPayload {\n return mergePermissions(undefined, this.privateElevatedPermissionsHash.values());\n }\n\n public get permissions(): UserPayload | undefined {\n if (!this.privatePermissions) {\n throw new Error('Cannot get permissions without calling (async) getUserPermissions before');\n }\n\n return mergePermissions(this.privatePermissions, this.privateElevatedPermissionsHash.values());\n }\n\n public elevatePermissions(addedPermissions: PartialUserPayload): () => void {\n // @itayankri is concerned about memory consumption, so create a symbol with no description, to avoid assigning memory for the description string\n // eslint-disable-next-line symbol-description\n const elevationId = Symbol();\n\n // Validate that the added permissions are valid UUIDs\n Object.values(addedPermissions).forEach((entityIds) => {\n Object.keys(entityIds).forEach((entityId) => {\n if (!validateUUID(entityId)) {\n throw new Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${entityId}`);\n }\n });\n });\n\n const currentUserTrace = getCurrentContext();\n if (!currentUserTrace) {\n throw new Error('Cannot find current user cross services trace');\n }\n\n const currentElevation = JSON.parse(currentUserTrace.context[ELEVATED_PERMISSIONS_HEADER] || '{}');\n const newElevation = Object.assign(currentElevation, addedPermissions);\n this.privateElevatedPermissionsHash.set(elevationId, newElevation);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n return () => {\n this.privateElevatedPermissionsHash.delete(elevationId);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n };\n }\n\n public async getUserPermissionsLegacy() {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissionsLegacy) {\n return this.privatePermissionsLegacy;\n }\n const { data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload-legacy`);\n\n this.privatePermissionsLegacy = data;\n return this.privatePermissionsLegacy;\n }\n\n public get permissionsLegacy(): any {\n if (!this.privatePermissionsLegacy) {\n throw new Error('Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before');\n }\n return this.privatePermissionsLegacy;\n }\n\n public async getUserAppPermissions(appId, clientSecret) {\n if (!this.id || !appId || !clientSecret) {\n return undefined;\n }\n const currentAppPermission = this.appPermission[appId];\n\n if (currentAppPermission) {\n return currentAppPermission;\n }\n\n const cacheKey = `${this.id}:${appId}`;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.appPermission[appId] = cachedResult;\n return cachedResult;\n }\n\n const { data } = await AutofleetApiNetwork.post<UserPayload>(`/api/v1/apps/${appId}/get-user-payload`, {\n userId: this.id,\n }, {\n headers: {\n 'x-autofleet-apps-secret': clientSecret,\n },\n });\n\n userCache.set(cacheKey, data);\n this.appPermission[appId] = data;\n return this.appPermission[appId];\n }\n}\n","import { AutofleetApiNetwork } from './services';\n\nexport const decodeAppBearer = async (bearer: string, appId: string): Promise<any> => {\n const { data: decoded } = await AutofleetApiNetwork.post('/api/v1/auth', { bearer, appId });\n return decoded;\n};\n\nexport const getClientSecret = async (appId: string): Promise<any> => {\n const { data: secret } = await AutofleetApiNetwork.get(`/api/v1/auth/client-secret/${appId}`);\n return secret;\n};\n","export default class AppDoesNotExist extends Error {\n name = 'AppDoesNotExist';\n\n message = 'app does not exist';\n}\n","export const IDENTITY_MS = 'identity-ms';\nexport const ACCESS_TOKEN = 'accessToken';\nexport const USER_OBJECT = 'userObject';\nexport const USER_TRACING_HEADER = 'x-af-user-id';\nexport const ORIGIN_HEADER = 'X-IAF-ORIGIN-SERVICE';\nexport const USER_PERMISSIONS_HEADER = 'x-af-user-permissions';\nexport const LOWER_CASE_ORIGIN_HEADER = ORIGIN_HEADER.toLowerCase();\nexport const AUTOFLEET_APPS_SECRET_HEADER = 'x-autofleet-apps-secret';\n","import type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentContext } from '@autofleet/outbreak';\nimport ApiUser, { CONTEXTS_IDS_HEADER, ELEVATED_PERMISSIONS_HEADER, type UserPayload } from './ApiUser';\nimport {\n IDENTITY_MS,\n USER_OBJECT,\n USER_TRACING_HEADER,\n ORIGIN_HEADER,\n LOWER_CASE_ORIGIN_HEADER,\n} from './const';\n\nexport type CustomPermissionLoader = (userId: string) => Promise<UserPayload>;\nexport interface AuthFromUserIdHeaderOptions {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n customPermissionLoader?: CustomPermissionLoader;\n}\n\nexport const authFromUserIdHeader = async (options: AuthFromUserIdHeaderOptions, headers: IncomingHttpHeaders): Promise<ApiUser | undefined> => {\n const originHeader = headers[ORIGIN_HEADER] || headers[LOWER_CASE_ORIGIN_HEADER] || '';\n if (!Array.isArray(originHeader) && originHeader.toLowerCase() === IDENTITY_MS) {\n return undefined;\n }\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n customPermissionLoader,\n } = options;\n const userId = headers[USER_TRACING_HEADER] as string;\n if (!userId || Array.isArray(userId)) {\n return undefined;\n }\n\n const elevatedPermissionsFromHeader = headers[ELEVATED_PERMISSIONS_HEADER]?.length > 0 ? JSON.parse(headers[ELEVATED_PERMISSIONS_HEADER] as string) : {};\n const contextIds = (headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n\n const userObject = new ApiUser(userId, 'user', elevatedPermissionsFromHeader, contextIds);\n if (eagerLoadUserPermissions) {\n if (customPermissionLoader) {\n await userObject.useCustomPermissionLoader(customPermissionLoader);\n } else {\n await userObject.getUserPermissions();\n }\n }\n\n if (eagerLoadUserPermissionsLegacy) {\n await userObject.getUserPermissionsLegacy();\n }\n\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n return userObject;\n};\n","import type { Handler, Request } from 'express';\nimport { getCurrentContext, newTrace, traceTypes } from '@autofleet/outbreak';\nimport jwt from 'jsonwebtoken';\nimport ApiUser, { CONTEXTS_IDS_HEADER } from './ApiUser';\nimport { decodeAppBearer } from '../app-auth';\nimport AppDoesNotExist from '../exceptions/appDoesNotExist';\nimport { decodeBearer, getAuthFromBearer } from '../utils';\nimport {\n ACCESS_TOKEN,\n USER_OBJECT,\n USER_TRACING_HEADER,\n USER_PERMISSIONS_HEADER,\n AUTOFLEET_APPS_SECRET_HEADER,\n} from './const';\nimport { authFromUserIdHeader, AuthFromUserIdHeaderOptions } from './common';\n\ndeclare module 'express-serve-static-core' {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n interface Request {\n user: ApiUser;\n }\n}\n\nexport const middleware = (options: AuthFromUserIdHeaderOptions = {}): Handler => async (req, res, next): Promise<any> => {\n try {\n const userObject = await authFromUserIdHeader(options, req.headers);\n if (userObject) {\n req.user = userObject;\n // Added in order to support outbreak.\n // @ts-expect-error we are setting an object onto the request headers.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n }\n\n next();\n } catch (e) {\n res.status(401).json({ error: 'cannot authenticate user' });\n }\n};\n\nexport const middlewareWithDecode = (options: {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n returnErrorIfNoToken?: boolean\n} = {}): Handler => async (req, res, next): Promise<void> => {\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n returnErrorIfNoToken,\n } = options;\n let decoded;\n if (req.headers.authorization) {\n try {\n decoded = await decodeBearer(req.headers.authorization);\n } catch (e) {\n if (e instanceof jwt.TokenExpiredError) {\n res.status(401).json({ errors: ['Access token expired'] });\n } else if (e instanceof jwt.JsonWebTokenError) {\n res.status(400).json({ errors: [e.message] });\n } else {\n res.status(500).json({ errors: ['Server error while parsing token'] });\n }\n return;\n }\n const userId = decoded?.user?.id;\n\n if (userId) {\n req.headers[USER_TRACING_HEADER] = userId;\n }\n\n const contextIds = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n const userObject = new ApiUser(userId, decoded?.user?.accountType, undefined, contextIds);\n\n if (eagerLoadUserPermissions || eagerLoadUserPermissionsLegacy) {\n await Promise.all([\n eagerLoadUserPermissions && userObject.getUserPermissions(),\n eagerLoadUserPermissionsLegacy && userObject.getUserPermissionsLegacy(),\n ]);\n }\n\n req.user = userObject;\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n\n // Added in order to support outbreak.\n // @ts-expect-error we are setting an object onto the request headers.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n } else if (returnErrorIfNoToken) {\n res.status(401).json({ errors: ['No token provided'] });\n return;\n }\n next();\n};\n\nexport const appMiddleware = (options: {\n appId: string,\n clientSecret: string\n}): Handler => async (req, res, next): Promise<void> => {\n const {\n appId,\n clientSecret,\n } = options;\n let decoded;\n\n if (!req.headers.authorization) {\n res.status(401).json({ errors: ['No token provided'] });\n return;\n }\n\n try {\n decoded = await decodeAppBearer(req.headers.authorization, appId);\n if (!decoded) {\n throw new AppDoesNotExist();\n }\n } catch (e) {\n if (e instanceof jwt.TokenExpiredError) {\n res.status(401).json({ errors: ['Access token expired'] });\n return;\n }\n if ([jwt.JsonWebTokenError, AppDoesNotExist].some((Err) => e instanceof Err)) {\n res.status(400).json({ errors: [e.message] });\n return;\n }\n res.status(500).json({ errors: ['Server error while parsing token'] });\n return;\n }\n const userId = decoded?.userId;\n if (userId) {\n req.headers[USER_TRACING_HEADER] = userId;\n }\n\n const userObject = new ApiUser(userId);\n\n if (appId) {\n req.headers[AUTOFLEET_APPS_SECRET_HEADER] = clientSecret;\n // Won't work until we find a better solution for identity ms\n await userObject.getUserAppPermissions(appId, clientSecret);\n }\n\n req.user = userObject;\n const currentTraceContext = getCurrentContext().nonHeaderContext;\n currentTraceContext?.set(USER_OBJECT, userObject);\n currentTraceContext?.set(ACCESS_TOKEN, getAuthFromBearer(req.headers.authorization));\n\n // Added in order to support outbreak.\n // @ts-expect-error we are setting an object onto the request headers.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n\n next();\n};\n\nexport const eagerLoadPermissionsMiddleware: Handler = async (req, res, next) => {\n await req.user.getUserPermissions();\n next();\n};\n\nexport const getDecodedBearer = (req: Request) => {\n if (!req.headers.authorization) {\n return null;\n }\n return decodeBearer(req.headers.authorization);\n};\n\nexport const createOrSetRabbitTrace = async (trace: ReturnType<typeof newTrace> | undefined, userId: string | undefined) => {\n const userObject = new ApiUser(userId);\n\n await userObject.getUserPermissions();\n // eslint-disable-next-line no-param-reassign\n trace ??= newTrace(traceTypes.RABBIT);\n trace.nonHeaderContext.set(USER_OBJECT, userObject);\n};\n\nexport default ApiUser;\n","import type { FastifyPluginCallback } from 'fastify';\nimport type ApiUser from './ApiUser';\nimport { AuthFromUserIdHeaderOptions, authFromUserIdHeader } from './common';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n user?: ApiUser;\n }\n}\n\n// eslint-disable-next-line import/prefer-default-export\nexport const authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions> = (fastify, options, done) => {\n fastify.addHook('onRequest', async (request, reply) => {\n try {\n const user = await authFromUserIdHeader(options, request.headers);\n if (user) {\n fastify.decorateRequest('user', user);\n }\n } catch (e) {\n reply.status(401).send({ error: 'cannot authenticate user' });\n }\n });\n\n done();\n};\nauthFromUserIdHeaderPlugin[Symbol.for('skip-override')] = true; // Prevent Fastify from overriding the plugin\n","import { getCurrentContext } from '@autofleet/outbreak';\nimport { USER_OBJECT } from './user/const';\nimport ApiUser, { type UserPayload } from './user/ApiUser';\n\nexport const getUser = () : ApiUser | undefined => getCurrentContext().nonHeaderContext?.get(USER_OBJECT) as ApiUser | undefined;\n\nexport const isUserExist = () => getUser()?.id;\n\nconst checkUserPermissions = (\n entityId: string,\n entityType: Exclude<keyof UserPayload, 'accountType' | 'createdAt'>,\n) => !isUserExist() || Object.hasOwn(getUser()!.permissions[entityType], entityId);\n\nexport const checkFleetPermission = (fleetId: string) => checkUserPermissions(fleetId, 'fleets');\nexport const checkBusinessModelPermission = (businessModelId: string) => checkUserPermissions(businessModelId, 'businessModels');\nexport const checkDemandSourcePermission = (demandSourceId: string) => checkUserPermissions(demandSourceId, 'demandSources');\n","import type ApiUser from './user';\n\n// eslint-disable-next-line import/prefer-default-export\nexport class UnauthorizedAccessError extends Error {\n constructor(public user: ApiUser | null = null, message = 'UnauthorizedAccessError') {\n super(message);\n this.name = 'UnauthorizedAccessError';\n }\n}\n","import * as jwt from 'jsonwebtoken';\n\nexport const AUTHORIZATION_METHODS = {\n NONE: 'NONE',\n BASIC: 'BASIC',\n JWT: 'JWT',\n};\n\nconst AUTHORIZATION_ACTIONS = {\n [AUTHORIZATION_METHODS.NONE]: () => undefined,\n [AUTHORIZATION_METHODS.BASIC]: (authorizationSettings: any) => {\n const { username, password } = authorizationSettings;\n const encodedCredentials = Buffer.from(`${username}:${password}`).toString('base64');\n return `Basic ${encodedCredentials}`;\n },\n [AUTHORIZATION_METHODS.JWT]: (authorizationSettings: any) => {\n const { secret } = authorizationSettings;\n if (secret) {\n return `Bearer ${jwt.sign({}, secret, { expiresIn: 10 })}`;\n }\n return undefined;\n },\n};\n\nexport const getAuthorizationHeader = (authorizationSettings: { method: string } | undefined): string | undefined => {\n const authorizationMethod = authorizationSettings?.method;\n\n if (!authorizationMethod || !AUTHORIZATION_ACTIONS[authorizationMethod]) {\n return undefined;\n }\n\n return AUTHORIZATION_ACTIONS[authorizationMethod](authorizationSettings);\n};\n","import type { LoggerInstanceManager } from '@autofleet/logger';\nimport * as outbreak from '@autofleet/outbreak';\nimport User, {\n middleware,\n eagerLoadPermissionsMiddleware,\n middlewareWithDecode,\n getDecodedBearer,\n appMiddleware,\n createOrSetRabbitTrace,\n} from './user';\nimport { authFromUserIdHeaderPlugin } from './user/fastify';\nimport { type UserPayload, CONTEXTS_IDS_HEADER } from './user/ApiUser';\nimport {\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n} from './check-permission';\nimport { UnauthorizedAccessError } from './errors';\nimport { getRefreshTokenSecret, getTokenSecret } from './secret-getter';\nimport { AUTHORIZATION_METHODS, getAuthorizationHeader } from './authorization';\n\nconst getCurrentPayload = outbreak.getCurrentContext;\n\ntype OutbreakOptions = Parameters<typeof outbreak.default>[0];\ntype LoggerWithContextMiddleware = Partial<Pick<LoggerInstanceManager, 'addContextMiddleware'>>;\nconst enableTracing = ({ outbreakOptions = {}, logger }: { outbreakOptions?: OutbreakOptions, logger?: LoggerWithContextMiddleware } = {}): void => {\n outbreak.default({\n headersPrefix: 'x-af',\n contextMiddlewareGetter: logger?.addContextMiddleware,\n ...outbreakOptions,\n });\n};\n\nconst { traceTypes, newTrace } = outbreak;\n\nexport {\n traceTypes,\n newTrace,\n enableTracing,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n getRefreshTokenSecret,\n getTokenSecret,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n type UserPayload,\n CONTEXTS_IDS_HEADER,\n authFromUserIdHeaderPlugin,\n};\n\nexport default {\n traceTypes,\n newTrace,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n CONTEXTS_IDS_HEADER,\n authFromUserIdHeaderPlugin,\n};\n"]}
|
package/lib/index.d.cts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import * as fastify from 'fastify';
|
|
2
|
+
import { FastifyPluginCallback } from 'fastify';
|
|
3
|
+
import * as express from 'express';
|
|
4
|
+
import { Handler, Request } from 'express';
|
|
1
5
|
import { LoggerInstanceManager } from '@autofleet/logger';
|
|
2
6
|
import * as outbreak from '@autofleet/outbreak';
|
|
3
7
|
import { newTrace as newTrace$1 } from '@autofleet/outbreak';
|
|
@@ -25,7 +29,6 @@ interface PartialUserPayload {
|
|
|
25
29
|
drivers?: EntityPermissions;
|
|
26
30
|
businessAccounts?: EntityPermissions;
|
|
27
31
|
}
|
|
28
|
-
type CustomPermissionLoader = (string: any) => Promise<UserPayload>;
|
|
29
32
|
declare class ApiUser {
|
|
30
33
|
id?: string;
|
|
31
34
|
accountType?: AccountType;
|
|
@@ -37,7 +40,7 @@ declare class ApiUser {
|
|
|
37
40
|
readonly emptyUser: boolean;
|
|
38
41
|
constructor(id?: string, accountType?: AccountType, elevatedPermissions?: PartialUserPayload, contextIds?: string[]);
|
|
39
42
|
getUserPermissions(): Promise<UserPayload>;
|
|
40
|
-
useCustomPermissionLoader(customPermissionLoader:
|
|
43
|
+
useCustomPermissionLoader(customPermissionLoader: (userId: string) => UserPayload | PromiseLike<UserPayload>): Promise<UserPayload>;
|
|
41
44
|
get businessModels(): string[] | undefined;
|
|
42
45
|
get fleets(): string[] | undefined;
|
|
43
46
|
get demandSources(): string[] | undefined;
|
|
@@ -50,24 +53,39 @@ declare class ApiUser {
|
|
|
50
53
|
getUserAppPermissions(appId: any, clientSecret: any): Promise<any>;
|
|
51
54
|
}
|
|
52
55
|
|
|
53
|
-
|
|
56
|
+
type CustomPermissionLoader = (userId: string) => Promise<UserPayload>;
|
|
57
|
+
interface AuthFromUserIdHeaderOptions {
|
|
54
58
|
eagerLoadUserPermissions?: boolean;
|
|
55
59
|
eagerLoadUserPermissionsLegacy?: boolean;
|
|
56
60
|
customPermissionLoader?: CustomPermissionLoader;
|
|
57
|
-
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
declare module 'express-serve-static-core' {
|
|
64
|
+
interface Request {
|
|
65
|
+
user: ApiUser;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
declare const middleware: (options?: AuthFromUserIdHeaderOptions) => Handler;
|
|
58
69
|
declare const middlewareWithDecode: (options?: {
|
|
59
70
|
eagerLoadUserPermissions?: boolean;
|
|
60
71
|
eagerLoadUserPermissionsLegacy?: boolean;
|
|
61
72
|
returnErrorIfNoToken?: boolean;
|
|
62
|
-
}) =>
|
|
73
|
+
}) => Handler;
|
|
63
74
|
declare const appMiddleware: (options: {
|
|
64
75
|
appId: string;
|
|
65
76
|
clientSecret: string;
|
|
66
|
-
}) =>
|
|
67
|
-
declare const eagerLoadPermissionsMiddleware:
|
|
68
|
-
declare const getDecodedBearer: (req:
|
|
77
|
+
}) => Handler;
|
|
78
|
+
declare const eagerLoadPermissionsMiddleware: Handler;
|
|
79
|
+
declare const getDecodedBearer: (req: Request) => any;
|
|
69
80
|
declare const createOrSetRabbitTrace: (trace: ReturnType<typeof newTrace$1> | undefined, userId: string | undefined) => Promise<void>;
|
|
70
81
|
|
|
82
|
+
declare module 'fastify' {
|
|
83
|
+
interface FastifyRequest {
|
|
84
|
+
user?: ApiUser;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
declare const authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions>;
|
|
88
|
+
|
|
71
89
|
declare const getUser: () => ApiUser | undefined;
|
|
72
90
|
declare const isUserExist: () => string;
|
|
73
91
|
declare const checkFleetPermission: (fleetId: string) => boolean;
|
|
@@ -130,40 +148,31 @@ declare const _default: {
|
|
|
130
148
|
readonly nonHeaderContext: Map<string, unknown>;
|
|
131
149
|
};
|
|
132
150
|
User: typeof ApiUser;
|
|
133
|
-
middleware: (options?:
|
|
134
|
-
eagerLoadUserPermissions?: boolean;
|
|
135
|
-
eagerLoadUserPermissionsLegacy?: boolean;
|
|
136
|
-
customPermissionLoader?: CustomPermissionLoader;
|
|
137
|
-
}) => (req: any, res: any, next: any) => Promise<any>;
|
|
151
|
+
middleware: (options?: AuthFromUserIdHeaderOptions) => express.Handler;
|
|
138
152
|
middlewareWithDecode: (options?: {
|
|
139
153
|
eagerLoadUserPermissions?: boolean;
|
|
140
154
|
eagerLoadUserPermissionsLegacy?: boolean;
|
|
141
155
|
returnErrorIfNoToken?: boolean;
|
|
142
|
-
}) =>
|
|
143
|
-
eagerLoadPermissionsMiddleware:
|
|
156
|
+
}) => express.Handler;
|
|
157
|
+
eagerLoadPermissionsMiddleware: express.Handler;
|
|
144
158
|
getCurrentPayload: () => {
|
|
145
159
|
type: "httpRequest" | "webSocket" | "rabbit" | "bull";
|
|
146
160
|
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
147
161
|
readonly context: Map<string, unknown>;
|
|
148
162
|
readonly nonHeaderContext: Map<string, unknown>;
|
|
149
163
|
} | Record<string, never>;
|
|
150
|
-
getDecodedBearer: (req:
|
|
164
|
+
getDecodedBearer: (req: express.Request) => any;
|
|
151
165
|
checkFleetPermission: (fleetId: string) => boolean;
|
|
152
166
|
checkBusinessModelPermission: (businessModelId: string) => boolean;
|
|
153
167
|
checkDemandSourcePermission: (demandSourceId: string) => boolean;
|
|
154
168
|
isUserExist: () => string;
|
|
155
|
-
getUser: () => ApiUser;
|
|
169
|
+
getUser: () => ApiUser | undefined;
|
|
156
170
|
UnauthorizedAccessError: typeof UnauthorizedAccessError;
|
|
157
171
|
appMiddleware: (options: {
|
|
158
172
|
appId: string;
|
|
159
173
|
clientSecret: string;
|
|
160
|
-
}) =>
|
|
161
|
-
createOrSetRabbitTrace: (trace:
|
|
162
|
-
type: "httpRequest" | "webSocket" | "rabbit" | "bull";
|
|
163
|
-
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
164
|
-
readonly context: Map<string, unknown>;
|
|
165
|
-
readonly nonHeaderContext: Map<string, unknown>;
|
|
166
|
-
}, userId: string) => Promise<void>;
|
|
174
|
+
}) => express.Handler;
|
|
175
|
+
createOrSetRabbitTrace: (trace: ReturnType<typeof outbreak.newTrace> | undefined, userId: string | undefined) => Promise<void>;
|
|
167
176
|
outbreak: typeof outbreak;
|
|
168
177
|
AUTHORIZATION_METHODS: {
|
|
169
178
|
NONE: string;
|
|
@@ -172,8 +181,9 @@ declare const _default: {
|
|
|
172
181
|
};
|
|
173
182
|
getAuthorizationHeader: (authorizationSettings: {
|
|
174
183
|
method: string;
|
|
175
|
-
}) => string;
|
|
184
|
+
} | undefined) => string | undefined;
|
|
176
185
|
CONTEXTS_IDS_HEADER: string;
|
|
186
|
+
authFromUserIdHeaderPlugin: fastify.FastifyPluginCallback<AuthFromUserIdHeaderOptions>;
|
|
177
187
|
};
|
|
178
188
|
|
|
179
|
-
export { AUTHORIZATION_METHODS, CONTEXTS_IDS_HEADER, UnauthorizedAccessError, ApiUser as User, type UserPayload, appMiddleware, checkBusinessModelPermission, checkDemandSourcePermission, checkFleetPermission, createOrSetRabbitTrace, _default as default, eagerLoadPermissionsMiddleware, enableTracing, getAuthorizationHeader, getCurrentPayload, getDecodedBearer, getRefreshTokenSecret, getTokenSecret, getUser, isUserExist, middleware, middlewareWithDecode, newTrace, traceTypes };
|
|
189
|
+
export { AUTHORIZATION_METHODS, CONTEXTS_IDS_HEADER, UnauthorizedAccessError, ApiUser as User, type UserPayload, appMiddleware, authFromUserIdHeaderPlugin, checkBusinessModelPermission, checkDemandSourcePermission, checkFleetPermission, createOrSetRabbitTrace, _default as default, eagerLoadPermissionsMiddleware, enableTracing, getAuthorizationHeader, getCurrentPayload, getDecodedBearer, getRefreshTokenSecret, getTokenSecret, getUser, isUserExist, middleware, middlewareWithDecode, newTrace, traceTypes };
|
package/lib/index.d.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import * as fastify from 'fastify';
|
|
2
|
+
import { FastifyPluginCallback } from 'fastify';
|
|
3
|
+
import * as express from 'express';
|
|
4
|
+
import { Handler, Request } from 'express';
|
|
1
5
|
import { LoggerInstanceManager } from '@autofleet/logger';
|
|
2
6
|
import * as outbreak from '@autofleet/outbreak';
|
|
3
7
|
import { newTrace as newTrace$1 } from '@autofleet/outbreak';
|
|
@@ -25,7 +29,6 @@ interface PartialUserPayload {
|
|
|
25
29
|
drivers?: EntityPermissions;
|
|
26
30
|
businessAccounts?: EntityPermissions;
|
|
27
31
|
}
|
|
28
|
-
type CustomPermissionLoader = (string: any) => Promise<UserPayload>;
|
|
29
32
|
declare class ApiUser {
|
|
30
33
|
id?: string;
|
|
31
34
|
accountType?: AccountType;
|
|
@@ -37,7 +40,7 @@ declare class ApiUser {
|
|
|
37
40
|
readonly emptyUser: boolean;
|
|
38
41
|
constructor(id?: string, accountType?: AccountType, elevatedPermissions?: PartialUserPayload, contextIds?: string[]);
|
|
39
42
|
getUserPermissions(): Promise<UserPayload>;
|
|
40
|
-
useCustomPermissionLoader(customPermissionLoader:
|
|
43
|
+
useCustomPermissionLoader(customPermissionLoader: (userId: string) => UserPayload | PromiseLike<UserPayload>): Promise<UserPayload>;
|
|
41
44
|
get businessModels(): string[] | undefined;
|
|
42
45
|
get fleets(): string[] | undefined;
|
|
43
46
|
get demandSources(): string[] | undefined;
|
|
@@ -50,24 +53,39 @@ declare class ApiUser {
|
|
|
50
53
|
getUserAppPermissions(appId: any, clientSecret: any): Promise<any>;
|
|
51
54
|
}
|
|
52
55
|
|
|
53
|
-
|
|
56
|
+
type CustomPermissionLoader = (userId: string) => Promise<UserPayload>;
|
|
57
|
+
interface AuthFromUserIdHeaderOptions {
|
|
54
58
|
eagerLoadUserPermissions?: boolean;
|
|
55
59
|
eagerLoadUserPermissionsLegacy?: boolean;
|
|
56
60
|
customPermissionLoader?: CustomPermissionLoader;
|
|
57
|
-
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
declare module 'express-serve-static-core' {
|
|
64
|
+
interface Request {
|
|
65
|
+
user: ApiUser;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
declare const middleware: (options?: AuthFromUserIdHeaderOptions) => Handler;
|
|
58
69
|
declare const middlewareWithDecode: (options?: {
|
|
59
70
|
eagerLoadUserPermissions?: boolean;
|
|
60
71
|
eagerLoadUserPermissionsLegacy?: boolean;
|
|
61
72
|
returnErrorIfNoToken?: boolean;
|
|
62
|
-
}) =>
|
|
73
|
+
}) => Handler;
|
|
63
74
|
declare const appMiddleware: (options: {
|
|
64
75
|
appId: string;
|
|
65
76
|
clientSecret: string;
|
|
66
|
-
}) =>
|
|
67
|
-
declare const eagerLoadPermissionsMiddleware:
|
|
68
|
-
declare const getDecodedBearer: (req:
|
|
77
|
+
}) => Handler;
|
|
78
|
+
declare const eagerLoadPermissionsMiddleware: Handler;
|
|
79
|
+
declare const getDecodedBearer: (req: Request) => any;
|
|
69
80
|
declare const createOrSetRabbitTrace: (trace: ReturnType<typeof newTrace$1> | undefined, userId: string | undefined) => Promise<void>;
|
|
70
81
|
|
|
82
|
+
declare module 'fastify' {
|
|
83
|
+
interface FastifyRequest {
|
|
84
|
+
user?: ApiUser;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
declare const authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions>;
|
|
88
|
+
|
|
71
89
|
declare const getUser: () => ApiUser | undefined;
|
|
72
90
|
declare const isUserExist: () => string;
|
|
73
91
|
declare const checkFleetPermission: (fleetId: string) => boolean;
|
|
@@ -130,40 +148,31 @@ declare const _default: {
|
|
|
130
148
|
readonly nonHeaderContext: Map<string, unknown>;
|
|
131
149
|
};
|
|
132
150
|
User: typeof ApiUser;
|
|
133
|
-
middleware: (options?:
|
|
134
|
-
eagerLoadUserPermissions?: boolean;
|
|
135
|
-
eagerLoadUserPermissionsLegacy?: boolean;
|
|
136
|
-
customPermissionLoader?: CustomPermissionLoader;
|
|
137
|
-
}) => (req: any, res: any, next: any) => Promise<any>;
|
|
151
|
+
middleware: (options?: AuthFromUserIdHeaderOptions) => express.Handler;
|
|
138
152
|
middlewareWithDecode: (options?: {
|
|
139
153
|
eagerLoadUserPermissions?: boolean;
|
|
140
154
|
eagerLoadUserPermissionsLegacy?: boolean;
|
|
141
155
|
returnErrorIfNoToken?: boolean;
|
|
142
|
-
}) =>
|
|
143
|
-
eagerLoadPermissionsMiddleware:
|
|
156
|
+
}) => express.Handler;
|
|
157
|
+
eagerLoadPermissionsMiddleware: express.Handler;
|
|
144
158
|
getCurrentPayload: () => {
|
|
145
159
|
type: "httpRequest" | "webSocket" | "rabbit" | "bull";
|
|
146
160
|
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
147
161
|
readonly context: Map<string, unknown>;
|
|
148
162
|
readonly nonHeaderContext: Map<string, unknown>;
|
|
149
163
|
} | Record<string, never>;
|
|
150
|
-
getDecodedBearer: (req:
|
|
164
|
+
getDecodedBearer: (req: express.Request) => any;
|
|
151
165
|
checkFleetPermission: (fleetId: string) => boolean;
|
|
152
166
|
checkBusinessModelPermission: (businessModelId: string) => boolean;
|
|
153
167
|
checkDemandSourcePermission: (demandSourceId: string) => boolean;
|
|
154
168
|
isUserExist: () => string;
|
|
155
|
-
getUser: () => ApiUser;
|
|
169
|
+
getUser: () => ApiUser | undefined;
|
|
156
170
|
UnauthorizedAccessError: typeof UnauthorizedAccessError;
|
|
157
171
|
appMiddleware: (options: {
|
|
158
172
|
appId: string;
|
|
159
173
|
clientSecret: string;
|
|
160
|
-
}) =>
|
|
161
|
-
createOrSetRabbitTrace: (trace:
|
|
162
|
-
type: "httpRequest" | "webSocket" | "rabbit" | "bull";
|
|
163
|
-
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
164
|
-
readonly context: Map<string, unknown>;
|
|
165
|
-
readonly nonHeaderContext: Map<string, unknown>;
|
|
166
|
-
}, userId: string) => Promise<void>;
|
|
174
|
+
}) => express.Handler;
|
|
175
|
+
createOrSetRabbitTrace: (trace: ReturnType<typeof outbreak.newTrace> | undefined, userId: string | undefined) => Promise<void>;
|
|
167
176
|
outbreak: typeof outbreak;
|
|
168
177
|
AUTHORIZATION_METHODS: {
|
|
169
178
|
NONE: string;
|
|
@@ -172,8 +181,9 @@ declare const _default: {
|
|
|
172
181
|
};
|
|
173
182
|
getAuthorizationHeader: (authorizationSettings: {
|
|
174
183
|
method: string;
|
|
175
|
-
}) => string;
|
|
184
|
+
} | undefined) => string | undefined;
|
|
176
185
|
CONTEXTS_IDS_HEADER: string;
|
|
186
|
+
authFromUserIdHeaderPlugin: fastify.FastifyPluginCallback<AuthFromUserIdHeaderOptions>;
|
|
177
187
|
};
|
|
178
188
|
|
|
179
|
-
export { AUTHORIZATION_METHODS, CONTEXTS_IDS_HEADER, UnauthorizedAccessError, ApiUser as User, type UserPayload, appMiddleware, checkBusinessModelPermission, checkDemandSourcePermission, checkFleetPermission, createOrSetRabbitTrace, _default as default, eagerLoadPermissionsMiddleware, enableTracing, getAuthorizationHeader, getCurrentPayload, getDecodedBearer, getRefreshTokenSecret, getTokenSecret, getUser, isUserExist, middleware, middlewareWithDecode, newTrace, traceTypes };
|
|
189
|
+
export { AUTHORIZATION_METHODS, CONTEXTS_IDS_HEADER, UnauthorizedAccessError, ApiUser as User, type UserPayload, appMiddleware, authFromUserIdHeaderPlugin, checkBusinessModelPermission, checkDemandSourcePermission, checkFleetPermission, createOrSetRabbitTrace, _default as default, eagerLoadPermissionsMiddleware, enableTracing, getAuthorizationHeader, getCurrentPayload, getDecodedBearer, getRefreshTokenSecret, getTokenSecret, getUser, isUserExist, middleware, middlewareWithDecode, newTrace, traceTypes };
|
package/lib/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
export{
|
|
1
|
+
import*as g from'@autofleet/outbreak';import {getCurrentContext,newTrace,traceTypes}from'@autofleet/outbreak';export{g as outbreak };import*as S from'jsonwebtoken';import S__default from'jsonwebtoken';import Ue from'node-cache';import xe from'object-hash';import b from'moment';import B from'@autofleet/network';var {DEPRECATED_JWT_SECRET:ue,JWT_NEW_SECRET:pe,DEPRECATED_REFRESH_JWT_SECRET:me,REFRESH_JWT_SECRET:fe,DEPRECATION_UNIX_TIMESTAMP:le}=process.env,k=(s,e,r)=>{let o=b(parseInt(le,10)*1e3);try{let t;if(s){let{iat:i}=S__default.decode(s);t=b(i*1e3);}else t=b();return t.isBefore(o)?e:r}catch{return r}},Ee=s=>k(s,me,fe),C=s=>k(s,ue,pe);var w=s=>s.replace("Bearer ",""),_=(s,e)=>{let r=w(s);return S.verify(r,C(r))};var Pe="00000000-0000-0000-0000-000000000000",ge="ffffffff-ffff-ffff-ffff-ffffffffffff",h="[0-9a-f]",ye="[1-8]",he=new RegExp(`^(?:${h}{8}-${h}{4}-${ye}${h}{3}-[89ab]${h}{3}-${h}{12}|${Pe}|${ge})$`,"i");function j(s){return typeof s=="string"&&he.test(s)}var $=10,F=process.env.API_GATEWAY_URL||"https://api.autofleet.io",O=new B({serviceName:"IDENTITY_MS",retries:3,retryCondition:()=>true,cache:process.env.NODE_ENV!=="test"?{maxAge:$*1e3}:void 0}),A=new B({baseURL:F,serviceUrl:F,retries:3,retryCondition:()=>true,cache:process.env.NODE_ENV!=="test"?{maxAge:$*1e3}:void 0});var l="x-af-elevated-permissions",E="x-af-context-ids",f=new Ue({stdTTL:10}),J=(s,e)=>{let r={...s,fleets:{...s?.fleets},businessModels:{...s?.businessModels},demandSources:{...s?.demandSources}};for(let o of e)Object.keys(o).forEach(t=>{r[t]??={},Object.entries(o[t]).forEach(([i,n])=>{r[t][i]=(r[t][i]||[]).concat(n);});});return r},u=class{constructor(e,r,o,t){this.id=e;this.accountType=r;this.contextIds=t;this.privateElevatedPermissionsHash=new Map;this.appPermission={};this.emptyUser=!!e,o&&this.privateElevatedPermissionsHash.set(Symbol("initial"),o);}async getUserPermissions(){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let e=xe({id:this.id,contextIds:this.contextIds}),r=f.get(e);return r||({data:r}=await O.get(`/api/v1/users/${this.id}/authorization-payload`,{params:{contextIds:this.contextIds}}),f.set(e,r)),this.accountType=r.accountType,this.privatePermissions=r,this.privatePermissions}async useCustomPermissionLoader(e){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let r=this.id,o=f.get(r);if(o)return this.privatePermissions=o,o;let t=await e(this.id);return f.set(r,t),this.privatePermissions=t,this.privatePermissions}get businessModels(){return this.getUserProperty("businessModels")}get fleets(){return this.getUserProperty("fleets")}get demandSources(){return this.getUserProperty("demandSources")}getUserProperty(e){if(!this.privatePermissions)throw new Error(`Cannot get ${e} without calling (async) getUserPermissions before`);return Object.keys(this.privatePermissions[e]||{})}get elevatedPermissions(){return J(void 0,this.privateElevatedPermissionsHash.values())}get permissions(){if(!this.privatePermissions)throw new Error("Cannot get permissions without calling (async) getUserPermissions before");return J(this.privatePermissions,this.privateElevatedPermissionsHash.values())}elevatePermissions(e){let r=Symbol();Object.values(e).forEach(n=>{Object.keys(n).forEach(a=>{if(!j(a))throw new Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${a}`)});});let o=getCurrentContext();if(!o)throw new Error("Cannot find current user cross services trace");let t=JSON.parse(o.context[l]||"{}"),i=Object.assign(t,e);return this.privateElevatedPermissionsHash.set(r,i),o.context.set(l,JSON.stringify(this.elevatedPermissions)),()=>{this.privateElevatedPermissionsHash.delete(r),o.context.set(l,JSON.stringify(this.elevatedPermissions));}}async getUserPermissionsLegacy(){if(!this.id)return;if(this.privatePermissionsLegacy)return this.privatePermissionsLegacy;let{data:e}=await O.get(`/api/v1/users/${this.id}/authorization-payload-legacy`);return this.privatePermissionsLegacy=e,this.privatePermissionsLegacy}get permissionsLegacy(){if(!this.privatePermissionsLegacy)throw new Error("Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before");return this.privatePermissionsLegacy}async getUserAppPermissions(e,r){if(!this.id||!e||!r)return;let o=this.appPermission[e];if(o)return o;let t=`${this.id}:${e}`,i=f.get(t);if(i)return this.appPermission[e]=i,i;let{data:n}=await A.post(`/api/v1/apps/${e}/get-user-payload`,{userId:this.id},{headers:{"x-autofleet-apps-secret":r}});return f.set(t,n),this.appPermission[e]=n,this.appPermission[e]}};var W=async(s,e)=>{let{data:r}=await A.post("/api/v1/auth",{bearer:s,appId:e});return r};var P=class extends Error{constructor(){super(...arguments);this.name="AppDoesNotExist";this.message="app does not exist";}};var G="identity-ms",z="accessToken",m="userObject",U="x-af-user-id",H="X-IAF-ORIGIN-SERVICE",I="x-af-user-permissions",X=H.toLowerCase(),V="x-autofleet-apps-secret";var T=async(s,e)=>{let r=e[H]||e[X]||"";if(!Array.isArray(r)&&r.toLowerCase()===G)return;let{eagerLoadUserPermissions:o,eagerLoadUserPermissionsLegacy:t,customPermissionLoader:i}=s,n=e[U];if(!n||Array.isArray(n))return;let a=e[l]?.length>0?JSON.parse(e[l]):{},c=e?.[E]?.split(","),d=new u(n,"user",a,c);return o&&(i?await d.useCustomPermissionLoader(i):await d.getUserPermissions()),t&&await d.getUserPermissionsLegacy(),getCurrentContext().nonHeaderContext?.set(m,d),d};var Y=(s={})=>async(e,r,o)=>{try{let t=await T(s,e.headers);t&&(e.user=t,e.headers[I]=t),o();}catch{r.status(401).json({error:"cannot authenticate user"});}},Z=(s={})=>async(e,r,o)=>{let{eagerLoadUserPermissions:t,eagerLoadUserPermissionsLegacy:i,returnErrorIfNoToken:n}=s,a;if(e.headers.authorization){try{a=await _(e.headers.authorization);}catch(y){y instanceof S__default.TokenExpiredError?r.status(401).json({errors:["Access token expired"]}):y instanceof S__default.JsonWebTokenError?r.status(400).json({errors:[y.message]}):r.status(500).json({errors:["Server error while parsing token"]});return}let c=a?.user?.id;c&&(e.headers[U]=c);let d=e.headers?.[E]?.split(","),p=new u(c,a?.user?.accountType,void 0,d);(t||i)&&await Promise.all([t&&p.getUserPermissions(),i&&p.getUserPermissionsLegacy()]),e.user=p,getCurrentContext().nonHeaderContext?.set(m,p),e.headers[I]=p;}else if(n){r.status(401).json({errors:["No token provided"]});return}o();},Q=s=>async(e,r,o)=>{let{appId:t,clientSecret:i}=s,n;if(!e.headers.authorization){r.status(401).json({errors:["No token provided"]});return}try{if(n=await W(e.headers.authorization,t),!n)throw new P}catch(p){if(p instanceof S__default.TokenExpiredError){r.status(401).json({errors:["Access token expired"]});return}if([S__default.JsonWebTokenError,P].some(y=>p instanceof y)){r.status(400).json({errors:[p.message]});return}r.status(500).json({errors:["Server error while parsing token"]});return}let a=n?.userId;a&&(e.headers[U]=a);let c=new u(a);t&&(e.headers[V]=i,await c.getUserAppPermissions(t,i)),e.user=c;let d=getCurrentContext().nonHeaderContext;d?.set(m,c),d?.set(z,w(e.headers.authorization)),e.headers[I]=c,o();},q=async(s,e,r)=>{await s.user.getUserPermissions(),r();},ee=s=>s.headers.authorization?_(s.headers.authorization):null,se=async(s,e)=>{let r=new u(e);await r.getUserPermissions(),s??=newTrace(traceTypes.RABBIT),s.nonHeaderContext.set(m,r);},re=u;var N=(s,e,r)=>{s.addHook("onRequest",async(o,t)=>{try{let i=await T(e,o.headers);i&&s.decorateRequest("user",i);}catch{t.status(401).send({error:"cannot authenticate user"});}}),r();};N[Symbol.for("skip-override")]=true;var v=()=>getCurrentContext().nonHeaderContext?.get(m),L=()=>v()?.id,D=(s,e)=>!L()||Object.hasOwn(v().permissions[e],s),te=s=>D(s,"fleets"),oe=s=>D(s,"businessModels"),ie=s=>D(s,"demandSources");var R=class extends Error{constructor(r=null,o="UnauthorizedAccessError"){super(o);this.user=r;this.name="UnauthorizedAccessError";}};var x={NONE:"NONE",BASIC:"BASIC",JWT:"JWT"},ne={[x.NONE]:()=>{},[x.BASIC]:s=>{let{username:e,password:r}=s;return `Basic ${Buffer.from(`${e}:${r}`).toString("base64")}`},[x.JWT]:s=>{let{secret:e}=s;if(e)return `Bearer ${S.sign({},e,{expiresIn:10})}`}},ce=s=>{let e=s?.method;if(!(!e||!ne[e]))return ne[e](s)};var Re=g.getCurrentContext,As=({outbreakOptions:s={},logger:e}={})=>{g.default({headersPrefix:"x-af",contextMiddlewareGetter:e?.addContextMiddleware,...s});},{traceTypes:be,newTrace:Ce}=g;var Is={traceTypes:be,newTrace:Ce,User:re,middleware:Y,middlewareWithDecode:Z,eagerLoadPermissionsMiddleware:q,getCurrentPayload:Re,getDecodedBearer:ee,checkFleetPermission:te,checkBusinessModelPermission:oe,checkDemandSourcePermission:ie,isUserExist:L,getUser:v,UnauthorizedAccessError:R,appMiddleware:Q,createOrSetRabbitTrace:se,outbreak:g,AUTHORIZATION_METHODS:x,getAuthorizationHeader:ce,CONTEXTS_IDS_HEADER:E,authFromUserIdHeaderPlugin:N};
|
|
2
|
+
export{x as AUTHORIZATION_METHODS,E as CONTEXTS_IDS_HEADER,R as UnauthorizedAccessError,re as User,Q as appMiddleware,N as authFromUserIdHeaderPlugin,oe as checkBusinessModelPermission,ie as checkDemandSourcePermission,te as checkFleetPermission,se as createOrSetRabbitTrace,Is as default,q as eagerLoadPermissionsMiddleware,As as enableTracing,ce as getAuthorizationHeader,Re as getCurrentPayload,ee as getDecodedBearer,Ee as getRefreshTokenSecret,C as getTokenSecret,v as getUser,L as isUserExist,Y as middleware,Z as middlewareWithDecode,Ce as newTrace,be as traceTypes};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/secret-getter.ts","../src/utils.ts","../src/services.ts","../src/user/ApiUser.ts","../src/app-auth.ts","../src/exceptions/appDoesNotExist.ts","../src/user/index.ts","../src/check-permission.ts","../src/errors.ts","../src/authorization.ts","../src/index.ts"],"names":["DEPRECATED_JWT_SECRET","JWT_NEW_SECRET","DEPRECATED_REFRESH_JWT_SECRET","REFRESH_JWT_SECRET","DEPRECATION_UNIX_TIMESTAMP","getRelevantSecret","token","deprecatedSecret","newSecret","deprecationTime","moment","unixTime","iat","jwt","getRefreshTokenSecret","getTokenSecret","getAuthFromBearer","bearer","decodeBearer","appSecret","N","EMPTY_UUID","FULL_UUID","VALID_CHARS_REGEX","UUID_VERSION_REGEX","UUID_REGEX","validateUUID","uuid","CACHE_LIFETIME_IN_SEC","apiGwUrl","IdentityNetwork","Network","AutofleetApiNetwork","ELEVATED_PERMISSIONS_HEADER","CONTEXTS_IDS_HEADER","userCache","NodeCache","mergePermissions","target","sources","permissions","source","entityType","entityId","perms","ApiUser","id","accountType","elevatedPermissions","contextIds","cacheKey","objectHash","data","customPermissionLoader","cachedResult","key","addedPermissions","elevationId","entityIds","currentUserTrace","getCurrentContext","currentElevation","newElevation","appId","clientSecret","currentAppPermission","decodeAppBearer","decoded","AppDoesNotExist","IDENTITY_MS","ACCESS_TOKEN","USER_OBJECT","USER_TRACING_HEADER","ORIGIN_HEADER","USER_PERMISSIONS_HEADER","LOWER_CASE_ORIGIN_HEADER","middleware","options","req","res","next","eagerLoadUserPermissions","eagerLoadUserPermissionsLegacy","userId","elevatedPermissionsFromHeader","userObject","middlewareWithDecode","returnErrorIfNoToken","e","TokenExpiredError","JsonWebTokenError","appMiddleware","Err","currentTraceContext","eagerLoadPermissionsMiddleware","getDecodedBearer","createOrSetRabbitTrace","trace","newTrace","traceTypes","user_default","getUser","isUserExist","checkFleetPermission","fleetId","checkBusinessModelPermission","businessModelId","checkDemandSourcePermission","demandSourceId","UnauthorizedAccessError","user","message","AUTHORIZATION_METHODS","AUTHORIZATION_ACTIONS","authorizationSettings","username","password","secret","se","getAuthorizationHeader","authorizationMethod","getCurrentPayload","enableTracing","outbreakOptions","logger","outbreak","index_default"],"mappings":"+VAGA,IAAM,CACJ,qBAAAA,CAAAA,EAAAA,CAAuB,eAAAC,EACvB,CAAA,6BAAA,CAAAC,GAA+B,kBAAAC,CAAAA,EAAAA,CAC/B,0BAAAC,CAAAA,EACF,CAAI,CAAA,OAAA,CAAQ,IAENC,CAAoB,CAAA,CAACC,EAA2BC,CAA0BC,CAAAA,CAAAA,GAA8B,CAC5G,IAAMC,CAAAA,CAAkBC,EAAO,QAASN,CAAAA,EAAAA,CAA4B,EAAE,CAAI,CAAA,GAAI,EAC9E,GAAI,CACF,IAAIO,CACJ,CAAA,GAAIL,CAAO,CAAA,CACT,GAAM,CAAE,IAAAM,CAAI,CAAA,CAAIC,YAAI,MAAOP,CAAAA,CAAK,EAChCK,CAAWD,CAAAA,CAAAA,CAAOE,CAAM,CAAA,GAAI,EAC9B,CAAA,KACED,EAAWD,CAAO,EAAA,CAEpB,OAAOC,CAAS,CAAA,QAAA,CAASF,CAAe,CAAIF,CAAAA,CAAAA,CAAmBC,CACjE,CAAA,KAAY,CACV,OAAOA,CACT,CACF,CAAA,CAEaM,GAAyBR,CAA2BD,EAAAA,CAAAA,CAAkBC,EAAOJ,EAA+BC,CAAAA,EAAkB,EAC9HY,CA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AQ,CAAAA,CAAAA,CACA,cAAAlB,CACA,CAAA,sBAAA,CAAAK,EACA,QAAA6B,CAAAA,CAAAA,CACA,sBAAAb,CACA,CAAA,sBAAA,CAAAO,EACA,CAAA,mBAAA,CAAArF,CACF","file":"index.js","sourcesContent":["import jwt from 'jsonwebtoken';\nimport moment from 'moment';\n\nconst {\n DEPRECATED_JWT_SECRET, JWT_NEW_SECRET,\n DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET,\n DEPRECATION_UNIX_TIMESTAMP,\n} = process.env;\n\nconst getRelevantSecret = (token: string | undefined, deprecatedSecret: string, newSecret: string): string => {\n const deprecationTime = moment(parseInt(DEPRECATION_UNIX_TIMESTAMP, 10) * 1000);\n try {\n let unixTime: moment.Moment;\n if (token) {\n const { iat } = jwt.decode(token) as jwt.JwtPayload;\n unixTime = moment(iat * 1000);\n } else {\n unixTime = moment();\n }\n return unixTime.isBefore(deprecationTime) ? deprecatedSecret : newSecret;\n } catch (e) {\n return newSecret;\n }\n};\n\nexport const getRefreshTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET);\nexport const getTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_JWT_SECRET, JWT_NEW_SECRET);\n","import type { UUID } from 'node:crypto';\nimport * as jwt from 'jsonwebtoken';\nimport { getTokenSecret } from './secret-getter';\n\nconst CONTEXT_PROPS = ['fleetId', 'businessModelId', 'demandSourceId'];\nconst CONTEXT_MAP_PROPS = {\n fleet: 'fleets',\n business: 'businessModels',\n demand: 'demandSources',\n};\n\nexport const getAuthFromBearer = (bearer: string): string => bearer.replace('Bearer ', '');\n\nexport const decodeBearer = (bearer: string, appSecret?: string): any => {\n const token = getAuthFromBearer(bearer);\n const decoded = jwt.verify(token, appSecret || getTokenSecret(token));\n return decoded;\n};\n\nexport const parsePermissions = (contextId, decodedToken): any => {\n if (!decodedToken) { return []; }\n const { contexts } = decodedToken;\n const activeContext = contexts.find((context) => context.id === contextId);\n\n const permissionsValue = `${activeContext.permissions?.map((cp) => `${cp},`)}`;\n\n return {\n key: activeContext.entityId,\n value: permissionsValue,\n };\n};\n\nexport const getEntitiesFromContext = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n\n const attributes = {};\n contexts.forEach((context) => {\n const prop = CONTEXT_MAP_PROPS[context.subSystem || 'business'];\n\n const permissions = parsePermissions(context.id, decodedToken);\n // eslint-disable-next-line no-unused-expressions\n attributes[prop]\n ? attributes[prop][permissions.key] = permissions.value\n : attributes[prop] = { [permissions.key]: permissions.value };\n });\n\n return attributes;\n};\n\nexport const getContextAttributes = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n const attributes = {};\n contexts.forEach((context) => {\n CONTEXT_PROPS.forEach((prop) => {\n if (context[prop]) {\n const contextPropWrapped = [context[prop]];\n // eslint-disable-next-line no-unused-expressions\n attributes[prop]\n ? attributes[prop] = attributes[prop].concat(contextPropWrapped)\n : attributes[prop] = contextPropWrapped;\n }\n });\n });\n return attributes;\n};\n\nconst EMPTY_UUID = '00000000-0000-0000-0000-000000000000';\nconst FULL_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff';\nconst VALID_CHARS_REGEX = '[0-9a-f]';\nconst UUID_VERSION_REGEX = '[1-8]';\nconst UUID_REGEX = new RegExp(`^(?:${VALID_CHARS_REGEX}{8}-${VALID_CHARS_REGEX}{4}-${UUID_VERSION_REGEX}${VALID_CHARS_REGEX}{3}-[89ab]${VALID_CHARS_REGEX}{3}-${VALID_CHARS_REGEX}{12}|${EMPTY_UUID}|${FULL_UUID})$`, 'i');\nexport function validateUUID(uuid: unknown): uuid is UUID {\n return typeof uuid === 'string' && UUID_REGEX.test(uuid);\n}\n","import Network from '@autofleet/network';\n\nconst CACHE_LIFETIME_IN_SEC = 10;\nconst apiGwUrl = process.env.API_GATEWAY_URL || 'https://api.autofleet.io';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const IdentityNetwork = new Network({\n serviceName: 'IDENTITY_MS',\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n\nexport const AutofleetApiNetwork = new Network({\n baseURL: apiGwUrl,\n serviceUrl: apiGwUrl,\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n","import NodeCache from 'node-cache';\nimport objectHash from 'object-hash';\nimport { getCurrentContext } from '@autofleet/outbreak';\nimport { validateUUID } from '../utils';\nimport { AutofleetApiNetwork, IdentityNetwork } from '../services';\n\nexport type AccountType = 'client' | 'user' | 'service' | 'driver'\ninterface EntityPermissions {\n [key: string]: string[];\n}\n\nexport const ELEVATED_PERMISSIONS_HEADER = 'x-af-elevated-permissions';\nexport const CONTEXTS_IDS_HEADER = 'x-af-context-ids';\n\nexport interface UserPayload {\n businessModels: EntityPermissions;\n fleets: EntityPermissions;\n demandSources: EntityPermissions;\n businessAccounts?: EntityPermissions;\n accountType?: AccountType;\n contexts?: EntityPermissions;\n createdAt?: string;\n}\n\nexport interface PartialUserPayload {\n businessModels?: EntityPermissions;\n fleets?: EntityPermissions;\n demandSources?: EntityPermissions;\n vehicles?: EntityPermissions;\n drivers?: EntityPermissions;\n businessAccounts?: EntityPermissions;\n}\n\nexport type CustomPermissionLoader = (string) => Promise<UserPayload>;\n\nconst userCache = new NodeCache({ stdTTL: 10 });\n\nconst mergePermissions = (target: UserPayload, sources: Iterable<PartialUserPayload>): UserPayload => {\n const permissions: UserPayload = {\n ...target,\n fleets: { ...target?.fleets },\n businessModels: { ...target?.businessModels },\n demandSources: { ...target?.demandSources },\n // Clone other nested objects as needed\n };\n\n // eslint-disable-next-line no-restricted-syntax\n for (const source of sources) {\n Object.keys(source).forEach((entityType) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType] ??= {};\n Object.entries(source[entityType]!).forEach(([entityId, perms]) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType][entityId] = (permissions[entityType][entityId] || []).concat(perms);\n });\n });\n }\n\n return permissions;\n};\n\nexport default class ApiUser {\n private privatePermissions: UserPayload | undefined;\n\n private readonly privateElevatedPermissionsHash = new Map<symbol, PartialUserPayload | undefined>();\n\n private privatePermissionsLegacy: any;\n\n private readonly appPermission: {[key: string]: any; } = {};\n\n public readonly emptyUser: boolean;\n\n constructor(public id? : string, public accountType?: AccountType, elevatedPermissions?: PartialUserPayload, public contextIds?: string[]) {\n this.emptyUser = !!id;\n if (elevatedPermissions) {\n this.privateElevatedPermissionsHash.set(Symbol('initial'), elevatedPermissions);\n }\n }\n\n async getUserPermissions(): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n const cacheKey = objectHash({\n id: this.id,\n contextIds: this.contextIds,\n });\n\n let data = userCache.get<UserPayload>(cacheKey);\n\n if (!data) {\n ({ data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload`, { params: { contextIds: this.contextIds } }));\n userCache.set(cacheKey, data);\n }\n\n this.accountType = data.accountType;\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n async useCustomPermissionLoader(customPermissionLoader: any): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n\n const cacheKey = this.id;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.privatePermissions = cachedResult;\n return cachedResult;\n }\n\n const data = await customPermissionLoader(this.id);\n userCache.set(cacheKey, data);\n\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n get businessModels(): string[] | undefined {\n return this.getUserProperty('businessModels');\n }\n\n get fleets(): string[] | undefined {\n return this.getUserProperty('fleets');\n }\n\n get demandSources(): string[] | undefined {\n return this.getUserProperty('demandSources');\n }\n\n private getUserProperty(key: keyof UserPayload): string[] | undefined {\n if (!this.privatePermissions) {\n throw new Error(`Cannot get ${key} without calling (async) getUserPermissions before`);\n }\n return Object.keys(this.privatePermissions[key] || {});\n }\n\n get elevatedPermissions(): UserPayload {\n return mergePermissions(undefined, this.privateElevatedPermissionsHash.values());\n }\n\n get permissions(): UserPayload | undefined {\n if (!this.privatePermissions) {\n throw new Error('Cannot get permissions without calling (async) getUserPermissions before');\n }\n\n return mergePermissions(this.privatePermissions, this.privateElevatedPermissionsHash.values());\n }\n\n elevatePermissions(addedPermissions: PartialUserPayload): () => void {\n // @itayankri is concerned about memory consumption, so create a symbol with no description, to avoid assigning memory for the description string\n // eslint-disable-next-line symbol-description\n const elevationId = Symbol();\n\n // Validate that the added permissions are valid UUIDs\n Object.values(addedPermissions).forEach((entityIds) => {\n Object.keys(entityIds).forEach((entityId) => {\n if (!validateUUID(entityId)) {\n throw new Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${entityId}`);\n }\n });\n });\n\n const currentUserTrace = getCurrentContext();\n if (!currentUserTrace) {\n throw new Error('Cannot find current user cross services trace');\n }\n\n const currentElevation = JSON.parse(currentUserTrace.context[ELEVATED_PERMISSIONS_HEADER] || '{}');\n const newElevation = Object.assign(currentElevation, addedPermissions);\n this.privateElevatedPermissionsHash.set(elevationId, newElevation);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n return () => {\n this.privateElevatedPermissionsHash.delete(elevationId);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n };\n }\n\n async getUserPermissionsLegacy() {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissionsLegacy) {\n return this.privatePermissionsLegacy;\n }\n const { data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload-legacy`);\n\n this.privatePermissionsLegacy = data;\n return this.privatePermissionsLegacy;\n }\n\n get permissionsLegacy(): any {\n if (!this.privatePermissionsLegacy) {\n throw new Error('Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before');\n }\n return this.privatePermissionsLegacy;\n }\n\n async getUserAppPermissions(appId, clientSecret) {\n if (!this.id || !appId || !clientSecret) {\n return undefined;\n }\n const currentAppPermission = this.appPermission[appId];\n\n if (currentAppPermission) {\n return currentAppPermission;\n }\n\n const cacheKey = `${this.id}:${appId}`;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.appPermission[appId] = cachedResult;\n return cachedResult;\n }\n\n const { data } = await AutofleetApiNetwork.post(`/api/v1/apps/${appId}/get-user-payload`, {\n userId: this.id,\n }, {\n headers: {\n 'x-autofleet-apps-secret': clientSecret,\n },\n });\n\n userCache.set(cacheKey, data);\n this.appPermission[appId] = data;\n return this.appPermission[appId];\n }\n}\n","import { AutofleetApiNetwork } from './services';\n\nexport const decodeAppBearer = async (bearer: string, appId: string): Promise<any> => {\n const { data: decoded } = await AutofleetApiNetwork.post('/api/v1/auth', { bearer, appId });\n return decoded;\n};\n\nexport const getClientSecret = async (appId: string): Promise<any> => {\n const { data: secret } = await AutofleetApiNetwork.get(`/api/v1/auth/client-secret/${appId}`);\n return secret;\n};\n","export default class AppDoesNotExist extends Error {\n name = 'AppDoesNotExist';\n\n message = 'app does not exist';\n}\n","import { getCurrentContext, newTrace, traceTypes } from '@autofleet/outbreak';\nimport { TokenExpiredError, JsonWebTokenError } from 'jsonwebtoken';\nimport ApiUser, { CONTEXTS_IDS_HEADER, CustomPermissionLoader, ELEVATED_PERMISSIONS_HEADER } from './ApiUser';\nimport { decodeAppBearer } from '../app-auth';\nimport AppDoesNotExist from '../exceptions/appDoesNotExist';\nimport { decodeBearer, getAuthFromBearer } from '../utils';\n\nconst IDENTITY_MS = 'identity-ms';\nconst ACCESS_TOKEN = 'accessToken';\nexport const USER_OBJECT = 'userObject';\nconst USER_TRACING_HEADER = 'x-af-user-id';\nconst ORIGIN_HEADER = 'X-IAF-ORIGIN-SERVICE';\nconst USER_PERMISSIONS_HEADER = 'x-af-user-permissions';\nconst LOWER_CASE_ORIGIN_HEADER = ORIGIN_HEADER.toLowerCase();\n\nexport const middleware = (options: {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n customPermissionLoader?: CustomPermissionLoader;\n} = {}) => async (req, res, next): Promise<any> => {\n try {\n const originHeader: string = req.headers[ORIGIN_HEADER] || req.headers[LOWER_CASE_ORIGIN_HEADER] || '';\n if (originHeader.toLowerCase() === IDENTITY_MS) {\n return next();\n }\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n customPermissionLoader,\n } = options;\n const userId = req.headers[USER_TRACING_HEADER];\n if (!userId) {\n return next();\n }\n\n const elevatedPermissionsFromHeader = req.headers[ELEVATED_PERMISSIONS_HEADER]?.length > 0 ? JSON.parse(req.headers[ELEVATED_PERMISSIONS_HEADER]) : {};\n const contextIds = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n\n const userObject = new ApiUser(userId, 'user', elevatedPermissionsFromHeader, contextIds);\n if (eagerLoadUserPermissions) {\n if (customPermissionLoader) {\n await userObject.useCustomPermissionLoader(customPermissionLoader);\n } else {\n await userObject.getUserPermissions();\n }\n }\n\n if (eagerLoadUserPermissionsLegacy) {\n await userObject.getUserPermissionsLegacy();\n }\n\n req.user = userObject;\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n\n // Added in order to support outbreak.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n\n return next();\n } catch (e) {\n res.status(401);\n return res.json({\n error: 'cannot authenticate user',\n });\n }\n};\n\nexport const middlewareWithDecode = (options: {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n returnErrorIfNoToken?: boolean\n} = {}) => async (req, res, next): Promise<void> => {\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n returnErrorIfNoToken,\n } = options;\n let decoded;\n if (req.headers.authorization) {\n try {\n decoded = await decodeBearer(req.headers.authorization);\n } catch (e) {\n if (e instanceof TokenExpiredError) {\n res.status(401);\n res.json({\n errors: ['Access token expired'],\n });\n } else if (e instanceof JsonWebTokenError) {\n res.status(400);\n res.json({\n errors: [e.message],\n });\n } else {\n res.status(500);\n res.json({\n errors: ['Server error while parsing token'],\n });\n }\n return undefined;\n }\n const userId = decoded?.user?.id;\n\n if (userId) {\n req.headers[USER_TRACING_HEADER] = userId;\n }\n\n const contextIds = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n const userObject = new ApiUser(userId, decoded?.user?.accountType, undefined, contextIds);\n\n if (eagerLoadUserPermissions) {\n await userObject.getUserPermissions();\n }\n\n if (eagerLoadUserPermissionsLegacy) {\n await userObject.getUserPermissionsLegacy();\n }\n\n req.user = userObject;\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n\n // Added in order to support outbreak.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n } else if (returnErrorIfNoToken) {\n res.status(401);\n return res.json({\n errors: ['No token provided'],\n });\n }\n return next();\n};\n\nexport const appMiddleware = (options: {\n appId: string,\n clientSecret: string\n}) => async (req, res, next): Promise<void> => {\n const {\n appId,\n clientSecret,\n } = options;\n let decoded;\n\n if (!req.headers.authorization) {\n res.status(401);\n return res.json({\n errors: ['No token provided'],\n });\n }\n\n try {\n decoded = await decodeAppBearer(req.headers.authorization, appId);\n if (!decoded) {\n throw new AppDoesNotExist();\n }\n } catch (e) {\n if (e instanceof TokenExpiredError) {\n return res.status(401).json({\n errors: ['Access token expired'],\n });\n }\n if ([JsonWebTokenError, AppDoesNotExist].some((Err) => e instanceof Err)) {\n return res.status(400).json({\n errors: [e.message],\n });\n }\n return res.status(500).json({\n errors: ['Server error while parsing token'],\n });\n }\n const userId = decoded?.userId;\n if (userId) {\n req.headers[USER_OBJECT] = userId;\n }\n\n const userObject = new ApiUser(userId);\n\n if (appId) {\n req.headers['x-autofleet-apps-secret'] = clientSecret;\n // Won't work until we find a better solution for identity ms\n await userObject.getUserAppPermissions(appId, clientSecret);\n }\n\n req.user = userObject;\n const currentTraceContext = getCurrentContext().nonHeaderContext;\n currentTraceContext?.set(USER_OBJECT, userObject);\n currentTraceContext?.set(ACCESS_TOKEN, getAuthFromBearer(req.headers.authorization));\n\n // Added in order to support outbreak.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n\n return next();\n};\n\nexport const eagerLoadPermissionsMiddleware = async (req, res, next) => {\n await req.user.getUserPermissions();\n return next();\n};\n\nexport const getDecodedBearer = (req) => {\n if (req.headers.authorization) {\n return decodeBearer(req.headers.authorization);\n }\n\n return null;\n};\n\nexport const createOrSetRabbitTrace = async (trace: ReturnType<typeof newTrace> | undefined, userId: string | undefined) => {\n const userObject = new ApiUser(userId);\n\n await userObject.getUserPermissions();\n // eslint-disable-next-line no-param-reassign\n trace ??= newTrace(traceTypes.RABBIT);\n trace.nonHeaderContext.set(USER_OBJECT, userObject);\n};\n\nexport default ApiUser;\n","import { getCurrentContext } from '@autofleet/outbreak';\nimport ApiUser from './user/ApiUser';\nimport { USER_OBJECT } from './user';\n\nexport const getUser = () : ApiUser | undefined => getCurrentContext().nonHeaderContext?.get(USER_OBJECT) as ApiUser | undefined;\n\nexport const isUserExist = () => getUser()?.id;\n\nexport const checkFleetPermission = (fleetId: string) => !isUserExist() || Object.keys(getUser()!.permissions.fleets).includes(fleetId);\n\nexport const checkBusinessModelPermission = (businessModelId: string) => !isUserExist() || Object.keys(getUser()!.permissions.businessModels).includes(businessModelId);\n\nexport const checkDemandSourcePermission = (demandSourceId: string) => !isUserExist() || Object.keys(getUser()!.permissions.demandSources).includes(demandSourceId);\n","import type ApiUser from './user';\n\n// eslint-disable-next-line import/prefer-default-export\nexport class UnauthorizedAccessError extends Error {\n constructor(public user: ApiUser | null = null, message = 'UnauthorizedAccessError') {\n super(message);\n this.name = 'UnauthorizedAccessError';\n }\n}\n","import * as jwt from 'jsonwebtoken';\n\nexport const AUTHORIZATION_METHODS = {\n NONE: 'NONE',\n BASIC: 'BASIC',\n JWT: 'JWT',\n};\n\nconst AUTHORIZATION_ACTIONS = {\n [AUTHORIZATION_METHODS.NONE]: () => undefined,\n [AUTHORIZATION_METHODS.BASIC]: (authorizationSettings: any) => {\n const { username, password } = authorizationSettings;\n const encodedCredentials = Buffer.from(`${username}:${password}`).toString('base64');\n return `Basic ${encodedCredentials}`;\n },\n [AUTHORIZATION_METHODS.JWT]: (authorizationSettings: any) => {\n const { secret } = authorizationSettings;\n if (secret) {\n return `Bearer ${jwt.sign({}, secret, { expiresIn: 10 })}`;\n }\n return undefined;\n },\n};\n\nexport const getAuthorizationHeader = (authorizationSettings: { method: string } | undefined): string | undefined => {\n const authorizationMethod = authorizationSettings?.method;\n\n if (!authorizationMethod || !AUTHORIZATION_ACTIONS[authorizationMethod]) {\n return undefined;\n }\n\n return AUTHORIZATION_ACTIONS[authorizationMethod](authorizationSettings);\n};\n","import type { LoggerInstanceManager } from '@autofleet/logger';\nimport * as outbreak from '@autofleet/outbreak';\nimport User, {\n middleware,\n eagerLoadPermissionsMiddleware,\n middlewareWithDecode,\n getDecodedBearer,\n appMiddleware,\n createOrSetRabbitTrace,\n} from './user';\nimport { type UserPayload, CONTEXTS_IDS_HEADER } from './user/ApiUser';\nimport {\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n} from './check-permission';\nimport { UnauthorizedAccessError } from './errors';\nimport { getRefreshTokenSecret, getTokenSecret } from './secret-getter';\nimport { AUTHORIZATION_METHODS, getAuthorizationHeader } from './authorization';\n\nconst getCurrentPayload = outbreak.getCurrentContext;\n\ntype OutbreakOptions = Parameters<typeof outbreak.default>[0];\ntype LoggerWithContextMiddleware = Partial<Pick<LoggerInstanceManager, 'addContextMiddleware'>>;\nconst enableTracing = ({ outbreakOptions = {}, logger }: { outbreakOptions?: OutbreakOptions, logger?: LoggerWithContextMiddleware } = {}): void => {\n outbreak.default({\n headersPrefix: 'x-af',\n contextMiddlewareGetter: logger?.addContextMiddleware,\n ...outbreakOptions,\n });\n};\n\nconst { traceTypes, newTrace } = outbreak;\n\nexport {\n traceTypes,\n newTrace,\n enableTracing,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n getRefreshTokenSecret,\n getTokenSecret,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n type UserPayload,\n CONTEXTS_IDS_HEADER,\n};\n\nexport default {\n traceTypes,\n newTrace,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n CONTEXTS_IDS_HEADER,\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/secret-getter.ts","../src/utils.ts","../src/services.ts","../src/user/ApiUser.ts","../src/app-auth.ts","../src/exceptions/appDoesNotExist.ts","../src/user/const.ts","../src/user/common.ts","../src/user/index.ts","../src/user/fastify.ts","../src/check-permission.ts","../src/errors.ts","../src/authorization.ts","../src/index.ts"],"names":["DEPRECATED_JWT_SECRET","JWT_NEW_SECRET","DEPRECATED_REFRESH_JWT_SECRET","REFRESH_JWT_SECRET","DEPRECATION_UNIX_TIMESTAMP","getRelevantSecret","token","deprecatedSecret","newSecret","deprecationTime","moment","unixTime","iat","jwt","getRefreshTokenSecret","getTokenSecret","getAuthFromBearer","bearer","decodeBearer","appSecret","M","EMPTY_UUID","FULL_UUID","VALID_CHARS_REGEX","UUID_VERSION_REGEX","UUID_REGEX","validateUUID","uuid","CACHE_LIFETIME_IN_SEC","apiGwUrl","IdentityNetwork","Network","AutofleetApiNetwork","ELEVATED_PERMISSIONS_HEADER","CONTEXTS_IDS_HEADER","userCache","NodeCache","mergePermissions","target","sources","permissions","source","entityType","entityId","perms","ApiUser","id","accountType","elevatedPermissions","contextIds","cacheKey","objectHash","data","customPermissionLoader","cachedResult","key","addedPermissions","elevationId","entityIds","currentUserTrace","getCurrentContext","currentElevation","newElevation","appId","clientSecret","currentAppPermission","decodeAppBearer","decoded","AppDoesNotExist","IDENTITY_MS","ACCESS_TOKEN","USER_OBJECT","USER_TRACING_HEADER","ORIGIN_HEADER","USER_PERMISSIONS_HEADER","LOWER_CASE_ORIGIN_HEADER","AUTOFLEET_APPS_SECRET_HEADER","authFromUserIdHeader","options","headers","originHeader","eagerLoadUserPermissions","eagerLoadUserPermissionsLegacy","userId","elevatedPermissionsFromHeader","userObject","middleware","req","res","next","middlewareWithDecode","returnErrorIfNoToken","e","appMiddleware","Err","currentTraceContext","eagerLoadPermissionsMiddleware","getDecodedBearer","createOrSetRabbitTrace","trace","newTrace","traceTypes","user_default","authFromUserIdHeaderPlugin","fastify","done","request","reply","user","getUser","isUserExist","checkUserPermissions","checkFleetPermission","fleetId","checkBusinessModelPermission","businessModelId","checkDemandSourcePermission","demandSourceId","UnauthorizedAccessError","message","AUTHORIZATION_METHODS","AUTHORIZATION_ACTIONS","authorizationSettings","username","password","secret","ae","getAuthorizationHeader","authorizationMethod","getCurrentPayload","enableTracing","outbreakOptions","logger","outbreak","index_default"],"mappings":"wTAGA,IAAM,CACJ,qBAAA,CAAAA,EAAuB,CAAA,cAAA,CAAAC,GACvB,6BAAAC,CAAAA,EAAAA,CAA+B,kBAAAC,CAAAA,EAAAA,CAC/B,0BAAAC,CAAAA,EACF,EAAI,OAAQ,CAAA,GAAA,CAENC,CAAoB,CAAA,CA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M,CAAE,UAAA,CAAA9B,GAAY,QAAAD,CAAAA,EAAS,EAAIiC,EA8BjC,IAAOC,EAAQ,CAAA,CACb,UAAAjC,CAAAA,EAAAA,CACA,SAAAD,EACA,CAAA,IAAA,CAAAE,EACA,CAAA,UAAA,CAAAhB,CACA,CAAA,oBAAA,CAAAI,EACA,8BAAAM,CAAAA,CAAAA,CACA,iBAAAiC,CAAAA,EAAAA,CACA,gBAAAhC,CAAAA,EAAAA,CACA,qBAAAe,EACA,CAAA,4BAAA,CAAAE,GACA,2BAAAE,CAAAA,EAAAA,CACA,YAAAN,CACA,CAAA,OAAA,CAAAD,CACA,CAAA,uBAAA,CAAAS,CACA,CAAA,aAAA,CAAAzB,EACA,sBAAAK,CAAAA,EAAAA,CACA,QAAAmC,CAAAA,CAAAA,CACA,qBAAAb,CAAAA,CAAAA,CACA,uBAAAO,EACA,CAAA,mBAAA,CAAA7F,CACA,CAAA,0BAAA,CAAAqE,CACF","file":"index.js","sourcesContent":["import jwt from 'jsonwebtoken';\nimport moment from 'moment';\n\nconst {\n DEPRECATED_JWT_SECRET, JWT_NEW_SECRET,\n DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET,\n DEPRECATION_UNIX_TIMESTAMP,\n} = process.env;\n\nconst getRelevantSecret = (token: string | undefined, deprecatedSecret: string, newSecret: string): string => {\n const deprecationTime = moment(parseInt(DEPRECATION_UNIX_TIMESTAMP, 10) * 1000);\n try {\n let unixTime: moment.Moment;\n if (token) {\n const { iat } = jwt.decode(token) as jwt.JwtPayload;\n unixTime = moment(iat * 1000);\n } else {\n unixTime = moment();\n }\n return unixTime.isBefore(deprecationTime) ? deprecatedSecret : newSecret;\n } catch (e) {\n return newSecret;\n }\n};\n\nexport const getRefreshTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_REFRESH_JWT_SECRET, REFRESH_JWT_SECRET);\nexport const getTokenSecret = (token?: string): string => getRelevantSecret(token, DEPRECATED_JWT_SECRET, JWT_NEW_SECRET);\n","import type { UUID } from 'node:crypto';\nimport * as jwt from 'jsonwebtoken';\nimport { getTokenSecret } from './secret-getter';\n\nconst CONTEXT_PROPS = ['fleetId', 'businessModelId', 'demandSourceId'];\nconst CONTEXT_MAP_PROPS = {\n fleet: 'fleets',\n business: 'businessModels',\n demand: 'demandSources',\n};\n\nexport const getAuthFromBearer = (bearer: string): string => bearer.replace('Bearer ', '');\n\nexport const decodeBearer = (bearer: string, appSecret?: string): any => {\n const token = getAuthFromBearer(bearer);\n const decoded = jwt.verify(token, appSecret || getTokenSecret(token));\n return decoded;\n};\n\nexport const parsePermissions = (contextId, decodedToken): any => {\n if (!decodedToken) { return []; }\n const { contexts } = decodedToken;\n const activeContext = contexts.find((context) => context.id === contextId);\n\n const permissionsValue = `${activeContext.permissions?.map((cp) => `${cp},`)}`;\n\n return {\n key: activeContext.entityId,\n value: permissionsValue,\n };\n};\n\nexport const getEntitiesFromContext = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n\n const attributes = {};\n contexts.forEach((context) => {\n const prop = CONTEXT_MAP_PROPS[context.subSystem || 'business'];\n\n const permissions = parsePermissions(context.id, decodedToken);\n attributes[prop] ||= {};\n attributes[prop][permissions.key] = permissions.value;\n });\n\n return attributes;\n};\n\nexport const getContextAttributes = (contextId: string, decodedToken: any): any => {\n if (!decodedToken) { return []; }\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n const attributes = {};\n contexts.forEach((context) => {\n CONTEXT_PROPS.forEach((prop) => {\n if (context[prop]) {\n const contextPropWrapped = [context[prop]];\n attributes[prop] ||= [];\n attributes[prop] = attributes[prop].concat(contextPropWrapped);\n }\n });\n });\n return attributes;\n};\n\nconst EMPTY_UUID = '00000000-0000-0000-0000-000000000000';\nconst FULL_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff';\nconst VALID_CHARS_REGEX = '[0-9a-f]';\nconst UUID_VERSION_REGEX = '[1-8]';\nconst UUID_REGEX = new RegExp(\n `^(?:${VALID_CHARS_REGEX}{8}-${VALID_CHARS_REGEX}{4}-${UUID_VERSION_REGEX}${VALID_CHARS_REGEX}{3}-[89ab]${VALID_CHARS_REGEX}{3}-${VALID_CHARS_REGEX}{12}|${EMPTY_UUID}|${FULL_UUID})$`,\n 'i',\n);\nexport function validateUUID(uuid: unknown): uuid is UUID {\n return typeof uuid === 'string' && UUID_REGEX.test(uuid);\n}\n","import Network from '@autofleet/network';\n\nconst CACHE_LIFETIME_IN_SEC = 10;\nconst apiGwUrl = process.env.API_GATEWAY_URL || 'https://api.autofleet.io';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const IdentityNetwork = new Network({\n serviceName: 'IDENTITY_MS',\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n\nexport const AutofleetApiNetwork = new Network({\n baseURL: apiGwUrl,\n serviceUrl: apiGwUrl,\n retries: 3,\n retryCondition: () => true,\n cache: process.env.NODE_ENV !== 'test' ? {\n maxAge: CACHE_LIFETIME_IN_SEC * 1000,\n } : undefined,\n});\n","import NodeCache from 'node-cache';\nimport objectHash from 'object-hash';\nimport { getCurrentContext } from '@autofleet/outbreak';\nimport { validateUUID } from '../utils';\nimport { AutofleetApiNetwork, IdentityNetwork } from '../services';\n\nexport type AccountType = 'client' | 'user' | 'service' | 'driver'\ninterface EntityPermissions {\n [key: string]: string[];\n}\n\nexport const ELEVATED_PERMISSIONS_HEADER = 'x-af-elevated-permissions';\nexport const CONTEXTS_IDS_HEADER = 'x-af-context-ids';\n\nexport interface UserPayload {\n businessModels: EntityPermissions;\n fleets: EntityPermissions;\n demandSources: EntityPermissions;\n businessAccounts?: EntityPermissions;\n accountType?: AccountType;\n contexts?: EntityPermissions;\n createdAt?: string;\n}\n\nexport interface PartialUserPayload {\n businessModels?: EntityPermissions;\n fleets?: EntityPermissions;\n demandSources?: EntityPermissions;\n vehicles?: EntityPermissions;\n drivers?: EntityPermissions;\n businessAccounts?: EntityPermissions;\n}\n\nconst userCache = new NodeCache({ stdTTL: 10 });\n\nconst mergePermissions = (target: UserPayload, sources: Iterable<PartialUserPayload>): UserPayload => {\n const permissions: UserPayload = {\n ...target,\n fleets: { ...target?.fleets },\n businessModels: { ...target?.businessModels },\n demandSources: { ...target?.demandSources },\n // Clone other nested objects as needed\n };\n\n // eslint-disable-next-line no-restricted-syntax\n for (const source of sources) {\n Object.keys(source).forEach((entityType) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType] ??= {};\n Object.entries(source[entityType]!).forEach(([entityId, perms]) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType][entityId] = (permissions[entityType][entityId] || []).concat(perms);\n });\n });\n }\n\n return permissions;\n};\n\nexport default class ApiUser {\n private privatePermissions: UserPayload | undefined;\n\n private readonly privateElevatedPermissionsHash = new Map<symbol, PartialUserPayload | undefined>();\n\n private privatePermissionsLegacy: any;\n\n private readonly appPermission: {[key: string]: any; } = {};\n\n public readonly emptyUser: boolean;\n\n constructor(public id? : string, public accountType?: AccountType, elevatedPermissions?: PartialUserPayload, public contextIds?: string[]) {\n this.emptyUser = !!id;\n if (elevatedPermissions) {\n this.privateElevatedPermissionsHash.set(Symbol('initial'), elevatedPermissions);\n }\n }\n\n public async getUserPermissions(): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n const cacheKey = objectHash({\n id: this.id,\n contextIds: this.contextIds,\n });\n\n let data = userCache.get<UserPayload>(cacheKey);\n\n if (!data) {\n ({ data } = await IdentityNetwork.get<UserPayload>(`/api/v1/users/${this.id}/authorization-payload`, { params: { contextIds: this.contextIds } }));\n userCache.set(cacheKey, data);\n }\n\n this.accountType = data.accountType;\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n public async useCustomPermissionLoader(customPermissionLoader: (userId: string) => UserPayload | PromiseLike<UserPayload>): Promise<UserPayload> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissions) {\n return this.privatePermissions;\n }\n\n const cacheKey = this.id;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.privatePermissions = cachedResult;\n return cachedResult;\n }\n\n const data = await customPermissionLoader(this.id);\n userCache.set(cacheKey, data);\n\n this.privatePermissions = data;\n return this.privatePermissions;\n }\n\n public get businessModels(): string[] | undefined {\n return this.getUserProperty('businessModels');\n }\n\n public get fleets(): string[] | undefined {\n return this.getUserProperty('fleets');\n }\n\n public get demandSources(): string[] | undefined {\n return this.getUserProperty('demandSources');\n }\n\n private getUserProperty(key: keyof UserPayload): string[] | undefined {\n if (!this.privatePermissions) {\n throw new Error(`Cannot get ${key} without calling (async) getUserPermissions before`);\n }\n return Object.keys(this.privatePermissions[key] || {});\n }\n\n public get elevatedPermissions(): UserPayload {\n return mergePermissions(undefined, this.privateElevatedPermissionsHash.values());\n }\n\n public get permissions(): UserPayload | undefined {\n if (!this.privatePermissions) {\n throw new Error('Cannot get permissions without calling (async) getUserPermissions before');\n }\n\n return mergePermissions(this.privatePermissions, this.privateElevatedPermissionsHash.values());\n }\n\n public elevatePermissions(addedPermissions: PartialUserPayload): () => void {\n // @itayankri is concerned about memory consumption, so create a symbol with no description, to avoid assigning memory for the description string\n // eslint-disable-next-line symbol-description\n const elevationId = Symbol();\n\n // Validate that the added permissions are valid UUIDs\n Object.values(addedPermissions).forEach((entityIds) => {\n Object.keys(entityIds).forEach((entityId) => {\n if (!validateUUID(entityId)) {\n throw new Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${entityId}`);\n }\n });\n });\n\n const currentUserTrace = getCurrentContext();\n if (!currentUserTrace) {\n throw new Error('Cannot find current user cross services trace');\n }\n\n const currentElevation = JSON.parse(currentUserTrace.context[ELEVATED_PERMISSIONS_HEADER] || '{}');\n const newElevation = Object.assign(currentElevation, addedPermissions);\n this.privateElevatedPermissionsHash.set(elevationId, newElevation);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n return () => {\n this.privateElevatedPermissionsHash.delete(elevationId);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n };\n }\n\n public async getUserPermissionsLegacy() {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissionsLegacy) {\n return this.privatePermissionsLegacy;\n }\n const { data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload-legacy`);\n\n this.privatePermissionsLegacy = data;\n return this.privatePermissionsLegacy;\n }\n\n public get permissionsLegacy(): any {\n if (!this.privatePermissionsLegacy) {\n throw new Error('Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before');\n }\n return this.privatePermissionsLegacy;\n }\n\n public async getUserAppPermissions(appId, clientSecret) {\n if (!this.id || !appId || !clientSecret) {\n return undefined;\n }\n const currentAppPermission = this.appPermission[appId];\n\n if (currentAppPermission) {\n return currentAppPermission;\n }\n\n const cacheKey = `${this.id}:${appId}`;\n\n const cachedResult = userCache.get<UserPayload>(cacheKey);\n if (cachedResult) {\n this.appPermission[appId] = cachedResult;\n return cachedResult;\n }\n\n const { data } = await AutofleetApiNetwork.post<UserPayload>(`/api/v1/apps/${appId}/get-user-payload`, {\n userId: this.id,\n }, {\n headers: {\n 'x-autofleet-apps-secret': clientSecret,\n },\n });\n\n userCache.set(cacheKey, data);\n this.appPermission[appId] = data;\n return this.appPermission[appId];\n }\n}\n","import { AutofleetApiNetwork } from './services';\n\nexport const decodeAppBearer = async (bearer: string, appId: string): Promise<any> => {\n const { data: decoded } = await AutofleetApiNetwork.post('/api/v1/auth', { bearer, appId });\n return decoded;\n};\n\nexport const getClientSecret = async (appId: string): Promise<any> => {\n const { data: secret } = await AutofleetApiNetwork.get(`/api/v1/auth/client-secret/${appId}`);\n return secret;\n};\n","export default class AppDoesNotExist extends Error {\n name = 'AppDoesNotExist';\n\n message = 'app does not exist';\n}\n","export const IDENTITY_MS = 'identity-ms';\nexport const ACCESS_TOKEN = 'accessToken';\nexport const USER_OBJECT = 'userObject';\nexport const USER_TRACING_HEADER = 'x-af-user-id';\nexport const ORIGIN_HEADER = 'X-IAF-ORIGIN-SERVICE';\nexport const USER_PERMISSIONS_HEADER = 'x-af-user-permissions';\nexport const LOWER_CASE_ORIGIN_HEADER = ORIGIN_HEADER.toLowerCase();\nexport const AUTOFLEET_APPS_SECRET_HEADER = 'x-autofleet-apps-secret';\n","import type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentContext } from '@autofleet/outbreak';\nimport ApiUser, { CONTEXTS_IDS_HEADER, ELEVATED_PERMISSIONS_HEADER, type UserPayload } from './ApiUser';\nimport {\n IDENTITY_MS,\n USER_OBJECT,\n USER_TRACING_HEADER,\n ORIGIN_HEADER,\n LOWER_CASE_ORIGIN_HEADER,\n} from './const';\n\nexport type CustomPermissionLoader = (userId: string) => Promise<UserPayload>;\nexport interface AuthFromUserIdHeaderOptions {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n customPermissionLoader?: CustomPermissionLoader;\n}\n\nexport const authFromUserIdHeader = async (options: AuthFromUserIdHeaderOptions, headers: IncomingHttpHeaders): Promise<ApiUser | undefined> => {\n const originHeader = headers[ORIGIN_HEADER] || headers[LOWER_CASE_ORIGIN_HEADER] || '';\n if (!Array.isArray(originHeader) && originHeader.toLowerCase() === IDENTITY_MS) {\n return undefined;\n }\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n customPermissionLoader,\n } = options;\n const userId = headers[USER_TRACING_HEADER] as string;\n if (!userId || Array.isArray(userId)) {\n return undefined;\n }\n\n const elevatedPermissionsFromHeader = headers[ELEVATED_PERMISSIONS_HEADER]?.length > 0 ? JSON.parse(headers[ELEVATED_PERMISSIONS_HEADER] as string) : {};\n const contextIds = (headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n\n const userObject = new ApiUser(userId, 'user', elevatedPermissionsFromHeader, contextIds);\n if (eagerLoadUserPermissions) {\n if (customPermissionLoader) {\n await userObject.useCustomPermissionLoader(customPermissionLoader);\n } else {\n await userObject.getUserPermissions();\n }\n }\n\n if (eagerLoadUserPermissionsLegacy) {\n await userObject.getUserPermissionsLegacy();\n }\n\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n return userObject;\n};\n","import type { Handler, Request } from 'express';\nimport { getCurrentContext, newTrace, traceTypes } from '@autofleet/outbreak';\nimport jwt from 'jsonwebtoken';\nimport ApiUser, { CONTEXTS_IDS_HEADER } from './ApiUser';\nimport { decodeAppBearer } from '../app-auth';\nimport AppDoesNotExist from '../exceptions/appDoesNotExist';\nimport { decodeBearer, getAuthFromBearer } from '../utils';\nimport {\n ACCESS_TOKEN,\n USER_OBJECT,\n USER_TRACING_HEADER,\n USER_PERMISSIONS_HEADER,\n AUTOFLEET_APPS_SECRET_HEADER,\n} from './const';\nimport { authFromUserIdHeader, AuthFromUserIdHeaderOptions } from './common';\n\ndeclare module 'express-serve-static-core' {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n interface Request {\n user: ApiUser;\n }\n}\n\nexport const middleware = (options: AuthFromUserIdHeaderOptions = {}): Handler => async (req, res, next): Promise<any> => {\n try {\n const userObject = await authFromUserIdHeader(options, req.headers);\n if (userObject) {\n req.user = userObject;\n // Added in order to support outbreak.\n // @ts-expect-error we are setting an object onto the request headers.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n }\n\n next();\n } catch (e) {\n res.status(401).json({ error: 'cannot authenticate user' });\n }\n};\n\nexport const middlewareWithDecode = (options: {\n eagerLoadUserPermissions?: boolean;\n eagerLoadUserPermissionsLegacy?: boolean;\n returnErrorIfNoToken?: boolean\n} = {}): Handler => async (req, res, next): Promise<void> => {\n const {\n eagerLoadUserPermissions,\n eagerLoadUserPermissionsLegacy,\n returnErrorIfNoToken,\n } = options;\n let decoded;\n if (req.headers.authorization) {\n try {\n decoded = await decodeBearer(req.headers.authorization);\n } catch (e) {\n if (e instanceof jwt.TokenExpiredError) {\n res.status(401).json({ errors: ['Access token expired'] });\n } else if (e instanceof jwt.JsonWebTokenError) {\n res.status(400).json({ errors: [e.message] });\n } else {\n res.status(500).json({ errors: ['Server error while parsing token'] });\n }\n return;\n }\n const userId = decoded?.user?.id;\n\n if (userId) {\n req.headers[USER_TRACING_HEADER] = userId;\n }\n\n const contextIds = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',');\n const userObject = new ApiUser(userId, decoded?.user?.accountType, undefined, contextIds);\n\n if (eagerLoadUserPermissions || eagerLoadUserPermissionsLegacy) {\n await Promise.all([\n eagerLoadUserPermissions && userObject.getUserPermissions(),\n eagerLoadUserPermissionsLegacy && userObject.getUserPermissionsLegacy(),\n ]);\n }\n\n req.user = userObject;\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, userObject);\n\n // Added in order to support outbreak.\n // @ts-expect-error we are setting an object onto the request headers.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n } else if (returnErrorIfNoToken) {\n res.status(401).json({ errors: ['No token provided'] });\n return;\n }\n next();\n};\n\nexport const appMiddleware = (options: {\n appId: string,\n clientSecret: string\n}): Handler => async (req, res, next): Promise<void> => {\n const {\n appId,\n clientSecret,\n } = options;\n let decoded;\n\n if (!req.headers.authorization) {\n res.status(401).json({ errors: ['No token provided'] });\n return;\n }\n\n try {\n decoded = await decodeAppBearer(req.headers.authorization, appId);\n if (!decoded) {\n throw new AppDoesNotExist();\n }\n } catch (e) {\n if (e instanceof jwt.TokenExpiredError) {\n res.status(401).json({ errors: ['Access token expired'] });\n return;\n }\n if ([jwt.JsonWebTokenError, AppDoesNotExist].some((Err) => e instanceof Err)) {\n res.status(400).json({ errors: [e.message] });\n return;\n }\n res.status(500).json({ errors: ['Server error while parsing token'] });\n return;\n }\n const userId = decoded?.userId;\n if (userId) {\n req.headers[USER_TRACING_HEADER] = userId;\n }\n\n const userObject = new ApiUser(userId);\n\n if (appId) {\n req.headers[AUTOFLEET_APPS_SECRET_HEADER] = clientSecret;\n // Won't work until we find a better solution for identity ms\n await userObject.getUserAppPermissions(appId, clientSecret);\n }\n\n req.user = userObject;\n const currentTraceContext = getCurrentContext().nonHeaderContext;\n currentTraceContext?.set(USER_OBJECT, userObject);\n currentTraceContext?.set(ACCESS_TOKEN, getAuthFromBearer(req.headers.authorization));\n\n // Added in order to support outbreak.\n // @ts-expect-error we are setting an object onto the request headers.\n req.headers[USER_PERMISSIONS_HEADER] = userObject;\n\n next();\n};\n\nexport const eagerLoadPermissionsMiddleware: Handler = async (req, res, next) => {\n await req.user.getUserPermissions();\n next();\n};\n\nexport const getDecodedBearer = (req: Request) => {\n if (!req.headers.authorization) {\n return null;\n }\n return decodeBearer(req.headers.authorization);\n};\n\nexport const createOrSetRabbitTrace = async (trace: ReturnType<typeof newTrace> | undefined, userId: string | undefined) => {\n const userObject = new ApiUser(userId);\n\n await userObject.getUserPermissions();\n // eslint-disable-next-line no-param-reassign\n trace ??= newTrace(traceTypes.RABBIT);\n trace.nonHeaderContext.set(USER_OBJECT, userObject);\n};\n\nexport default ApiUser;\n","import type { FastifyPluginCallback } from 'fastify';\nimport type ApiUser from './ApiUser';\nimport { AuthFromUserIdHeaderOptions, authFromUserIdHeader } from './common';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n user?: ApiUser;\n }\n}\n\n// eslint-disable-next-line import/prefer-default-export\nexport const authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions> = (fastify, options, done) => {\n fastify.addHook('onRequest', async (request, reply) => {\n try {\n const user = await authFromUserIdHeader(options, request.headers);\n if (user) {\n fastify.decorateRequest('user', user);\n }\n } catch (e) {\n reply.status(401).send({ error: 'cannot authenticate user' });\n }\n });\n\n done();\n};\nauthFromUserIdHeaderPlugin[Symbol.for('skip-override')] = true; // Prevent Fastify from overriding the plugin\n","import { getCurrentContext } from '@autofleet/outbreak';\nimport { USER_OBJECT } from './user/const';\nimport ApiUser, { type UserPayload } from './user/ApiUser';\n\nexport const getUser = () : ApiUser | undefined => getCurrentContext().nonHeaderContext?.get(USER_OBJECT) as ApiUser | undefined;\n\nexport const isUserExist = () => getUser()?.id;\n\nconst checkUserPermissions = (\n entityId: string,\n entityType: Exclude<keyof UserPayload, 'accountType' | 'createdAt'>,\n) => !isUserExist() || Object.hasOwn(getUser()!.permissions[entityType], entityId);\n\nexport const checkFleetPermission = (fleetId: string) => checkUserPermissions(fleetId, 'fleets');\nexport const checkBusinessModelPermission = (businessModelId: string) => checkUserPermissions(businessModelId, 'businessModels');\nexport const checkDemandSourcePermission = (demandSourceId: string) => checkUserPermissions(demandSourceId, 'demandSources');\n","import type ApiUser from './user';\n\n// eslint-disable-next-line import/prefer-default-export\nexport class UnauthorizedAccessError extends Error {\n constructor(public user: ApiUser | null = null, message = 'UnauthorizedAccessError') {\n super(message);\n this.name = 'UnauthorizedAccessError';\n }\n}\n","import * as jwt from 'jsonwebtoken';\n\nexport const AUTHORIZATION_METHODS = {\n NONE: 'NONE',\n BASIC: 'BASIC',\n JWT: 'JWT',\n};\n\nconst AUTHORIZATION_ACTIONS = {\n [AUTHORIZATION_METHODS.NONE]: () => undefined,\n [AUTHORIZATION_METHODS.BASIC]: (authorizationSettings: any) => {\n const { username, password } = authorizationSettings;\n const encodedCredentials = Buffer.from(`${username}:${password}`).toString('base64');\n return `Basic ${encodedCredentials}`;\n },\n [AUTHORIZATION_METHODS.JWT]: (authorizationSettings: any) => {\n const { secret } = authorizationSettings;\n if (secret) {\n return `Bearer ${jwt.sign({}, secret, { expiresIn: 10 })}`;\n }\n return undefined;\n },\n};\n\nexport const getAuthorizationHeader = (authorizationSettings: { method: string } | undefined): string | undefined => {\n const authorizationMethod = authorizationSettings?.method;\n\n if (!authorizationMethod || !AUTHORIZATION_ACTIONS[authorizationMethod]) {\n return undefined;\n }\n\n return AUTHORIZATION_ACTIONS[authorizationMethod](authorizationSettings);\n};\n","import type { LoggerInstanceManager } from '@autofleet/logger';\nimport * as outbreak from '@autofleet/outbreak';\nimport User, {\n middleware,\n eagerLoadPermissionsMiddleware,\n middlewareWithDecode,\n getDecodedBearer,\n appMiddleware,\n createOrSetRabbitTrace,\n} from './user';\nimport { authFromUserIdHeaderPlugin } from './user/fastify';\nimport { type UserPayload, CONTEXTS_IDS_HEADER } from './user/ApiUser';\nimport {\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n} from './check-permission';\nimport { UnauthorizedAccessError } from './errors';\nimport { getRefreshTokenSecret, getTokenSecret } from './secret-getter';\nimport { AUTHORIZATION_METHODS, getAuthorizationHeader } from './authorization';\n\nconst getCurrentPayload = outbreak.getCurrentContext;\n\ntype OutbreakOptions = Parameters<typeof outbreak.default>[0];\ntype LoggerWithContextMiddleware = Partial<Pick<LoggerInstanceManager, 'addContextMiddleware'>>;\nconst enableTracing = ({ outbreakOptions = {}, logger }: { outbreakOptions?: OutbreakOptions, logger?: LoggerWithContextMiddleware } = {}): void => {\n outbreak.default({\n headersPrefix: 'x-af',\n contextMiddlewareGetter: logger?.addContextMiddleware,\n ...outbreakOptions,\n });\n};\n\nconst { traceTypes, newTrace } = outbreak;\n\nexport {\n traceTypes,\n newTrace,\n enableTracing,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n getRefreshTokenSecret,\n getTokenSecret,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n type UserPayload,\n CONTEXTS_IDS_HEADER,\n authFromUserIdHeaderPlugin,\n};\n\nexport default {\n traceTypes,\n newTrace,\n User,\n middleware,\n middlewareWithDecode,\n eagerLoadPermissionsMiddleware,\n getCurrentPayload,\n getDecodedBearer,\n checkFleetPermission,\n checkBusinessModelPermission,\n checkDemandSourcePermission,\n isUserExist,\n getUser,\n UnauthorizedAccessError,\n appMiddleware,\n createOrSetRabbitTrace,\n outbreak,\n AUTHORIZATION_METHODS,\n getAuthorizationHeader,\n CONTEXTS_IDS_HEADER,\n authFromUserIdHeaderPlugin,\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autofleet/zehut",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"description": "manage user's identity",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "./lib/index.
|
|
7
|
-
"module": "./lib/index.js",
|
|
6
|
+
"main": "./lib/index.js",
|
|
8
7
|
"types": "./lib/index.d.ts",
|
|
9
8
|
"exports": {
|
|
10
9
|
".": {
|
|
@@ -31,7 +30,7 @@
|
|
|
31
30
|
},
|
|
32
31
|
"repository": {
|
|
33
32
|
"type": "git",
|
|
34
|
-
"url": "
|
|
33
|
+
"url": "https://github.com/Autofleet/zehut.git"
|
|
35
34
|
},
|
|
36
35
|
"author": "",
|
|
37
36
|
"license": "ISC",
|
|
@@ -54,17 +53,18 @@
|
|
|
54
53
|
"@types/node": "^18.19.75",
|
|
55
54
|
"@typescript-eslint/eslint-plugin": "^6.5.0",
|
|
56
55
|
"@typescript-eslint/parser": "^6.5.0",
|
|
57
|
-
"@vitest/coverage-v8": "^3.0.
|
|
56
|
+
"@vitest/coverage-v8": "^3.0.6",
|
|
58
57
|
"axios": "^0.29.0",
|
|
59
58
|
"eslint": "^8.48.0",
|
|
60
59
|
"eslint-config-airbnb-typescript": "^17.1.0",
|
|
61
60
|
"eslint-plugin-import": "^2.28.1",
|
|
62
61
|
"express": "^4.21.2",
|
|
62
|
+
"fastify": "^5.3.2",
|
|
63
63
|
"nock": "^14.0.0",
|
|
64
64
|
"supertest": "^7.0.0",
|
|
65
65
|
"tsup": "^8.3.6",
|
|
66
|
-
"typescript": "^
|
|
67
|
-
"vitest": "^3.0.
|
|
66
|
+
"typescript": "^5.8.3",
|
|
67
|
+
"vitest": "^3.0.6"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"@autofleet/shtinker": "^1.2.0"
|
|
@@ -74,9 +74,6 @@
|
|
|
74
74
|
"optional": true
|
|
75
75
|
}
|
|
76
76
|
},
|
|
77
|
-
"optionalDependencies": {
|
|
78
|
-
"@rollup/rollup-linux-x64-gnu": "*"
|
|
79
|
-
},
|
|
80
77
|
"files": [
|
|
81
78
|
"lib/**/*"
|
|
82
79
|
]
|