@autofleet/zehut 4.3.5 → 4.3.6

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/lib/index.d.ts CHANGED
@@ -6,9 +6,7 @@ import { FastifyPluginCallback } from "fastify";
6
6
 
7
7
  //#region src/user/ApiUser.d.ts
8
8
  type AccountType = "client" | "user" | "service" | "driver";
9
- interface EntityPermissions {
10
- [key: string]: string[];
11
- }
9
+ type EntityPermissions = Record<string, string[]>;
12
10
  declare const CONTEXTS_IDS_HEADER = "x-af-context-ids";
13
11
  interface UserPayload {
14
12
  businessModels: EntityPermissions;
@@ -137,12 +135,12 @@ declare const PERMISSION_ERROR_TYPES: {
137
135
  type PermissionErrorType = typeof PERMISSION_ERROR_TYPES[keyof typeof PERMISSION_ERROR_TYPES];
138
136
  //#endregion
139
137
  //#region src/permissions/SDK/types.d.ts
140
- type Logger = {
138
+ interface Logger {
141
139
  debug: (message: string, meta?: unknown) => void;
142
140
  info: (message: string, meta?: unknown) => void;
143
141
  warn: (message: string, meta?: unknown) => void;
144
142
  error: (message: string, meta?: unknown) => void;
145
- };
143
+ }
146
144
  /**
147
145
  * The operator to use when evaluating permissions
148
146
  * - AND: All required permissions must be present
@@ -156,12 +154,12 @@ type PermissionsEvaluationOperator = typeof PERMISSIONS_EVALUATION_OPERATORS[key
156
154
  * - enforce: Optional - If true, the permissions evaluation will throw an error if the user does not have the required permissions (default: false)
157
155
  * - permissionsEvaluationOperator: Optional - If set, the permissions evaluation will use this operator to evaluate the permissions (default: AND)
158
156
  */
159
- type EvaluatePermissionsOpts = {
157
+ interface EvaluatePermissionsOpts {
160
158
  requireAll?: boolean;
161
159
  timeout?: number;
162
160
  enforce?: boolean;
163
161
  permissionsEvaluationOperator?: PermissionsEvaluationOperator;
164
- };
162
+ }
165
163
  /**
166
164
  * Parameters for evaluating permissions for a user across multiple contexts
167
165
  * - requiredPermissions: The required permissions to check against the user
@@ -170,13 +168,13 @@ type EvaluatePermissionsOpts = {
170
168
  * - options: Options for evaluating permissions {@link EvaluatePermissionsOpts}
171
169
  * - userId: The user id, if not provided, we will get the user from the current context
172
170
  */
173
- type EvaluatePermissionsParams = {
171
+ interface EvaluatePermissionsParams {
174
172
  requiredPermissions: string[];
175
173
  contextIds: string[];
176
174
  logger?: Logger;
177
175
  options: EvaluatePermissionsOpts;
178
176
  userId?: string;
179
- };
177
+ }
180
178
  /**
181
179
  * Parameters for resolving permissions for a user across multiple contexts
182
180
  * - user: The user for whom permissions are being resolved
@@ -190,10 +188,10 @@ type EvaluatePermissionsParams = {
190
188
  * - permissions: The full list of permissions the user has in the context
191
189
  * - hasRequiredPermissions: Whether the user has the required permissions in the context
192
190
  */
193
- type PermissionsEvaluation = {
191
+ interface PermissionsEvaluation {
194
192
  permissions: string[];
195
193
  hasRequiredPermissions: boolean;
196
- };
194
+ }
197
195
  /**
198
196
  * A mapping of context IDs to their corresponding permissions evaluation results
199
197
  */
@@ -208,7 +206,7 @@ type PermissionsEvaluationByContextId = Record<string, PermissionsEvaluation>;
208
206
  * - error: Optional error type if the evaluation failed
209
207
  * - message: Optional error message if the evaluation failed
210
208
  */
211
- type PermissionCheckResult = {
209
+ interface PermissionCheckResult {
212
210
  isAuthorized: boolean;
213
211
  userId?: string;
214
212
  resolvedPermissions: PermissionsEvaluationByContextId;
@@ -216,7 +214,7 @@ type PermissionCheckResult = {
216
214
  contextIds: string[];
217
215
  error?: PermissionErrorType;
218
216
  message?: string;
219
- };
217
+ }
220
218
  /**
221
219
  * A mapping of context IDs to the list of the effective permissions the user has in that context
222
220
  */
package/lib/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__export as e}from"./chunk-Cl8Af3a2.js";import*as t from"@autofleet/outbreak";import{getCurrentContext as n,newTrace as r,traceTypes as i}from"@autofleet/outbreak";import a from"jsonwebtoken";import o from"node-cache";import s from"object-hash";import c from"moment";import l from"@autofleet/network";const{DEPRECATED_JWT_SECRET:u,JWT_NEW_SECRET:d,DEPRECATED_REFRESH_JWT_SECRET:f,REFRESH_JWT_SECRET:p,DEPRECATION_UNIX_TIMESTAMP:m}=process.env,h=(e,t,n)=>{let r=c(parseInt(m||``,10)*1e3);try{let i;if(e){let{iat:t}=a.decode(e);i=c(t*1e3)}else i=c();return i.isBefore(r)?t:n}catch(e){return n}},ee=e=>h(e,f,p),g=e=>h(e,u,d),_=e=>e.replace(`Bearer `,``),v=(e,t)=>{let n=_(e);return a.verify(n,t||g(n))},y=`[0-9a-f]`,te=RegExp(`^(?:${y}{8}-${y}{4}-[1-8]${y}{3}-[89ab]${y}{3}-${y}{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$`,`i`);function ne(e){return typeof e==`string`&&te.test(e)}const b=process.env.API_GATEWAY_URL||`https://api.autofleet.io`,x=new l({serviceName:`IDENTITY_MS`,retries:3,retryCondition:()=>!0,cache:process.env.NODE_ENV===`test`?void 0:{maxAge:10*1e3}}),S=new l({baseURL:b,serviceUrl:b,retries:3,retryCondition:()=>!0,cache:process.env.NODE_ENV===`test`?void 0:{maxAge:10*1e3}}),C=`x-af-elevated-permissions`,w=`x-af-context-ids`,T=new o({stdTTL:10}),E=(e,t)=>{let n={...e,fleets:{...e?.fleets},businessModels:{...e?.businessModels},demandSources:{...e?.demandSources}};for(let e of t)Object.entries(e||{}).forEach(([e,t])=>{n[e]??={},Object.entries(t).forEach(([t,r])=>{n[e][t]=(n[e][t]||[]).concat(r)})});return n};typeof Symbol.dispose!=`symbol`&&Object.defineProperty(Symbol,`dispose`,{__proto__:null,configurable:!1,enumerable:!1,value:Symbol.for(`nodejs.dispose`),writable:!1}),typeof Symbol.asyncDispose!=`symbol`&&Object.defineProperty(Symbol,`asyncDispose`,{__proto__:null,configurable:!1,enumerable:!1,value:Symbol.for(`nodejs.asyncDispose`),writable:!1});var D=class{constructor(e,t,n,r){this.id=e,this.accountType=t,this.contextIds=r,this.privateElevatedPermissionsHash=new Map,this.appPermission={},this.emptyUser=!!e,n&&this.privateElevatedPermissionsHash.set(Symbol(`initial`),n)}async getUserPermissions(){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let e=s({id:this.id,contextIds:this.contextIds}),t=T.get(e);return t||({data:t}=await x.get(`/api/v1/users/${this.id}/authorization-payload`,{params:{contextIds:this.contextIds}}),T.set(e,t)),this.accountType=t.accountType,this.privatePermissions=t,this.privatePermissions}async useCustomPermissionLoader(e){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let t=this.id,n=T.get(t);if(n)return this.privatePermissions=n,n;let r=await e(this.id);return T.set(t,r),this.privatePermissions=r,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 Error(`Cannot get ${e} without calling (async) getUserPermissions before`);return Object.keys(this.privatePermissions[e]||{})}get elevatedPermissions(){return E(void 0,this.privateElevatedPermissionsHash.values())}get permissions(){if(!this.privatePermissions)throw Error(`Cannot get permissions without calling (async) getUserPermissions before`);return E(this.privatePermissions,this.privateElevatedPermissionsHash.values())}elevatePermissions(e){let t=Symbol();Object.values(e).forEach(e=>{Object.keys(e).forEach(e=>{if(!ne(e))throw Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${e}`)})});let r=n();if(!r)throw Error(`Cannot find current user cross services trace`);let i=JSON.parse(r.context?.get(C)||`{}`),a=Object.assign(i,e);this.privateElevatedPermissionsHash.set(t,a),r.context.set(C,JSON.stringify(this.elevatedPermissions));let o=()=>{this.privateElevatedPermissionsHash.delete(t),r.context.set(C,JSON.stringify(this.elevatedPermissions))};return o[Symbol.dispose]=o,o}async getUserPermissionsLegacy(){if(!this.id)return;if(this.privatePermissionsLegacy)return this.privatePermissionsLegacy;let e=s({id:this.id,contextIds:this.contextIds,legacy:!0}),t=T.get(e);return t||({data:t}=await x.get(`/api/v1/users/${this.id}/authorization-payload-legacy`,{params:{contextIds:this.contextIds}}),T.set(e,t)),this.privatePermissionsLegacy=t,this.privatePermissionsLegacy}get permissionsLegacy(){if(!this.privatePermissionsLegacy)throw Error(`Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before`);return this.privatePermissionsLegacy}async getUserAppPermissions(e,t){if(!this.id||!e||!t)return;let n=this.appPermission[e];if(n)return n;let r=`${this.id}:${e}`,i=T.get(r);if(i)return this.appPermission[e]=i,i;let{data:a}=await S.post(`/api/v1/apps/${e}/get-user-payload`,{userId:this.id},{headers:{"x-autofleet-apps-secret":t}});return T.set(r,a),this.appPermission[e]=a,this.appPermission[e]}};const re=async(e,t)=>{let{data:n}=await S.post(`/api/v1/auth`,{bearer:e,appId:t});return n};var O=class extends Error{constructor(...e){super(...e),this.name=`AppDoesNotExist`,this.message=`app does not exist`}};const k=`userObject`,A=`x-af-user-id`,j=`x-af-user-permissions`,ie=async(e,t)=>{let r=t[`X-IAF-ORIGIN-SERVICE`]||t[`x-iaf-origin-service`]||``;if(!Array.isArray(r)&&r.toLowerCase()===`identity-ms`)return;let{eagerLoadUserPermissions:i,eagerLoadUserPermissionsLegacy:a,customPermissionLoader:o}=e,s=t[A];if(!s||Array.isArray(s))return;let c=t[C],l=c?.length&&c.length>0?JSON.parse(c):{},u=(t?.[w])?.split(`,`),d=new D(s,`user`,l,u);return i&&(o?await d.useCustomPermissionLoader(o):await d.getUserPermissions()),a&&await d.getUserPermissionsLegacy(),n().nonHeaderContext?.set(k,d),d},ae=(e={})=>async(t,n,r)=>{try{let n=await ie(e,t.headers);n&&(t.user=n,t.headers[j]=n),r()}catch(e){n.status(401).json({error:`cannot authenticate user`})}},M=(e={})=>async(t,r,i)=>{let{eagerLoadUserPermissions:o,eagerLoadUserPermissionsLegacy:s,returnErrorIfNoToken:c}=e,l;if(t.headers.authorization){try{l=await v(t.headers.authorization)}catch(e){e instanceof a.TokenExpiredError?r.status(401).json({errors:[`Access token expired`]}):e instanceof a.JsonWebTokenError?r.status(400).json({errors:[e.message]}):r.status(500).json({errors:[`Server error while parsing token`]});return}let e=l?.user?.id;e&&(t.headers[A]=e);let i=(t.headers?.[w])?.split(`,`),c=new D(e,l?.user?.accountType,void 0,i);(o||s)&&await Promise.all([o&&c.getUserPermissions(),s&&c.getUserPermissionsLegacy()]),t.user=c,n().nonHeaderContext?.set(k,c),t.headers[j]=c}else if(c){r.status(401).json({errors:[`No token provided`]});return}i()},N=e=>async(t,r,i)=>{let{appId:o,clientSecret:s}=e,c;if(!t.headers.authorization){r.status(401).json({errors:[`No token provided`]});return}try{if(c=await re(t.headers.authorization,o),!c)throw new O}catch(e){if(e instanceof a.TokenExpiredError){r.status(401).json({errors:[`Access token expired`]});return}if([a.JsonWebTokenError,O].some(t=>e instanceof t)){r.status(400).json({errors:[e.message]});return}r.status(500).json({errors:[`Server error while parsing token`]});return}let l=c?.userId;l&&(t.headers[A]=l);let u=new D(l);o&&(t.headers[`x-autofleet-apps-secret`]=s,await u.getUserAppPermissions(o,s)),t.user=u;let d=n().nonHeaderContext;d?.set(k,u),d?.set(`accessToken`,_(t.headers.authorization)),t.headers[j]=u,i()},P=async(e,t,n)=>{await e.user.getUserPermissions(),n()},F=e=>e.headers.authorization?v(e.headers.authorization):null,I=async(e,t)=>{let n=new D(t);await n.getUserPermissions(),e??=r(i.RABBIT),e.nonHeaderContext.set(k,n)};var L=D;const R=(e,t,n)=>{e.decorateRequest(`user`,void 0),e.addHook(`onRequest`,async(e,n)=>{try{let n=await ie(t,e.headers);n&&(e.user=n)}catch(e){n.status(401).send({error:`cannot authenticate user`})}}),n()};Object.defineProperty(R,Symbol.for(`skip-override`),{value:!0});const z=()=>n().nonHeaderContext?.get(k),B=()=>z()?.id,V=(e,t)=>!B()||Object.hasOwn(z().permissions?.[t]??{},e),H=e=>V(e,`fleets`),U=e=>V(e,`businessModels`),W=e=>V(e,`demandSources`);var G=class extends Error{constructor(e=null,t=`UnauthorizedAccessError`){super(t),this.user=e,this.name=`UnauthorizedAccessError`}};const K={NONE:`NONE`,BASIC:`BASIC`,JWT:`JWT`},q={[K.NONE]:()=>void 0,[K.BASIC]:e=>{let{username:t,password:n}=e;return`Basic ${Buffer.from(`${t}:${n}`).toString(`base64`)}`},[K.JWT]:e=>{let{secret:t}=e;if(t)return`Bearer ${a.sign({},t,{expiresIn:10})}`}},J=e=>{let t=e?.method;if(!(!t||!q[t]))return q[t](e)},Y=new class e{constructor(e,t){this.ttl=10,t&&(this.ttl=t),this.cache=e||new o({stdTTL:this.ttl})}static getCacheKeys(e,t,n){let r=`${e}-${t}`,i=(n.map(e=>`${r}-${e}`));return{baseCacheKey:r,cacheKeys:i}}async getUserPermissions(t,n){try{let{baseCacheKey:r,cacheKeys:i}=(e.getCacheKeys(`perm`,t,n)),a=await(this.cache.mget(i)),o={};return Object.entries(a).filter(([,e])=>e).forEach(([e,t])=>{let n=e.replace(`${r}-`,``);o[n]=t}),o}catch(e){return{}}}async setUserPermissions(e,t){try{let n=t=>`perm-${e}-${t}`,r=(Object.entries(t).map(([e,t])=>({key:n(e),val:t,ttl:this.ttl})));return await this.cache.mset(r),{success:!0}}catch(e){return{success:!1}}}async getCachedDeniedPermissions(t,n){try{let{baseCacheKey:r,cacheKeys:i}=(e.getCacheKeys(`seen`,t,n)),a=await(this.cache.mget(i)),o={};return Object.entries(a).filter(([,e])=>e).forEach(([e,t])=>{let n=e.replace(`${r}-`,``);o[n]=t}),o}catch(e){return{}}}async setCachedDeniedPermissions(e,t,n){try{let r=t=>`seen-${e}-${t}`,i=(t.map(e=>({key:r(e),val:n,ttl:this.ttl})));return await this.cache.mset(i),{success:!0}}catch(e){return{success:!1}}}},X={AND:`and`,OR:`or`},Z={USER_NOT_FOUND:`USER_NOT_FOUND`,INSUFFICIENT_PERMISSIONS:`INSUFFICIENT_PERMISSIONS`,VALIDATION_ERROR:`VALIDATION_ERROR`,API_ERROR:`API_ERROR`,NO_REQUIRED_PERMISSIONS:`NO_REQUIRED_PERMISSIONS`,UNAUTHORIZED:`UNAUTHORIZED`,BAD_REQUEST:`BAD_REQUEST`,INTERNAL_ERROR:`INTERNAL_ERROR`},Q={USER_NOT_FOUND:`User not found`,INSUFFICIENT_PERMISSIONS:`User does not have sufficient permissions`,VALIDATION_ERROR:`Validation error occurred`,API_ERROR:`API error occurred`,NO_REQUIRED_PERMISSIONS:`No required permissions provided for evaluation`,UNAUTHORIZED:`User is not authorized to perform this action`,BAD_REQUEST:`Bad request, please check the input parameters`,INTERNAL_ERROR:`Internal server error occurred while checking permissions`},oe=(e,t,n)=>{let r=new Set(e),i=t.filter(e=>r.has(e));return n===X.AND?i.length===t.length:i.length>0},se=(e,t)=>{let n=Object.values(e);return t?n.every(e=>e.hasRequiredPermissions):n.some(e=>e.hasRequiredPermissions)},ce=e=>{let t=[];return e?.length||t.push(`contextIds cannot be empty`),t},le=(e,t,n,r)=>({isAuthorized:!1,error:e,resolvedPermissions:{},requiredPermissions:t,contextIds:n,...r&&{message:r}}),ue=async(e,t,n,r)=>{let i={},a=new Map;if(r?.debug(`Start caching permissions results`,{userId:e,resolvedPermissions:t,requiredPermissions:n}),Object.entries(t).forEach(([e,t])=>{if(t?.permissions){let r=new Set(t.permissions),o=n.filter(e=>r.has(e)),s=n.filter(e=>!r.has(e));if(o.length&&(i[e]=o),s.length){let t=s.sort().join(`,`);a.has(t)||a.set(t,[]),a.get(t).push(e)}}}),Object.keys(i).length>0){let t=await Y.getUserPermissions(e,Object.keys(i));Object.keys(t??{}).forEach(e=>{i[e]&&(i[e]=Array.from(new Set([...t[e]||[],...i[e]])))}),r?.debug(`Caching granted permissions`,{userId:e,permissionsToCache:i,pastCache:t});let{success:n}=await Y.setUserPermissions(e,i);n||r?.error(`Failed to cache granted permissions`,{userId:e,permissionsToCache:i})}let o=Array.from(a.entries()).map(([t,n])=>{let r=t.split(`,`);return Y.setCachedDeniedPermissions(e,n,r)});r?.debug(`Caching denied permissions`,{userId:e,deniedPermissionsGroups:Array.from(a.entries()).map(([e,t])=>({deniedPermissions:e.split(`,`),contextIds:t}))}),await Promise.all(o)},de=(e,t,n)=>{if(!e.length)return{isResolvableFromCache:!1,hasRequiredPermissions:!1};let r=new Set(e),i=t.filter(e=>r.has(e));return n===X.AND?{isResolvableFromCache:i.length>0,hasRequiredPermissions:!1}:{isResolvableFromCache:i.length===t.length,hasRequiredPermissions:!1}},fe=(e,t,n)=>{let r=[...e],i=t.filter(e=>!n[e]);return r.push(...i),r},pe=(e,t,n,r)=>{let i={};return e.forEach(e=>{let a=t[e],o=de(a,n,r);o.isResolvableFromCache&&(i[e]={permissions:[],hasRequiredPermissions:o.hasRequiredPermissions})}),i},me=(e,t,n)=>{let r={};return Object.keys(e||{}).length&&Object.entries(e).forEach(([e,i])=>{let a=oe(i,t,n);a&&(r[e]={permissions:i,hasRequiredPermissions:a})}),r},he=async(e,t,n,r)=>{let i=(await x.post(`/api/v1/permissions/resolve`,{userId:e,contextIds:t,requiredPermissions:n},{timeout:r.timeout}))?.data||{};if(!Object.keys(i||{}).length)throw Error(`Failed to resolve permissions`);if(r.permissionsEvaluationOperator===X.AND)return i;let a={};return Object.entries(i).forEach(([e,t])=>{let i=t?.permissions||[],o=oe(i,n,r.permissionsEvaluationOperator);a[e]={permissions:i,hasRequiredPermissions:o}}),a},ge=(e,t,n,r)=>{let i=ce(e);return i.length?le(Z.VALIDATION_ERROR,t,e,i.join(`, `)):n?t?.length?null:(r?.info(`No requiredPermissions provided`,{userId:n,contextIds:e}),{isAuthorized:!1,userId:n,resolvedPermissions:{},requiredPermissions:t,contextIds:e,error:Z.NO_REQUIRED_PERMISSIONS}):(r?.warn(`User not found in context, cannot check permissions`,{contextIds:e,requiredPermissions:t}),le(Z.USER_NOT_FOUND,t,e))},_e=async(e,t,n,r,i)=>{let a={...i},o=await he(e,t,n,r);return a={...i,...o},await ue(e,o,n),a},ve=async(e,t,n,r)=>{let{logger:i}=r,a=await Y.getUserPermissions(e,t),o=me(a,n,r.permissionsEvaluationOperator),s={...o},c=t.filter(e=>!o[e]),l=await Y.getCachedDeniedPermissions(e,c),u=c.filter(e=>!l[e]),d=c.filter(e=>l[e]),f=pe(d,l,n,r.permissionsEvaluationOperator);s={...s,...f};let p=fe(u,d,f);return p.length?_e(e,p,n,r,s):(i?.debug(`Final resolved permissions`,{userId:e,requiredPermissions:n,resolvedPermissions:s}),s)},ye=async({requiredPermissions:e,contextIds:t,logger:n,userId:r,options:{requireAll:i=!0,permissionsEvaluationOperator:a=X.AND,timeout:o=1e4}})=>{let s=r||z()?.id||null,c=ge(t,e,s,n);if(c)return c;let l=await ve(s,t,e,{permissionsEvaluationOperator:a,timeout:o,logger:n}),u=se(l,i);return n?.info(`Resolved permissions`,{userId:s,requiredPermissions:e,resolvedPermissions:l,isAuthorized:u,requireAll:i,permissionsEvaluationOperator:a,contextIds:t}),{isAuthorized:u,userId:s,resolvedPermissions:l,requiredPermissions:e,contextIds:t,...u?{}:{error:Z.INSUFFICIENT_PERMISSIONS}}},be=(e,t)=>{t?.debug(`Extracting context IDs from request`,{headers:e.headers,query:e.query,body:e.body});let n=(e.headers?.[w])?.split(`,`)||[],r=e.headers?.[`af-context`]?[e.headers[`af-context`]]:[],i=(e.query?.contextIds)?.split(`,`)||[],a=e.query?.contextId?[e.query.contextId]:[],o=e.query?.context?[e.query.context]:[],s=e.body?.contextIds||[],c=e.body?.contextId?[e.body.contextId]:[];return Array.from(new Set([...n,...r,...i,...a,...o,...s,...c])).filter(Boolean)},xe=(e,t,n,r,i,a,o,s,c)=>{if(r){s?.error(t,{url:a.url,method:a.method,requiredPermissions:c?.requiredPermissions||[],...c}),i.status(n).json({error:e,message:t,...c?.requiredPermissions&&{requiredPermissions:c.requiredPermissions}});return}s?.warn(t,{url:a.url,method:a.method,requiredPermissions:c?.requiredPermissions||[],...c}),o()},Se=(e,t,a)=>{try{r(i.HTTP_REQUEST);let a=new D(e,void 0,void 0,t);n().nonHeaderContext?.set(k,a)}catch(n){a?.error(`Error creating new user trace`,{error:n,userId:e,contextIds:t})}},Ce=async(e,t)=>{try{let n=((await x.get(`/api/v1/users/${e}/contexts`,{timeout:t}))?.data||[]).map(e=>e.id);return Se(e,n),n}catch(e){return[]}},we=(e,t={enforce:!1,requireAll:!0,permissionsEvaluationOperator:X.AND})=>async(n,r,i)=>{try{let{logger:a,enforce:o,requireAll:s,permissionsEvaluationOperator:c}=t,l=(t,s,c)=>xe(t,s,c,o,r,n,i,a,{requiredPermissions:e}),u=null;try{u=v(n.headers.authorization||``)}catch{}let d=z()||u?.user;if(!d?.id){l(Z.UNAUTHORIZED,Q.UNAUTHORIZED,401);return}let f=be(n,a),p=f?.length?[]:await Ce(d.id,t.timeout),m=Array.from(new Set([...f,...p]));if(!m?.length){l(Z.BAD_REQUEST,Q.BAD_REQUEST,400);return}let h=await ye({requiredPermissions:e,contextIds:m,logger:a,userId:d.id,options:{requireAll:s??!0,permissionsEvaluationOperator:c??X.AND,timeout:1e4,...a&&{logger:a}}});if(h.isAuthorized){a?.info(`User has required permissions`,{userId:d.id,requiredPermissions:e,contextIds:m,url:n.url,method:n.method}),i();return}if(!o){a?.warn(`User does not have required permissions, skipping enforcement`,{userId:d.id,requiredPermissions:e,contextIds:m,url:n.url,method:n.method}),i();return}r.status(403).json({error:Z.INSUFFICIENT_PERMISSIONS,message:Q.INSUFFICIENT_PERMISSIONS,required:e,contexts:m,userId:h.userId})}catch(a){if(t.logger?.error(`Error in requirePermissions middleware`,{error:a,requiredPermissions:e,url:n.url,method:n.method}),!t.enforce){t.logger?.error(`Error during permission check, skipping enforcement`,{error:a,url:n.url,method:n.method}),i();return}r.status(500).json({error:Z.INTERNAL_ERROR,message:Q.INTERNAL_ERROR})}};var $={};e($,{default:()=>De,middlewares:()=>Ee,sdk:()=>Te});const Te={evaluatePermissions:ye},Ee={requirePermissions:we};var De={sdk:Te,middlewares:Ee};const Oe=t.getCurrentContext,ke=({outbreakOptions:e={},logger:n}={})=>{t.default({headersPrefix:`x-af`,contextMiddlewareGetter:n?.addContextMiddleware,...e})},Ae=t.traceTypes,je=t.newTrace;var Me={traceTypes:Ae,newTrace:je,User:L,middleware:ae,middlewareWithDecode:M,eagerLoadPermissionsMiddleware:P,getCurrentPayload:Oe,getDecodedBearer:F,checkFleetPermission:H,checkBusinessModelPermission:U,checkDemandSourcePermission:W,isUserExist:B,getUser:z,UnauthorizedAccessError:G,appMiddleware:N,createOrSetRabbitTrace:I,outbreak:t,AUTHORIZATION_METHODS:K,getAuthorizationHeader:J,CONTEXTS_IDS_HEADER:w,authFromUserIdHeaderPlugin:R,permissions:$};export{K as AUTHORIZATION_METHODS,w as CONTEXTS_IDS_HEADER,G as UnauthorizedAccessError,L as User,N as appMiddleware,R as authFromUserIdHeaderPlugin,U as checkBusinessModelPermission,W as checkDemandSourcePermission,H as checkFleetPermission,I as createOrSetRabbitTrace,Me as default,P as eagerLoadPermissionsMiddleware,ke as enableTracing,J as getAuthorizationHeader,Oe as getCurrentPayload,F as getDecodedBearer,ee as getRefreshTokenSecret,g as getTokenSecret,z as getUser,B as isUserExist,ae as middleware,M as middlewareWithDecode,je as newTrace,t as outbreak,$ as permissions,Ae as traceTypes};
1
+ import{__export as e}from"./chunk-Cl8Af3a2.js";import*as t from"@autofleet/outbreak";import{getCurrentContext as n,newTrace as r,traceTypes as i}from"@autofleet/outbreak";import a from"jsonwebtoken";import o from"node-cache";import s from"object-hash";import c from"moment";import l from"@autofleet/network";const{DEPRECATED_JWT_SECRET:u,JWT_NEW_SECRET:d,DEPRECATED_REFRESH_JWT_SECRET:f,REFRESH_JWT_SECRET:p,DEPRECATION_UNIX_TIMESTAMP:m}=process.env,h=(e,t,n)=>{let r=c(parseInt(m||``,10)*1e3);try{let i;if(e){let{iat:t}=a.decode(e);i=c(t*1e3)}else i=c();return i.isBefore(r)?t:n}catch{return n}},ee=e=>h(e,f,p),g=e=>h(e,u,d),_=e=>e.replace(`Bearer `,``),v=(e,t)=>{let n=_(e),r=a.verify(n,t||g(n));return r},y=`[0-9a-f]`,te=RegExp(`^(?:${y}{8}-${y}{4}-[1-8]${y}{3}-[89ab]${y}{3}-${y}{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$`,`i`);function ne(e){return typeof e==`string`&&te.test(e)}const b=process.env.API_GATEWAY_URL||`https://api.autofleet.io`,x=new l({serviceName:`IDENTITY_MS`,retries:3,retryCondition:()=>!0,cache:process.env.NODE_ENV===`test`?void 0:{maxAge:10*1e3}}),S=new l({baseURL:b,serviceUrl:b,retries:3,retryCondition:()=>!0,cache:process.env.NODE_ENV===`test`?void 0:{maxAge:10*1e3}}),C=`x-af-elevated-permissions`,w=`x-af-context-ids`,T=new o({stdTTL:10}),E=(e,t)=>{let n={...e,fleets:{...e?.fleets},businessModels:{...e?.businessModels},demandSources:{...e?.demandSources}};for(let e of t)Object.entries(e??{}).forEach(([e,t])=>{n[e]??={},Object.entries(t).forEach(([t,r])=>{n[e][t]=(n[e][t]||[]).concat(r)})});return n};typeof Symbol.dispose!=`symbol`&&Object.defineProperty(Symbol,`dispose`,{__proto__:null,configurable:!1,enumerable:!1,value:Symbol.for(`nodejs.dispose`),writable:!1}),typeof Symbol.asyncDispose!=`symbol`&&Object.defineProperty(Symbol,`asyncDispose`,{__proto__:null,configurable:!1,enumerable:!1,value:Symbol.for(`nodejs.asyncDispose`),writable:!1});var D=class{constructor(e,t,n,r){this.id=e,this.accountType=t,this.contextIds=r,this.privateElevatedPermissionsHash=new Map,this.appPermission={},this.emptyUser=!!e,n&&this.privateElevatedPermissionsHash.set(Symbol(`initial`),n)}async getUserPermissions(){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let e=s({id:this.id,contextIds:this.contextIds}),t=T.get(e);return t||({data:t}=await x.get(`/api/v1/users/${this.id}/authorization-payload`,{params:{contextIds:this.contextIds}}),T.set(e,t)),this.accountType=t.accountType,this.privatePermissions=t,this.privatePermissions}async useCustomPermissionLoader(e){if(!this.id)return;if(this.privatePermissions)return this.privatePermissions;let t=this.id,n=T.get(t);if(n)return this.privatePermissions=n,n;let r=await e(this.id);return T.set(t,r),this.privatePermissions=r,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 Error(`Cannot get ${e} without calling (async) getUserPermissions before`);return Object.keys(this.privatePermissions[e]||{})}get elevatedPermissions(){return E(void 0,this.privateElevatedPermissionsHash.values())}get permissions(){if(!this.privatePermissions)throw Error(`Cannot get permissions without calling (async) getUserPermissions before`);return E(this.privatePermissions,this.privateElevatedPermissionsHash.values())}elevatePermissions(e){let t=Symbol();Object.values(e).forEach(e=>{Object.keys(e).forEach(e=>{if(!ne(e))throw Error(`Entity id on elevatePermissions is not a valid UUID, provided: ${e}`)})});let r=n();if(!r)throw Error(`Cannot find current user cross services trace`);let i=JSON.parse(r.context?.get(C)||`{}`),a=Object.assign(i,e);this.privateElevatedPermissionsHash.set(t,a),r.context.set(C,JSON.stringify(this.elevatedPermissions));let o=()=>{this.privateElevatedPermissionsHash.delete(t),r.context.set(C,JSON.stringify(this.elevatedPermissions))};return o[Symbol.dispose]=o,o}async getUserPermissionsLegacy(){if(!this.id)return;if(this.privatePermissionsLegacy)return this.privatePermissionsLegacy;let e=s({id:this.id,contextIds:this.contextIds,legacy:!0}),t=T.get(e);return t||({data:t}=await x.get(`/api/v1/users/${this.id}/authorization-payload-legacy`,{params:{contextIds:this.contextIds}}),T.set(e,t)),this.privatePermissionsLegacy=t,this.privatePermissionsLegacy}get permissionsLegacy(){if(!this.privatePermissionsLegacy)throw Error(`Cannot get permissionsLegacy without calling (async) getUserPermissionsLegacy before`);return this.privatePermissionsLegacy}async getUserAppPermissions(e,t){if(!this.id||!e||!t)return;let n=this.appPermission[e];if(n)return n;let r=`${this.id}:${e}`,i=T.get(r);if(i)return this.appPermission[e]=i,i;let{data:a}=await S.post(`/api/v1/apps/${e}/get-user-payload`,{userId:this.id},{headers:{"x-autofleet-apps-secret":t}});return T.set(r,a),this.appPermission[e]=a,this.appPermission[e]}};const re=async(e,t)=>{let{data:n}=await S.post(`/api/v1/auth`,{bearer:e,appId:t});return n};var O=class extends Error{constructor(...e){super(...e),this.name=`AppDoesNotExist`,this.message=`app does not exist`}};const k=`userObject`,A=`x-af-user-id`,j=`x-af-user-permissions`,ie=async(e,t)=>{let r=t[`X-IAF-ORIGIN-SERVICE`]||t[`x-iaf-origin-service`]||``;if(!Array.isArray(r)&&r.toLowerCase()===`identity-ms`)return;let{eagerLoadUserPermissions:i,eagerLoadUserPermissionsLegacy:a,customPermissionLoader:o}=e,s=t[A];if(!s||Array.isArray(s))return;let c=t[C],l=c?.length&&c.length>0?JSON.parse(c):{},u=(t?.[w])?.split(`,`),d=new D(s,`user`,l,u);return i&&(o?await d.useCustomPermissionLoader(o):await d.getUserPermissions()),a&&await d.getUserPermissionsLegacy(),n().nonHeaderContext?.set(k,d),d},ae=(e={})=>async(t,n,r)=>{try{let n=await ie(e,t.headers);n&&(t.user=n,t.headers[j]=n),r()}catch{n.status(401).json({error:`cannot authenticate user`})}},M=(e={})=>async(t,r,i)=>{let{eagerLoadUserPermissions:o,eagerLoadUserPermissionsLegacy:s,returnErrorIfNoToken:c}=e,l;if(t.headers.authorization){try{l=await v(t.headers.authorization)}catch(e){e instanceof a.TokenExpiredError?r.status(401).json({errors:[`Access token expired`]}):e instanceof a.JsonWebTokenError?r.status(400).json({errors:[e.message]}):r.status(500).json({errors:[`Server error while parsing token`]});return}let e=l?.user?.id;e&&(t.headers[A]=e);let i=(t.headers?.[w])?.split(`,`),c=new D(e,l?.user?.accountType,void 0,i);(o||s)&&await Promise.all([o&&c.getUserPermissions(),s&&c.getUserPermissionsLegacy()]),t.user=c,n().nonHeaderContext?.set(k,c),t.headers[j]=c}else if(c){r.status(401).json({errors:[`No token provided`]});return}i()},N=e=>async(t,r,i)=>{let{appId:o,clientSecret:s}=e,c;if(!t.headers.authorization){r.status(401).json({errors:[`No token provided`]});return}try{if(c=await re(t.headers.authorization,o),!c)throw new O}catch(e){if(e instanceof a.TokenExpiredError){r.status(401).json({errors:[`Access token expired`]});return}if([a.JsonWebTokenError,O].some(t=>e instanceof t)){r.status(400).json({errors:[e.message]});return}r.status(500).json({errors:[`Server error while parsing token`]});return}let l=c?.userId;l&&(t.headers[A]=l);let u=new D(l);o&&(t.headers[`x-autofleet-apps-secret`]=s,await u.getUserAppPermissions(o,s)),t.user=u;let d=n().nonHeaderContext;d?.set(k,u),d?.set(`accessToken`,_(t.headers.authorization)),t.headers[j]=u,i()},P=async(e,t,n)=>{await e.user.getUserPermissions(),n()},F=e=>e.headers.authorization?v(e.headers.authorization):null,I=async(e,t)=>{let n=new D(t);await n.getUserPermissions(),e??=r(i.RABBIT),e.nonHeaderContext.set(k,n)};var L=D;const R=(e,t,n)=>{e.decorateRequest(`user`,void 0),e.addHook(`onRequest`,async(e,n)=>{try{let n=await ie(t,e.headers);n&&(e.user=n)}catch{n.status(401).send({error:`cannot authenticate user`})}}),n()};Object.defineProperty(R,Symbol.for(`skip-override`),{value:!0});const z=()=>n().nonHeaderContext?.get(k),B=()=>z()?.id,V=(e,t)=>!B()||Object.hasOwn(z().permissions?.[t]??{},e),H=e=>V(e,`fleets`),U=e=>V(e,`businessModels`),W=e=>V(e,`demandSources`);var G=class extends Error{constructor(e=null,t=`UnauthorizedAccessError`){super(t),this.user=e,this.name=`UnauthorizedAccessError`}};const K={NONE:`NONE`,BASIC:`BASIC`,JWT:`JWT`},q={[K.NONE]:()=>void 0,[K.BASIC]:e=>{let{username:t,password:n}=e,r=Buffer.from(`${t}:${n}`).toString(`base64`);return`Basic ${r}`},[K.JWT]:e=>{let{secret:t}=e;if(t)return`Bearer ${a.sign({},t,{expiresIn:10})}`}},J=e=>{let t=e?.method;if(!(!t||!q[t]))return q[t](e)};var oe=class e{constructor(e,t){this.ttl=10,t&&(this.ttl=t),this.cache=e??new o({stdTTL:this.ttl})}static getCacheKeys(e,t,n){let r=`${e}-${t}`,i=n.map(e=>`${r}-${e}`);return{baseCacheKey:r,cacheKeys:i}}getUserPermissions(t,n){try{let{baseCacheKey:r,cacheKeys:i}=e.getCacheKeys(`perm`,t,n),a=this.cache.mget(i),o={};return Object.entries(a).filter(([,e])=>e).forEach(([e,t])=>{let n=e.replace(`${r}-`,``);o[n]=t}),o}catch{return{}}}setUserPermissions(e,t){try{let n=t=>`perm-${e}-${t}`,r=Object.entries(t).map(([e,t])=>({key:n(e),val:t,ttl:this.ttl}));return this.cache.mset(r),{success:!0}}catch{return{success:!1}}}getCachedDeniedPermissions(t,n){try{let{baseCacheKey:r,cacheKeys:i}=e.getCacheKeys(`seen`,t,n),a=this.cache.mget(i),o={};return Object.entries(a).filter(([,e])=>e).forEach(([e,t])=>{let n=e.replace(`${r}-`,``);o[n]=t}),o}catch{return{}}}setCachedDeniedPermissions(e,t,n){try{let r=t=>`seen-${e}-${t}`,i=t.map(e=>({key:r(e),val:n,ttl:this.ttl}));return this.cache.mset(i),{success:!0}}catch{return{success:!1}}}};const Y=new oe,X={AND:`and`,OR:`or`},Z={USER_NOT_FOUND:`USER_NOT_FOUND`,INSUFFICIENT_PERMISSIONS:`INSUFFICIENT_PERMISSIONS`,VALIDATION_ERROR:`VALIDATION_ERROR`,API_ERROR:`API_ERROR`,NO_REQUIRED_PERMISSIONS:`NO_REQUIRED_PERMISSIONS`,UNAUTHORIZED:`UNAUTHORIZED`,BAD_REQUEST:`BAD_REQUEST`,INTERNAL_ERROR:`INTERNAL_ERROR`},Q={USER_NOT_FOUND:`User not found`,INSUFFICIENT_PERMISSIONS:`User does not have sufficient permissions`,VALIDATION_ERROR:`Validation error occurred`,API_ERROR:`API error occurred`,NO_REQUIRED_PERMISSIONS:`No required permissions provided for evaluation`,UNAUTHORIZED:`User is not authorized to perform this action`,BAD_REQUEST:`Bad request, please check the input parameters`,INTERNAL_ERROR:`Internal server error occurred while checking permissions`},se=(e,t,n)=>{let r=new Set(e),i=t.filter(e=>r.has(e));return n===X.AND?i.length===t.length:i.length>0},ce=(e,t)=>{let n=Object.values(e);return t?n.every(e=>e.hasRequiredPermissions):n.some(e=>e.hasRequiredPermissions)},le=e=>{let t=[];return e?.length||t.push(`contextIds cannot be empty`),t},ue=(e,t,n,r)=>({isAuthorized:!1,error:e,resolvedPermissions:{},requiredPermissions:t,contextIds:n,...r&&{message:r}}),de=(e,t,n,r)=>{let i={},a=new Map;if(r?.debug(`Start caching permissions results`,{userId:e,resolvedPermissions:t,requiredPermissions:n}),Object.entries(t).forEach(([e,t])=>{if(t?.permissions){let r=new Set(t.permissions),o=n.filter(e=>r.has(e)),s=n.filter(e=>!r.has(e));if(o.length&&(i[e]=o),s.length){let t=s.sort().join(`,`);a.has(t)||a.set(t,[]),a.get(t).push(e)}}}),Object.keys(i).length>0){let t=Y.getUserPermissions(e,Object.keys(i));Object.keys(t??{}).forEach(e=>{if(i[e]){let n=Array.from(new Set([...t[e]||[],...i[e]]));i[e]=n}}),r?.debug(`Caching granted permissions`,{userId:e,permissionsToCache:i,pastCache:t});let{success:n}=Y.setUserPermissions(e,i);n||r?.error(`Failed to cache granted permissions`,{userId:e,permissionsToCache:i})}Array.from(a.entries()).map(([t,n])=>{let r=t.split(`,`);return Y.setCachedDeniedPermissions(e,n,r)}),r?.debug(`Caching denied permissions`,{userId:e,deniedPermissionsGroups:Array.from(a.entries()).map(([e,t])=>({deniedPermissions:e.split(`,`),contextIds:t}))})},fe=(e,t,n)=>{if(!e.length)return{isResolvableFromCache:!1,hasRequiredPermissions:!1};let r=new Set(e),i=t.filter(e=>r.has(e));return n===X.AND?{isResolvableFromCache:i.length>0,hasRequiredPermissions:!1}:{isResolvableFromCache:i.length===t.length,hasRequiredPermissions:!1}},pe=(e,t,n)=>{let r=[...e],i=t.filter(e=>!n[e]);return r.push(...i),r},me=(e,t,n,r)=>{let i={};return e.forEach(e=>{let a=t[e],o=fe(a,n,r);o.isResolvableFromCache&&(i[e]={permissions:[],hasRequiredPermissions:o.hasRequiredPermissions})}),i},he=(e,t,n)=>{let r={};return Object.keys(e||{}).length&&Object.entries(e).forEach(([e,i])=>{let a=se(i,t,n);a&&(r[e]={permissions:i,hasRequiredPermissions:a})}),r},ge=async(e,t,n,r)=>{let i=await x.post(`/api/v1/permissions/resolve`,{userId:e,contextIds:t,requiredPermissions:n},{timeout:r.timeout}),a=i?.data||{};if(!Object.keys(a||{}).length)throw Error(`Failed to resolve permissions`);if(r.permissionsEvaluationOperator===X.AND)return a;let o={};return Object.entries(a).forEach(([e,t])=>{let i=t?.permissions||[],a=se(i,n,r.permissionsEvaluationOperator);o[e]={permissions:i,hasRequiredPermissions:a}}),o},_e=(e,t,n,r)=>{let i=le(e);return i.length?ue(Z.VALIDATION_ERROR,t,e,i.join(`, `)):n?t?.length?null:(r?.info(`No requiredPermissions provided`,{userId:n,contextIds:e}),{isAuthorized:!1,userId:n,resolvedPermissions:{},requiredPermissions:t,contextIds:e,error:Z.NO_REQUIRED_PERMISSIONS}):(r?.warn(`User not found in context, cannot check permissions`,{contextIds:e,requiredPermissions:t}),ue(Z.USER_NOT_FOUND,t,e))},ve=async(e,t,n,r,i)=>{let a={...i},o=await ge(e,t,n,r);return a={...i,...o},de(e,o,n),a},ye=async(e,t,n,r)=>{let{logger:i}=r,a=Y.getUserPermissions(e,t),o=he(a,n,r.permissionsEvaluationOperator),s={...o},c=t.filter(e=>!o[e]),l=Y.getCachedDeniedPermissions(e,c),u=c.filter(e=>!l[e]),d=c.filter(e=>l[e]),f=me(d,l,n,r.permissionsEvaluationOperator);s={...s,...f};let p=pe(u,d,f);return p.length?ve(e,p,n,r,s):(i?.debug(`Final resolved permissions`,{userId:e,requiredPermissions:n,resolvedPermissions:s}),s)},be=async({requiredPermissions:e,contextIds:t,logger:n,userId:r,options:{requireAll:i=!0,permissionsEvaluationOperator:a=X.AND,timeout:o=1e4}})=>{let s=r||z()?.id||null,c=_e(t,e,s,n);if(c)return c;let l=await ye(s,t,e,{permissionsEvaluationOperator:a,timeout:o,logger:n}),u=ce(l,i);return n?.info(`Resolved permissions`,{userId:s,requiredPermissions:e,resolvedPermissions:l,isAuthorized:u,requireAll:i,permissionsEvaluationOperator:a,contextIds:t}),{isAuthorized:u,userId:s,resolvedPermissions:l,requiredPermissions:e,contextIds:t,...u?{}:{error:Z.INSUFFICIENT_PERMISSIONS}}},xe=(e,t)=>{t?.debug(`Extracting context IDs from request`,{headers:e.headers,query:e.query,body:e.body});let n=(e.headers?.[w])?.split(`,`)||[],r=e.headers?.[`af-context`]?[e.headers[`af-context`]]:[],i=(e.query?.contextIds)?.split(`,`)||[],a=e.query?.contextId?[e.query.contextId]:[],o=e.query?.context?[e.query.context]:[],s=e.body?.contextIds||[],c=e.body?.contextId?[e.body.contextId]:[];return Array.from(new Set([...n,...r,...i,...a,...o,...s,...c])).filter(Boolean)},Se=(e,t,n,r,i,a,o,s,c)=>{if(r){s?.error(t,{url:a.url,method:a.method,requiredPermissions:c?.requiredPermissions??[],...c}),i.status(n).json({error:e,message:t,...c?.requiredPermissions&&{requiredPermissions:c.requiredPermissions}});return}s?.warn(t,{url:a.url,method:a.method,requiredPermissions:c?.requiredPermissions??[],...c}),o()},Ce=(e,t,a)=>{try{r(i.HTTP_REQUEST);let a=new D(e,void 0,void 0,t);n().nonHeaderContext?.set(k,a)}catch(n){a?.error(`Error creating new user trace`,{error:n,userId:e,contextIds:t})}},we=async(e,t)=>{try{let n=await x.get(`/api/v1/users/${e}/contexts`,{timeout:t}),r=(n?.data||[]).map(e=>e.id);return Ce(e,r),r}catch{return[]}},Te=(e,t={enforce:!1,requireAll:!0,permissionsEvaluationOperator:X.AND})=>async(n,r,i)=>{try{let{logger:a,enforce:o,requireAll:s,permissionsEvaluationOperator:c}=t,l=(t,s,c)=>Se(t,s,c,o,r,n,i,a,{requiredPermissions:e}),u=null;try{u=v(n.headers.authorization||``)}catch{}let d=z()??u?.user;if(!d?.id){l(Z.UNAUTHORIZED,Q.UNAUTHORIZED,401);return}let f=xe(n,a),p=f?.length?[]:await we(d.id,t.timeout),m=Array.from(new Set([...f,...p]));if(!m?.length){l(Z.BAD_REQUEST,Q.BAD_REQUEST,400);return}let h=await be({requiredPermissions:e,contextIds:m,logger:a,userId:d.id,options:{requireAll:s??!0,permissionsEvaluationOperator:c??X.AND,timeout:1e4,...a&&{logger:a}}});if(h.isAuthorized){a?.info(`User has required permissions`,{userId:d.id,requiredPermissions:e,contextIds:m,url:n.url,method:n.method}),i();return}if(!o){a?.warn(`User does not have required permissions, skipping enforcement`,{userId:d.id,requiredPermissions:e,contextIds:m,url:n.url,method:n.method}),i();return}r.status(403).json({error:Z.INSUFFICIENT_PERMISSIONS,message:Q.INSUFFICIENT_PERMISSIONS,required:e,contexts:m,userId:h.userId})}catch(a){let o=t.logger;if(o?.error(`Error in requirePermissions middleware`,{error:a,requiredPermissions:e,url:n.url,method:n.method}),!t.enforce){t.logger?.error(`Error during permission check, skipping enforcement`,{error:a,url:n.url,method:n.method}),i();return}r.status(500).json({error:Z.INTERNAL_ERROR,message:Q.INTERNAL_ERROR})}};var $={};e($,{default:()=>Oe,middlewares:()=>De,sdk:()=>Ee});const Ee={evaluatePermissions:be},De={requirePermissions:Te};var Oe={sdk:Ee,middlewares:De};const ke=t.getCurrentContext,Ae=({outbreakOptions:e={},logger:n}={})=>{t.default({headersPrefix:`x-af`,contextMiddlewareGetter:n?.addContextMiddleware,...e})},je=t.traceTypes,Me=t.newTrace,Ne={traceTypes:je,newTrace:Me,User:L,middleware:ae,middlewareWithDecode:M,eagerLoadPermissionsMiddleware:P,getCurrentPayload:ke,getDecodedBearer:F,checkFleetPermission:H,checkBusinessModelPermission:U,checkDemandSourcePermission:W,isUserExist:B,getUser:z,UnauthorizedAccessError:G,appMiddleware:N,createOrSetRabbitTrace:I,outbreak:t,AUTHORIZATION_METHODS:K,getAuthorizationHeader:J,CONTEXTS_IDS_HEADER:w,authFromUserIdHeaderPlugin:R,permissions:$};var Pe=Ne;export{K as AUTHORIZATION_METHODS,w as CONTEXTS_IDS_HEADER,G as UnauthorizedAccessError,L as User,N as appMiddleware,R as authFromUserIdHeaderPlugin,U as checkBusinessModelPermission,W as checkDemandSourcePermission,H as checkFleetPermission,I as createOrSetRabbitTrace,Pe as default,P as eagerLoadPermissionsMiddleware,Ae as enableTracing,J as getAuthorizationHeader,ke as getCurrentPayload,F as getDecodedBearer,ee as getRefreshTokenSecret,g as getTokenSecret,z as getUser,B as isUserExist,ae as middleware,M as middlewareWithDecode,Me as newTrace,t as outbreak,$ as permissions,je as traceTypes};
2
2
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["unixTime: moment.Moment","IdentityNetwork: Network","AutofleetApiNetwork: Network","permissions: UserPayload","id?: string","accountType?: AccountType | undefined","contextIds?: string[]","eagerLoadPermissionsMiddleware: Asyncify<Handler>","newTrace","traceTypes","authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions>","user: ApiUser | null","result: EntityPermissions","result: Record<string, string[]>","permissionCache: PermissionCache","errors: string[]","permissionsToCache: PermissionsByContextId","result: PermissionsEvaluationByContextId","processedPermissions: PermissionsEvaluationByContextId","data: PermissionsEvaluationByContextId","reEvaluatedPermissions: PermissionsEvaluationByContextId","newResolvedPermissions: PermissionsEvaluationByContextId","traceTypes","decodedToken: { user?: { id?: string } } | null","contextIdsFromRequest: string[]","sdk: SdkExports","middlewares: MiddlewareExports","getCurrentPayload: typeof outbreak.getCurrentContext","traceTypes: typeof outbreak.traceTypes","newTrace: typeof outbreak.newTrace","zehutDefault: Default"],"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/permissions/SDK/permissionCache.ts","../src/permissions/SDK/consts.ts","../src/permissions/SDK/evaluatePermissions.ts","../src/permissions/middleware/requirePermissions.ts","../src/permissions/index.ts","../src/index.ts"],"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 jwt from 'jsonwebtoken';\nimport { getTokenSecret } from './secret-getter';\n\ntype Context = Partial<Record<ContextProp | 'id', string>> & { subSystem?: SubSystemType; permissions?: string[]; entityId: string; };\n\nconst CONTEXT_PROPS = ['fleetId', 'businessModelId', 'demandSourceId'] as const;\ntype ContextProp = typeof CONTEXT_PROPS[number];\nconst CONTEXT_MAP_PROPS = {\n fleet: 'fleets',\n business: 'businessModels',\n demand: 'demandSources',\n} as const;\ntype SubSystemType = keyof typeof CONTEXT_MAP_PROPS;\ntype ContextSubSystemProp = typeof CONTEXT_MAP_PROPS[SubSystemType];\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: string, decodedToken: { contexts: Context[]; }): { key: string; value: string; } | undefined => {\n if (!decodedToken) return undefined;\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\ntype EntitiesFromContext = { [key in ContextSubSystemProp]?: Record<string, string> };\nexport const getEntitiesFromContext = (contextId: string | undefined, decodedToken: { contexts: Context[]; }): EntitiesFromContext => {\n if (!decodedToken) return {};\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n\n const attributes: EntitiesFromContext = {};\n contexts.forEach((context) => {\n const prop = CONTEXT_MAP_PROPS[context.subSystem || 'business'];\n\n const permissions = parsePermissions(context.id!, decodedToken);\n if (!permissions) return;\n attributes[prop] ||= {};\n attributes[prop][permissions.key] = permissions.value;\n });\n\n return attributes;\n};\n\ntype ContextAttributes = { [key in ContextProp]?: string[] };\nexport const getContextAttributes = (contextId: string | undefined, decodedToken: { contexts: Context[]; }): ContextAttributes => {\n if (!decodedToken) return {};\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter((context) => context.id === contextId);\n }\n const attributes: ContextAttributes = {};\n contexts.forEach((context) => {\n CONTEXT_PROPS.forEach((prop) => {\n if (context[prop]) {\n attributes[prop] ||= [];\n attributes[prop].push(context[prop]);\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: Network = 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: Network = 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 | undefined, sources: Iterable<PartialUserPayload | undefined>): 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.entries(source || {}) as [Exclude<keyof UserPayload, 'accountType' | 'createdAt'>, EntityPermissions][]).forEach(([entityType, entityValue]) => {\n // eslint-disable-next-line no-param-reassign\n permissions[entityType] ??= {};\n Object.entries(entityValue).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\nif (typeof Symbol.dispose !== 'symbol') {\n // Polyfill for dispose if it does not exist, based on https://github.com/nodejs/node/blob/9a9409ff1f45c968173118de4cd37dea784f8ec9/lib/internal/process/pre_execution.js#L163-L171\n Object.defineProperty(Symbol, 'dispose', {\n // @ts-expect-error: TypeScript does not recognize __proto__ as a valid property\n __proto__: null,\n configurable: false,\n enumerable: false,\n value: Symbol.for('nodejs.dispose'),\n writable: false,\n });\n}\nif (typeof Symbol.asyncDispose !== 'symbol') {\n // Polyfill for asyncDispose if it does not exist, based on https://github.com/nodejs/node/blob/9a9409ff1f45c968173118de4cd37dea784f8ec9/lib/internal/process/pre_execution.js#L174-L183\n Object.defineProperty(Symbol, 'asyncDispose', {\n // @ts-expect-error: TypeScript does not recognize __proto__ as a valid property\n __proto__: null,\n configurable: false,\n enumerable: false,\n value: Symbol.for('nodejs.asyncDispose'),\n writable: false,\n });\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 | undefined, 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[] {\n return this.getUserProperty('businessModels');\n }\n\n public get fleets(): string[] {\n return this.getUserProperty('fleets');\n }\n\n public get demandSources(): string[] {\n return this.getUserProperty('demandSources');\n }\n\n private getUserProperty(key: keyof UserPayload): string[] {\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) & { [Symbol.dispose]: () => 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?.get(ELEVATED_PERMISSIONS_HEADER) as string | undefined || '{}');\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 const cleanup = () => {\n this.privateElevatedPermissionsHash.delete(elevationId);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n };\n cleanup[Symbol.dispose] = cleanup;\n return cleanup;\n }\n\n public async getUserPermissionsLegacy(): Promise<unknown> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissionsLegacy) {\n return this.privatePermissionsLegacy;\n }\n\n const cacheKey = objectHash({\n id: this.id,\n contextIds: this.contextIds,\n legacy: true,\n });\n let data = userCache.get(cacheKey);\n\n if (!data) {\n ({ data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload-legacy`, { params: { contextIds: this.contextIds } }));\n userCache.set(cacheKey, data);\n }\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: string, clientSecret: string): Promise<UserPayload | undefined> {\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() as Lowercase<typeof ORIGIN_HEADER>;\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 elevatedPermHeaderValue = headers[ELEVATED_PERMISSIONS_HEADER];\n const elevatedPermissionsFromHeader = elevatedPermHeaderValue?.length && elevatedPermHeaderValue.length > 0 ? JSON.parse(elevatedPermHeaderValue 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\ntype Asyncify<T extends (...a: any[]) => any> = (...a: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n\nexport const middleware = (options: AuthFromUserIdHeaderOptions = {}): Asyncify<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} = {}): Asyncify<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}): Asyncify<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 as Error).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: Asyncify<Handler> = async (req, res, next) => {\n await req.user.getUserPermissions();\n next();\n};\n\nexport const getDecodedBearer = (req: Request): any => {\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): Promise<void> => {\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.decorateRequest('user', undefined);\n fastify.addHook('onRequest', async (request, reply) => {\n try {\n const user = await authFromUserIdHeader(options, request.headers);\n if (user) {\n request.user = user;\n }\n } catch (e) {\n reply.status(401).send({ error: 'cannot authenticate user' });\n }\n });\n\n done();\n};\nObject.defineProperty(authFromUserIdHeaderPlugin, Symbol.for('skip-override'), { value: 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 = (): string | undefined => 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): boolean => checkUserPermissions(fleetId, 'fleets');\nexport const checkBusinessModelPermission = (businessModelId: string): boolean => checkUserPermissions(businessModelId, 'businessModels');\nexport const checkDemandSourcePermission = (demandSourceId: string): boolean => 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 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 NodeCache from 'node-cache';\n\ninterface EntityPermissions {\n [key: string]: string[];\n}\n\nexport class PermissionCache {\n private cache: NodeCache;\n\n private ttl: number = 10;\n\n /**\n * Creates a new PermissionCache instance\n * @param cache - Optional NodeCache instance. If not provided, creates a new one with default TTL of 10 seconds\n */\n constructor(cache?: NodeCache, ttl?: number) {\n if (ttl) {\n this.ttl = ttl;\n }\n this.cache = cache || new NodeCache({ stdTTL: this.ttl });\n }\n\n private static getCacheKeys(cacheName: string, userId: string, contextIds: string[]) {\n const baseCacheKey = `${cacheName}-${userId}`;\n const cacheKeys = contextIds.map((contextId) => `${baseCacheKey}-${contextId}`);\n\n return { baseCacheKey, cacheKeys };\n }\n\n /**\n * Retrieves user permissions for multiple contexts from cache\n * @param userId - The user identifier\n * @param contextIds - Array of context identifiers to fetch permissions for\n * @returns Promise that resolves to an object mapping context IDs to permission arrays\n */\n public async getUserPermissions(userId: string, contextIds: string[]): Promise<EntityPermissions> {\n try {\n const { baseCacheKey, cacheKeys } = PermissionCache.getCacheKeys('perm', userId, contextIds);\n const cacheResult = await this.cache.mget(cacheKeys) as Record<string, string[]>;\n\n const result: EntityPermissions = {};\n Object.entries(cacheResult)\n .filter(([, permissions]) => permissions)\n .forEach(([key, permissions]) => {\n const contextId = key.replace(`${baseCacheKey}-`, '');\n result[contextId] = permissions;\n });\n\n return result;\n } catch (error) {\n return {};\n }\n }\n\n /**\n * Stores user permissions for multiple contexts in cache\n * @param userId - The user identifier\n * @param PermissionsByContextId - Object mapping context IDs to permission arrays\n * @param ttl - Optional time to live in seconds. Defaults to 10 seconds\n * @returns Promise that resolves to an object indicating success/failure\n */\n public async setUserPermissions(userId: string, PermissionsByContextId: EntityPermissions): Promise<{ success: boolean }> {\n try {\n const cacheKey = (contextId: string) => `perm-${userId}-${contextId}`;\n\n const cacheEntries = Object.entries(PermissionsByContextId).map(([contextId, permissions]) => ({\n key: cacheKey(contextId),\n val: permissions,\n ttl: this.ttl,\n }));\n\n await this.cache.mset(cacheEntries);\n\n return { success: true };\n } catch (error) {\n return { success: false };\n }\n }\n\n /**\n * Retrieves denied permissions status for multiple contexts from cache.\n * \"Denied\" permissions indicate that a user has already been evaluated for a specific set of\n * required permissions in a given context, avoiding redundant permission checks.\n * @param userId - The user identifier\n * @param contextIds - Array of context identifiers to check\n * @returns Promise that resolves to an object mapping context IDs to arrays of denied permissions\n */\n public async getCachedDeniedPermissions(userId: string, contextIds: string[]): Promise<Record<string, string[]>> {\n try {\n const { baseCacheKey, cacheKeys } = PermissionCache.getCacheKeys('seen', userId, contextIds);\n const cacheResult = await this.cache.mget(cacheKeys) as Record<string, string[]>;\n\n const result: Record<string, string[]> = {};\n Object.entries(cacheResult)\n .filter(([, permissions]) => permissions)\n .forEach(([key, permissions]) => {\n const contextId = key.replace(`${baseCacheKey}-`, '');\n result[contextId] = permissions;\n });\n\n return result;\n } catch (error) {\n return {};\n }\n }\n\n /**\n * Marks permissions as seen for multiple contexts in cache.\n * \"Seen\" permissions are used to track that a user has already been evaluated for a specific\n * set of required permissions in given contexts, preventing duplicate permission evaluations.\n * @param userId - The user identifier\n * @param contextIds - Array of context identifiers to mark as seen\n * @param deniedPermissions - Array of permissions that were evaluated and denied\n * @param ttl - Optional time to live in seconds. Defaults to 10 seconds\n * @returns Promise that resolves to an object indicating success/failure\n */\n public async setCachedDeniedPermissions(userId: string, contextIds: string[], deniedPermissions: string[]): Promise<{ success: boolean }> {\n try {\n const seenKey = (contextId: string) => `seen-${userId}-${contextId}`;\n\n const cacheEntries = contextIds.map((contextId) => ({\n key: seenKey(contextId),\n val: deniedPermissions,\n ttl: this.ttl,\n }));\n\n await this.cache.mset(cacheEntries);\n\n return { success: true };\n } catch (error) {\n return { success: false };\n }\n }\n}\n\nexport const permissionCache: PermissionCache = new PermissionCache();\n","export const PERMISSIONS_EVALUATION_OPERATORS = {\n AND: 'and',\n OR: 'or',\n};\n\nexport const PERMISSION_ERROR_TYPES = {\n USER_NOT_FOUND: 'USER_NOT_FOUND',\n INSUFFICIENT_PERMISSIONS: 'INSUFFICIENT_PERMISSIONS',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n API_ERROR: 'API_ERROR',\n NO_REQUIRED_PERMISSIONS: 'NO_REQUIRED_PERMISSIONS',\n UNAUTHORIZED: 'UNAUTHORIZED',\n BAD_REQUEST: 'BAD_REQUEST',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n};\n\nexport const PERMISSION_ERROR_MESSAGES = {\n USER_NOT_FOUND: 'User not found',\n INSUFFICIENT_PERMISSIONS: 'User does not have sufficient permissions',\n VALIDATION_ERROR: 'Validation error occurred',\n API_ERROR: 'API error occurred',\n NO_REQUIRED_PERMISSIONS: 'No required permissions provided for evaluation',\n UNAUTHORIZED: 'User is not authorized to perform this action',\n BAD_REQUEST: 'Bad request, please check the input parameters',\n INTERNAL_ERROR: 'Internal server error occurred while checking permissions',\n};\n","import { getUser } from '../../check-permission';\nimport { IdentityNetwork } from '../../services';\nimport {\n PermissionsEvaluationOperator,\n type EvaluatePermissionsParams,\n type PermissionsEvaluationByContextId,\n type PermissionCheckResult,\n type ResolvePermissionsParams,\n type Logger,\n PermissionsByContextId,\n} from './types';\nimport { type PermissionErrorType } from './errors';\nimport { permissionCache } from './permissionCache';\nimport { PERMISSIONS_EVALUATION_OPERATORS, PERMISSION_ERROR_TYPES } from './consts';\n\n/**\n * Evaluates whether user permissions meet requirements based on AND/OR operator\n * @param permissions - User's actual permissions\n * @param requiredPermissions - Required permissions to check against\n * @param operator - {@link PermissionsEvaluationOperator} AND (all required) or OR (at least one required)\n * @returns true if permissions meet requirements\n */\nconst evaluatePermissionsByOperator = (\n permissions: string[],\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): boolean => {\n const permissionsSet = new Set(permissions);\n const matchingPermissions = requiredPermissions.filter((permission) => permissionsSet.has(permission));\n\n return operator === PERMISSIONS_EVALUATION_OPERATORS.AND\n ? matchingPermissions.length === requiredPermissions.length // All required permissions must be present\n : matchingPermissions.length > 0; // At least one required permission must be present\n};\n\n/**\n * Creates empty permissions result for cases with no required permissions\n * @param contextIds - Context IDs to create results for\n * @returns {@link PermissionsEvaluationByContextId} with empty permissions and granted access\n */\nconst createEmptyPermissionsResult = (contextIds: string[]): PermissionsEvaluationByContextId => Object.fromEntries(\n contextIds.map((contextId) => [\n contextId,\n { permissions: [], hasRequiredPermissions: true },\n ]),\n);\n\n/**\n * Checks if permission requirements are met across all contexts\n * @param permissionsEvaluationByContextId - {@link PermissionsEvaluationByContextId} Permission evaluation results by context\n * @param requireAll - Whether all contexts must satisfy requirements (true) or just one (false)\n * @returns true if requirements are met\n */\nexport const checkAuthorizeRequirements = (permissionsEvaluationByContextId: PermissionsEvaluationByContextId, requireAll: boolean): boolean => {\n const permissionsEvaluationValues = Object.values(permissionsEvaluationByContextId);\n\n if (requireAll) {\n return permissionsEvaluationValues.every((evaluation) => evaluation.hasRequiredPermissions);\n }\n return permissionsEvaluationValues.some((evaluation) => evaluation.hasRequiredPermissions);\n};\n\nexport const formatResultsWithOrOperator = (\n contextsPermissionsEvaluations: PermissionsEvaluationByContextId,\n requiredPermissions: string[],\n): PermissionsEvaluationByContextId => {\n const permissionsEvaluationByContextId: PermissionsEvaluationByContextId = {};\n Object.entries(contextsPermissionsEvaluations).forEach(([contextId, evaluation]) => {\n const permissions = evaluation?.permissions || [];\n const hasRequiredPermissions = evaluatePermissionsByOperator(\n permissions,\n requiredPermissions,\n PERMISSIONS_EVALUATION_OPERATORS.OR,\n );\n\n permissionsEvaluationByContextId[contextId] = {\n permissions,\n hasRequiredPermissions,\n };\n });\n\n return permissionsEvaluationByContextId;\n};\n\n/**\n * Resolves permissions from Identity Service API\n * @param params - {@link ResolvePermissionsParams}\n * @returns {@link PermissionsEvaluationByContextId} Permission evaluation results by context ID\n */\nexport const resolvePermissions = async ({\n user,\n contextIds,\n requiredPermissions,\n options,\n}: ResolvePermissionsParams): Promise<PermissionsEvaluationByContextId> => {\n if (!requiredPermissions?.length) {\n return createEmptyPermissionsResult(contextIds);\n }\n\n const response = await IdentityNetwork.post('/api/v1/permissions/resolve', {\n userId: user.id,\n contextIds,\n requiredPermissions,\n }, {\n timeout: options.timeout,\n });\n\n const data: PermissionsEvaluationByContextId = response?.data || {};\n\n if (!Object.keys(data || {}).length) {\n throw new Error('Failed to resolve permissions');\n }\n\n if (options.permissionsEvaluationOperator === PERMISSIONS_EVALUATION_OPERATORS.AND) {\n return data;\n }\n\n // Re-evaluate with OR operator\n return formatResultsWithOrOperator(data, requiredPermissions);\n};\n\nconst validateInput = (contextIds: string[]): string[] => {\n const errors: string[] = [];\n\n if (!contextIds?.length) {\n errors.push('contextIds cannot be empty');\n }\n\n return errors;\n};\n\nconst createErrorResult = (\n error: PermissionErrorType,\n requiredPermissions: string[],\n contextIds: string[],\n message?: string,\n): PermissionCheckResult => ({\n isAuthorized: false,\n error,\n resolvedPermissions: {},\n requiredPermissions,\n contextIds,\n ...(message && { message }),\n});\n\n/**\n * Caches permission results based on whether they meet requirements\n * - Caches granted permissions directly\n * - Groups denied permissions by identical sets to optimize cache storage\n * @param userId - User ID\n * @param resolvedPermissions - Permissions evaluation results to cache\n * @param requiredPermissions - Required permissions used for evaluation\n * @returns Promise that resolves when caching is complete\n */\nconst cachePermissionsResults = async (\n userId: string,\n resolvedPermissions: PermissionsEvaluationByContextId,\n requiredPermissions: string[],\n logger?: Logger,\n): Promise<void> => {\n const permissionsToCache: PermissionsByContextId = {};\n const deniedPermissionsMap = new Map<string, string[]>();\n\n logger?.debug('Start caching permissions results', {\n userId,\n resolvedPermissions,\n requiredPermissions,\n });\n\n Object.entries(resolvedPermissions).forEach(([contextId, evaluation]) => {\n if (evaluation?.permissions) {\n const userPermissionsSet = new Set(evaluation.permissions);\n const effectivePermissions = requiredPermissions.filter((permission) => userPermissionsSet.has(permission));\n const deniedPermissions = requiredPermissions.filter((permission) => !userPermissionsSet.has(permission));\n\n if (effectivePermissions.length) {\n // Store only effective permissions (intersection of user and required permissions)\n permissionsToCache[contextId] = effectivePermissions;\n }\n\n if (deniedPermissions.length) {\n // Calculate which required permissions were denied by filtering out the ones the user has\n const deniedPermissionsKey = deniedPermissions.sort().join(',');\n\n if (!deniedPermissionsMap.has(deniedPermissionsKey)) {\n deniedPermissionsMap.set(deniedPermissionsKey, []);\n }\n deniedPermissionsMap.get(deniedPermissionsKey)!.push(contextId);\n }\n }\n });\n\n if (Object.keys(permissionsToCache).length > 0) {\n const pastCache = await permissionCache.getUserPermissions(userId, Object.keys(permissionsToCache));\n\n Object.keys(pastCache ?? {}).forEach((contextId) => {\n if (permissionsToCache[contextId]) {\n // Merge with any previously cached permissions to avoid overwriting\n const mergedPermissions = Array.from(new Set([...(pastCache[contextId] || []), ...permissionsToCache[contextId]]));\n permissionsToCache[contextId] = mergedPermissions;\n }\n });\n\n logger?.debug('Caching granted permissions', { userId, permissionsToCache, pastCache });\n const { success } = await permissionCache.setUserPermissions(userId, permissionsToCache);\n if (!success) {\n logger?.error('Failed to cache granted permissions', { userId, permissionsToCache });\n }\n }\n\n // Cache denied permissions grouped by the same denied permissions to utilize mset efficiently\n const deniedPermissionsCachePromises = Array.from(deniedPermissionsMap.entries()).map(([deniedPermissionsKey, contextIds]) => {\n const deniedPermissions = deniedPermissionsKey.split(',');\n return permissionCache.setCachedDeniedPermissions(userId, contextIds, deniedPermissions);\n });\n\n logger?.debug('Caching denied permissions', {\n userId,\n deniedPermissionsGroups: Array.from(deniedPermissionsMap.entries()).map(([key, contexts]) => ({\n deniedPermissions: key.split(','),\n contextIds: contexts,\n })),\n });\n await Promise.all(deniedPermissionsCachePromises);\n};\n\n/**\n * Determines if a context can be resolved from denied permissions cache\n * @param deniedPermissions - Previously denied permissions for the context\n * @param requiredPermissions - Currently required permissions\n * @param operator - Evaluation operator (AND/OR)\n * @returns Object indicating if context is resolvable from cache and the result\n */\nconst isResolvableFromDeniedCache = (\n deniedPermissions: string[],\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): { isResolvableFromCache: boolean; hasRequiredPermissions: boolean } => {\n if (!deniedPermissions.length) {\n return { isResolvableFromCache: false, hasRequiredPermissions: false };\n }\n\n const deniedSet = new Set(deniedPermissions);\n const deniedRequiredPermissions = requiredPermissions.filter((permission) => deniedSet.has(permission));\n\n if (operator === PERMISSIONS_EVALUATION_OPERATORS.AND) {\n // For AND: if any required permission was denied, we can resolve as false\n return {\n isResolvableFromCache: deniedRequiredPermissions.length > 0,\n hasRequiredPermissions: false,\n };\n }\n\n // For OR: only if ALL required permissions were denied, we can resolve as false\n return {\n isResolvableFromCache: deniedRequiredPermissions.length === requiredPermissions.length,\n hasRequiredPermissions: false,\n };\n};\n\n/**\n * Gets contexts that need API calls (unseen + partially resolvable seen contexts)\n * @param unseenContextIds - Context IDs that have no cached data\n * @param deniedContextIds - Context IDs that have cached denied permissions\n * @param deniedContextEntries - Context IDs that were fully resolved from cache\n * @returns Array of context IDs that need API calls\n */\nconst getContextsNeedingAPI = (\n unseenContextIds: string[],\n deniedContextIds: string[],\n deniedContextEntries: PermissionsEvaluationByContextId,\n): string[] => {\n const contextIdsNeedingAPI = [...unseenContextIds];\n\n // Add denied contexts that couldn't be resolved from cache\n const unresolvedDeniedContextIds = deniedContextIds.filter((contextId) => !deniedContextEntries[contextId]);\n contextIdsNeedingAPI.push(...unresolvedDeniedContextIds);\n\n return contextIdsNeedingAPI;\n};\n\n/**\n * Processes denied contexts that can be resolved from denied permissions cache\n * @param deniedContextIds - Context IDs that have cached denied permissions\n * @param deniedPermissions - Denied permissions cache data\n * @param requiredPermissions - Currently required permissions\n * @param operator - Evaluation operator (AND/OR)\n * @returns Object with cache-resolvable contexts and their evaluations\n */\nconst processCachedDeniedContexts = (\n deniedContextIds: string[],\n seenPermissions: Record<string, string[]>,\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): PermissionsEvaluationByContextId => {\n const result: PermissionsEvaluationByContextId = {};\n\n deniedContextIds.forEach((contextId) => {\n const deniedPermissions = seenPermissions[contextId];\n const cacheResult = isResolvableFromDeniedCache(deniedPermissions, requiredPermissions, operator);\n\n if (cacheResult.isResolvableFromCache) {\n result[contextId] = {\n permissions: [],\n hasRequiredPermissions: cacheResult.hasRequiredPermissions,\n };\n }\n });\n\n return result;\n};\n\n/**\n * Processes cached permissions into evaluation format\n * @param cachedPermissions - Raw permissions from cache\n * @param requiredPermissions - Required permissions to evaluate against\n * @param operator - Evaluation operator (AND/OR)\n * @returns Processed permissions evaluation\n */\nconst processCachedPermissions = (\n cachedPermissions: Record<string, string[]>,\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): PermissionsEvaluationByContextId => {\n const processedPermissions: PermissionsEvaluationByContextId = {};\n\n if (Object.keys(cachedPermissions || {}).length) {\n Object.entries(cachedPermissions).forEach(([contextId, permissions]) => {\n const hasRequiredPermissions = evaluatePermissionsByOperator(\n permissions,\n requiredPermissions,\n operator,\n );\n\n // Only include contexts that can be fully resolved from cache\n // Since we only cache effective permissions we won't have all of the user's permissions to fully resolve\n if (hasRequiredPermissions) {\n processedPermissions[contextId] = {\n permissions,\n hasRequiredPermissions,\n };\n }\n });\n }\n\n return processedPermissions;\n};\n\n/**\n * Calls the Identity API to resolve permissions for unseen contexts\n * @param userId - User ID\n * @param contextIds - Context IDs to resolve\n * @param requiredPermissions - Required permissions\n * @param options - API call options\n * @returns Resolved permissions from API\n */\nconst callIdentityAPI = async (\n userId: string,\n contextIds: string[],\n requiredPermissions: string[],\n options: { permissionsEvaluationOperator: PermissionsEvaluationOperator; timeout: number },\n): Promise<PermissionsEvaluationByContextId> => {\n const response = await IdentityNetwork.post('/api/v1/permissions/resolve', {\n userId,\n contextIds,\n requiredPermissions,\n }, {\n timeout: options.timeout,\n });\n\n const data: PermissionsEvaluationByContextId = response?.data || {};\n\n if (!Object.keys(data || {}).length) {\n throw new Error('Failed to resolve permissions');\n }\n\n // If using AND operator, return data as-is. For OR, re-evaluate.\n if (options.permissionsEvaluationOperator === PERMISSIONS_EVALUATION_OPERATORS.AND) {\n return data;\n }\n\n // Re-evaluate with OR operator\n const reEvaluatedPermissions: PermissionsEvaluationByContextId = {};\n Object.entries(data).forEach(([contextId, evaluation]) => {\n const permissions = evaluation?.permissions || [];\n const hasRequiredPermissions = evaluatePermissionsByOperator(\n permissions,\n requiredPermissions,\n options.permissionsEvaluationOperator,\n );\n\n reEvaluatedPermissions[contextId] = {\n permissions,\n hasRequiredPermissions,\n };\n });\n\n return reEvaluatedPermissions;\n};\n\n/**\n * Validates user context and required permissions for evaluation\n * @param contextIds - Context IDs to validate\n * @param requiredPermissions - Required permissions to validate\n * @param userId - User ID to validate\n * @param logger - Logger instance for warnings\n * @returns Error result if validation fails, null if validation passes\n */\nconst validateEvaluationInput = (\n contextIds: string[],\n requiredPermissions: string[],\n userId: string | null,\n logger?: Logger,\n): PermissionCheckResult | null => {\n const validationErrors = validateInput(contextIds);\n if (validationErrors.length) {\n return createErrorResult(PERMISSION_ERROR_TYPES.VALIDATION_ERROR, requiredPermissions, contextIds, validationErrors.join(', '));\n }\n\n if (!userId) {\n logger?.warn('User not found in context, cannot check permissions', {\n contextIds,\n requiredPermissions,\n });\n return createErrorResult(PERMISSION_ERROR_TYPES.USER_NOT_FOUND, requiredPermissions, contextIds);\n }\n\n if (!requiredPermissions?.length) {\n logger?.info('No requiredPermissions provided', {\n userId,\n contextIds,\n });\n return {\n isAuthorized: false,\n userId,\n resolvedPermissions: {},\n requiredPermissions,\n contextIds,\n error: PERMISSION_ERROR_TYPES.NO_REQUIRED_PERMISSIONS,\n };\n }\n\n return null;\n};\n\n/**\n * Resolves permissions from Identity API and combines with existing resolved permissions\n * @param userId - User ID\n * @param contextIdsNeedingAPI - Context IDs that need API resolution\n * @param requiredPermissions - Required permissions to check\n * @param options - API call options {@link ResolvePermissionsParams}\n * @param resolvedPermissions - Already resolved permissions from cache and denied cache\n * @returns Combined permissions including those resolved from API\n */\nconst resolvePermissionsFromAPI = async (\n userId: string,\n contextIdsNeedingAPI: string[],\n requiredPermissions: string[],\n options: { permissionsEvaluationOperator: PermissionsEvaluationOperator; timeout: number },\n resolvedPermissions: PermissionsEvaluationByContextId,\n): Promise<PermissionsEvaluationByContextId> => {\n let newResolvedPermissions: PermissionsEvaluationByContextId = { ...resolvedPermissions };\n // Call Identity API for unresolved contexts\n const resolvedPermissionsFromIdentityMS = await callIdentityAPI(\n userId,\n contextIdsNeedingAPI,\n requiredPermissions,\n options,\n );\n\n // Combine all resolved permissions\n newResolvedPermissions = {\n ...resolvedPermissions,\n ...resolvedPermissionsFromIdentityMS,\n };\n\n await cachePermissionsResults(userId, resolvedPermissionsFromIdentityMS, requiredPermissions);\n\n return newResolvedPermissions;\n};\n\n/**\n * Resolves permissions from multiple sources (cache, seen contexts, API)\n * @param userId - User ID\n * @param contextIds - Context IDs to resolve permissions for\n * @param requiredPermissions - Required permissions to check\n * @param options - Evaluation options\n * @returns Combined permissions from all sources: cache, denied cache, and API\n */\nconst resolveAllPermissions = async (\n userId: string,\n contextIds: string[],\n requiredPermissions: string[],\n options: {\n permissionsEvaluationOperator: PermissionsEvaluationOperator,\n timeout: number,\n logger?: Logger,\n },\n): Promise<PermissionsEvaluationByContextId> => {\n const { logger } = options;\n // Cached allowed permissions\n const cachedAllowedPermissions = await permissionCache.getUserPermissions(userId, contextIds);\n const resolvedPermissionsFromCache = processCachedPermissions(\n cachedAllowedPermissions,\n requiredPermissions,\n options.permissionsEvaluationOperator,\n );\n let resolvedPermissions = { ...resolvedPermissionsFromCache };\n\n // Context ids without allowed permissions in cache\n const contextIdsWithoutAllowedCache = contextIds.filter((contextId) => !resolvedPermissionsFromCache[contextId]);\n\n // Handle denied cache permissions\n const cachedDeniedPermissions = await permissionCache.getCachedDeniedPermissions(userId, contextIdsWithoutAllowedCache);\n\n // Context ids that have never been seen before (not in allowed or denied cache)\n const unseenContextIds = contextIdsWithoutAllowedCache.filter((contextId) => !cachedDeniedPermissions[contextId]);\n\n // Process denied permissions cache\n const deniedContextIds = contextIdsWithoutAllowedCache.filter((contextId) => cachedDeniedPermissions[contextId]);\n const deniedContextEntries = processCachedDeniedContexts(\n deniedContextIds,\n cachedDeniedPermissions,\n requiredPermissions,\n options.permissionsEvaluationOperator,\n );\n\n // Combine resolved permissions with those resolved from denied cache\n resolvedPermissions = { ...resolvedPermissions, ...deniedContextEntries };\n\n // Resolve the remaining contexts using the Identity API\n const contextIdsNeedingAPI = getContextsNeedingAPI(unseenContextIds, deniedContextIds, deniedContextEntries);\n if (contextIdsNeedingAPI.length) {\n // Call Identity API for unresolved contexts\n return resolvePermissionsFromAPI(\n userId,\n contextIdsNeedingAPI,\n requiredPermissions,\n options,\n resolvedPermissions,\n );\n }\n\n logger?.debug('Final resolved permissions', {\n userId,\n requiredPermissions,\n resolvedPermissions,\n });\n\n return resolvedPermissions;\n};\n\n/**\n * Main SDK function to evaluate user permissions\n * Checks both cached and API-resolved permissions to determine access\n * @param params - {@link EvaluatePermissionsParams}\n * @returns {@link PermissionCheckResult} Detailed permission check result with access status and context\n */\nexport const evaluatePermissions = async ({\n requiredPermissions,\n contextIds,\n logger,\n userId,\n options: {\n requireAll = true,\n permissionsEvaluationOperator = PERMISSIONS_EVALUATION_OPERATORS.AND,\n timeout = 10000,\n },\n}: EvaluatePermissionsParams): Promise<PermissionCheckResult> => {\n const resolvedUserId = userId || getUser()?.id || null;\n\n const validationError = validateEvaluationInput(contextIds, requiredPermissions, resolvedUserId, logger);\n if (validationError) {\n return validationError;\n }\n\n const resolvedPermissions = await resolveAllPermissions(\n resolvedUserId!,\n contextIds,\n requiredPermissions,\n { permissionsEvaluationOperator, timeout, logger },\n );\n\n const isAuthorized = checkAuthorizeRequirements(resolvedPermissions, requireAll);\n\n logger?.info('Resolved permissions', {\n userId: resolvedUserId,\n requiredPermissions,\n resolvedPermissions,\n isAuthorized,\n requireAll,\n permissionsEvaluationOperator,\n contextIds,\n });\n\n return {\n isAuthorized,\n userId: resolvedUserId!,\n resolvedPermissions,\n requiredPermissions,\n contextIds,\n ...(isAuthorized ? {} : { error: PERMISSION_ERROR_TYPES.INSUFFICIENT_PERMISSIONS }),\n };\n};\n\nexport default evaluatePermissions;\n","import type { Request, Response, NextFunction } from 'express';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentContext, newTrace, traceTypes } from '@autofleet/outbreak';\nimport { evaluatePermissions } from '../SDK/evaluatePermissions';\nimport type { EvaluatePermissionsOpts, Logger } from '../SDK/types';\nimport ApiUser, { CONTEXTS_IDS_HEADER } from '../../user/ApiUser';\nimport { PERMISSION_ERROR_MESSAGES, PERMISSION_ERROR_TYPES, PERMISSIONS_EVALUATION_OPERATORS } from '../SDK/consts';\nimport { decodeBearer } from '../../utils';\nimport { IdentityNetwork } from '../../services';\nimport { USER_OBJECT } from '../../user/const';\nimport { getUser } from '../../check-permission';\n\nexport interface RequirePermissionsOptions extends EvaluatePermissionsOpts {\n logger?: LoggerInstanceManager;\n}\n\nconst getContextIds = (req: Request, logger?: Logger): string[] => {\n logger?.debug('Extracting context IDs from request', {\n headers: req.headers,\n query: req.query,\n body: req.body,\n });\n\n const contextIdsFromHeader = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',') || [];\n const contextFromAFContextHeader = req.headers?.['af-context'] ? [req.headers['af-context'] as string] : [];\n const contextIdsFromQuery = (req.query?.contextIds as string)?.split(',') || [];\n const contextIdFromQuery = (req.query?.contextId as string) ? [req.query.contextId as string] : [];\n const contextFromQuery = req.query?.context ? [req.query.context as string] : [];\n const contextIdsFromBody = (req.body?.contextIds as string[]) || [];\n const contextIdFromBody = (req.body?.contextId as string) ? [req.body.contextId as string] : [];\n\n return Array.from(new Set([\n ...contextIdsFromHeader,\n ...contextFromAFContextHeader,\n ...contextIdsFromQuery,\n ...contextIdFromQuery,\n ...contextFromQuery,\n ...contextIdsFromBody,\n ...contextIdFromBody,\n ])).filter(Boolean);\n};\n\nconst handleError = (\n errorLabel: string,\n message: string,\n code: number,\n enforce: boolean | undefined,\n res: Response,\n req: Request,\n next: NextFunction,\n logger?: LoggerInstanceManager,\n additionalInfo?: { requiredPermissions?: string[]; },\n) => {\n if (enforce) {\n logger?.error(message, {\n url: req.url,\n method: req.method,\n requiredPermissions: additionalInfo?.requiredPermissions || [],\n ...additionalInfo,\n });\n\n res.status(code).json({\n error: errorLabel,\n message,\n ...(additionalInfo?.requiredPermissions && { requiredPermissions: additionalInfo.requiredPermissions }),\n });\n return;\n }\n\n logger?.warn(message, {\n url: req.url,\n method: req.method,\n requiredPermissions: additionalInfo?.requiredPermissions || [],\n ...additionalInfo,\n });\n next();\n};\n\nconst createNewUserTrace = (userId: string, contextIds: string[], logger?: Logger) => {\n try {\n newTrace(traceTypes.HTTP_REQUEST);\n const apiUser = new ApiUser(userId, undefined, undefined, contextIds);\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, apiUser);\n } catch (error) {\n logger?.error('Error creating new user trace', { error, userId, contextIds });\n }\n};\n\nconst getUserContextsFromIdentity = async (userId: string, timeout?: number): Promise<string[]> => {\n try {\n const response = await IdentityNetwork.get(`/api/v1/users/${userId}/contexts`, { timeout });\n const contextIds = (response?.data || []).map((context: { id: string }) => context.id);\n\n createNewUserTrace(userId, contextIds);\n\n return contextIds;\n } catch (error) {\n return [];\n }\n};\n\n/**\n * Express middleware that requires specific permissions for route access\n *\n * @param requiredPermissions - Array of permissions required to access the route\n * @param options - Configuration options for permission checking\n * @returns Express middleware function\n */\nexport const requirePermissions = (\n requiredPermissions: string[],\n options: RequirePermissionsOptions = {\n enforce: false,\n requireAll: true,\n permissionsEvaluationOperator: PERMISSIONS_EVALUATION_OPERATORS.AND,\n },\n) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const {\n logger,\n enforce,\n requireAll,\n permissionsEvaluationOperator,\n } = options;\n\n const handleErrorWrapper = (errorLabel: string, message: string, code: number) => handleError(\n errorLabel,\n message,\n code,\n enforce,\n res,\n req,\n next,\n logger,\n { requiredPermissions },\n );\n\n let decodedToken: { user?: { id?: string } } | null = null;\n try {\n decodedToken = decodeBearer(req.headers.authorization || '');\n } catch { /* no-op */ }\n const user = getUser() || decodedToken?.user;\n if (!user?.id) {\n handleErrorWrapper(\n PERMISSION_ERROR_TYPES.UNAUTHORIZED,\n PERMISSION_ERROR_MESSAGES.UNAUTHORIZED,\n 401,\n );\n return;\n }\n\n const contextIdsFromRequest: string[] = getContextIds(req, logger);\n // If no context IDs are provided in the request, fetch them from the Identity service\n const contextIdsFromIdentity = !contextIdsFromRequest?.length ? await getUserContextsFromIdentity(user.id, options.timeout) : [];\n\n // Combine and remove deduplicate context IDs from request and identity service\n const contextIds = Array.from(new Set([...contextIdsFromRequest, ...contextIdsFromIdentity]));\n\n if (!contextIds?.length) {\n handleErrorWrapper(\n PERMISSION_ERROR_TYPES.BAD_REQUEST,\n PERMISSION_ERROR_MESSAGES.BAD_REQUEST,\n 400,\n );\n return;\n }\n\n // Evaluate permissions using SDK\n const result = await evaluatePermissions({\n requiredPermissions,\n contextIds,\n logger,\n userId: user.id,\n options: {\n requireAll: requireAll ?? true,\n permissionsEvaluationOperator: permissionsEvaluationOperator ?? PERMISSIONS_EVALUATION_OPERATORS.AND,\n timeout: 10000,\n ...(logger && { logger }),\n },\n });\n\n if (result.isAuthorized) {\n logger?.info('User has required permissions', {\n userId: user.id,\n requiredPermissions,\n contextIds,\n url: req.url,\n method: req.method,\n });\n next();\n return;\n }\n\n if (!enforce) {\n logger?.warn('User does not have required permissions, skipping enforcement', {\n userId: user.id,\n requiredPermissions,\n contextIds,\n url: req.url,\n method: req.method,\n });\n next();\n return;\n }\n\n res.status(403).json({\n error: PERMISSION_ERROR_TYPES.INSUFFICIENT_PERMISSIONS,\n message: PERMISSION_ERROR_MESSAGES.INSUFFICIENT_PERMISSIONS,\n required: requiredPermissions,\n contexts: contextIds,\n userId: result.userId,\n });\n } catch (error) {\n const requestLogger = options.logger;\n requestLogger?.error('Error in requirePermissions middleware', {\n error,\n requiredPermissions,\n url: req.url,\n method: req.method,\n });\n\n if (!options.enforce) {\n options.logger?.error('Error during permission check, skipping enforcement', {\n error,\n url: req.url,\n method: req.method,\n });\n next();\n return;\n }\n\n res.status(500).json({\n error: PERMISSION_ERROR_TYPES.INTERNAL_ERROR,\n message: PERMISSION_ERROR_MESSAGES.INTERNAL_ERROR,\n });\n }\n};\n\nexport default requirePermissions;\n","import { evaluatePermissions } from './SDK/evaluatePermissions';\nimport { requirePermissions } from './middleware/requirePermissions';\n\ninterface SdkExports {\n evaluatePermissions: typeof evaluatePermissions;\n}\n\ninterface MiddlewareExports {\n requirePermissions: typeof requirePermissions;\n}\n\ninterface PermissionsModule {\n sdk: SdkExports;\n middlewares: MiddlewareExports;\n}\n\nexport const sdk: SdkExports = {\n evaluatePermissions,\n};\n\nexport const middlewares: MiddlewareExports = {\n requirePermissions,\n};\n\nexport default {\n sdk,\n middlewares,\n} as PermissionsModule;\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';\nimport * as permissions from './permissions';\n\nconst getCurrentPayload: typeof outbreak.getCurrentContext = 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\n/* eslint-disable prefer-destructuring */\nconst traceTypes: typeof outbreak.traceTypes = outbreak.traceTypes;\nconst newTrace: typeof outbreak.newTrace = outbreak.newTrace;\n/* eslint-enable prefer-destructuring */\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 permissions,\n};\n\ninterface Default {\n traceTypes: typeof outbreak.traceTypes;\n newTrace: typeof outbreak.newTrace;\n User: typeof User;\n middleware: typeof middleware;\n middlewareWithDecode: typeof middlewareWithDecode;\n eagerLoadPermissionsMiddleware: typeof eagerLoadPermissionsMiddleware;\n getCurrentPayload: typeof outbreak.getCurrentContext;\n getDecodedBearer: typeof getDecodedBearer;\n checkFleetPermission: typeof checkFleetPermission;\n checkBusinessModelPermission: typeof checkBusinessModelPermission;\n checkDemandSourcePermission: typeof checkDemandSourcePermission;\n isUserExist: typeof isUserExist;\n getUser: typeof getUser;\n UnauthorizedAccessError: typeof UnauthorizedAccessError;\n appMiddleware: typeof appMiddleware;\n createOrSetRabbitTrace: typeof createOrSetRabbitTrace;\n outbreak: typeof outbreak;\n AUTHORIZATION_METHODS: typeof AUTHORIZATION_METHODS;\n getAuthorizationHeader: typeof getAuthorizationHeader;\n CONTEXTS_IDS_HEADER: typeof CONTEXTS_IDS_HEADER;\n authFromUserIdHeaderPlugin: typeof authFromUserIdHeaderPlugin;\n permissions: typeof permissions;\n}\n\nconst zehutDefault: 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 permissions,\n};\n\nexport default zehutDefault;\n"],"mappings":"oTAGA,KAAM,CACJ,wBAAuB,iBACvB,gCAA+B,qB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ACA,uBACA,+BACA,8BACA,cACA,UACA,0BACA,gBACA,yBACA,WACA,wBACA,yBACA,sBACA,6BACA,YAAA,EACD"}
1
+ {"version":3,"file":"index.js","names":["unixTime: moment.Moment","IdentityNetwork: Network","AutofleetApiNetwork: Network","permissions: UserPayload","id?: string","accountType?: AccountType | undefined","contextIds?: string[]","eagerLoadPermissionsMiddleware: Asyncify<Handler>","newTrace","traceTypes","authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions>","user: ApiUser | null","result: EntityPermissions","result: Record<string, string[]>","permissionCache: PermissionCache","errors: string[]","permissionsToCache: PermissionsByContextId","result: PermissionsEvaluationByContextId","processedPermissions: PermissionsEvaluationByContextId","data: PermissionsEvaluationByContextId","reEvaluatedPermissions: PermissionsEvaluationByContextId","newResolvedPermissions: PermissionsEvaluationByContextId","traceTypes","decodedToken: { user?: { id?: string; }; } | null","contextIdsFromRequest: string[]","sdk: SdkExports","middlewares: MiddlewareExports","getCurrentPayload: typeof outbreak.getCurrentContext","traceTypes: typeof outbreak.traceTypes","newTrace: typeof outbreak.newTrace","zehutDefault: Default"],"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/permissions/SDK/permissionCache.ts","../src/permissions/SDK/consts.ts","../src/permissions/SDK/evaluatePermissions.ts","../src/permissions/middleware/requirePermissions.ts","../src/permissions/index.ts","../src/index.ts"],"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 {\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 jwt from 'jsonwebtoken';\nimport { getTokenSecret } from './secret-getter';\n\ntype Context = Partial<Record<ContextProp | 'id', string>> & { subSystem?: SubSystemType; permissions?: string[]; entityId: string; };\n\nconst CONTEXT_PROPS = ['fleetId', 'businessModelId', 'demandSourceId'] as const;\ntype ContextProp = typeof CONTEXT_PROPS[number];\nconst CONTEXT_MAP_PROPS = {\n fleet: 'fleets',\n business: 'businessModels',\n demand: 'demandSources',\n} as const;\ntype SubSystemType = keyof typeof CONTEXT_MAP_PROPS;\ntype ContextSubSystemProp = typeof CONTEXT_MAP_PROPS[SubSystemType];\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: string, decodedToken: { contexts: Context[]; }): { key: string; value: string; } | undefined => {\n if (!decodedToken) return undefined;\n const { contexts } = decodedToken;\n const activeContext = contexts.find(context => context.id === contextId);\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const permissionsValue = `${activeContext!.permissions?.map(cp => `${cp},`)}`;\n\n return {\n key: activeContext!.entityId,\n value: permissionsValue,\n };\n};\n\ntype EntitiesFromContext = Partial<Record<ContextSubSystemProp, Record<string, string>>>;\nexport const getEntitiesFromContext = (contextId: string | undefined, decodedToken: { contexts: Context[]; }): EntitiesFromContext => {\n if (!decodedToken) return {};\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter(context => context.id === contextId);\n }\n\n const attributes: EntitiesFromContext = {};\n contexts.forEach((context) => {\n const prop = CONTEXT_MAP_PROPS[context.subSystem || 'business'];\n\n const permissions = parsePermissions(context.id!, decodedToken);\n if (!permissions) return;\n attributes[prop] ??= {};\n attributes[prop][permissions.key] = permissions.value;\n });\n\n return attributes;\n};\n\ntype ContextAttributes = Partial<Record<ContextProp, string[]>>;\nexport const getContextAttributes = (contextId: string | undefined, decodedToken: { contexts: Context[]; }): ContextAttributes => {\n if (!decodedToken) return {};\n let { contexts } = decodedToken;\n if (contextId) {\n contexts = contexts.filter(context => context.id === contextId);\n }\n const attributes: ContextAttributes = {};\n contexts.forEach((context) => {\n CONTEXT_PROPS.forEach((prop) => {\n if (context[prop]) {\n attributes[prop] ??= [];\n attributes[prop].push(context[prop]);\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\nexport const IdentityNetwork: Network = 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: Network = 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';\ntype EntityPermissions = Record<string, string[]>;\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 | undefined, sources: Iterable<PartialUserPayload | undefined>): 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 for (const source of sources) {\n (Object.entries(source ?? {}) as [Exclude<keyof UserPayload, 'accountType' | 'createdAt'>, EntityPermissions][]).forEach(([entityType, entityValue]) => {\n permissions[entityType] ??= {};\n Object.entries(entityValue).forEach(([entityId, perms]) => {\n permissions[entityType]![entityId] = (permissions[entityType]![entityId] || []).concat(perms);\n });\n });\n }\n\n return permissions;\n};\n\nif (typeof Symbol.dispose !== 'symbol') {\n // Polyfill for dispose if it does not exist, based on https://github.com/nodejs/node/blob/9a9409ff1f45c968173118de4cd37dea784f8ec9/lib/internal/process/pre_execution.js#L163-L171\n Object.defineProperty(Symbol, 'dispose', {\n // @ts-expect-error: TypeScript does not recognize __proto__ as a valid property\n __proto__: null,\n configurable: false,\n enumerable: false,\n value: Symbol.for('nodejs.dispose'),\n writable: false,\n });\n}\nif (typeof Symbol.asyncDispose !== 'symbol') {\n // Polyfill for asyncDispose if it does not exist, based on https://github.com/nodejs/node/blob/9a9409ff1f45c968173118de4cd37dea784f8ec9/lib/internal/process/pre_execution.js#L174-L183\n Object.defineProperty(Symbol, 'asyncDispose', {\n // @ts-expect-error: TypeScript does not recognize __proto__ as a valid property\n __proto__: null,\n configurable: false,\n enumerable: false,\n value: Symbol.for('nodejs.asyncDispose'),\n writable: false,\n });\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: Record<string, any> = {};\n\n public readonly emptyUser: boolean;\n\n constructor(public id?: string, public accountType?: AccountType | undefined, 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[] {\n return this.getUserProperty('businessModels');\n }\n\n public get fleets(): string[] {\n return this.getUserProperty('fleets');\n }\n\n public get demandSources(): string[] {\n return this.getUserProperty('demandSources');\n }\n\n private getUserProperty(key: keyof UserPayload): string[] {\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) & { [Symbol.dispose]: () => void; } {\n // @itayankri is concerned about memory consumption, so create a symbol with no description, to avoid assigning memory for the description string\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?.get(ELEVATED_PERMISSIONS_HEADER) as string | undefined || '{}');\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 const cleanup = () => {\n this.privateElevatedPermissionsHash.delete(elevationId);\n currentUserTrace.context.set(ELEVATED_PERMISSIONS_HEADER, JSON.stringify(this.elevatedPermissions));\n };\n cleanup[Symbol.dispose] = cleanup;\n return cleanup;\n }\n\n public async getUserPermissionsLegacy(): Promise<unknown> {\n if (!this.id) {\n return undefined;\n }\n if (this.privatePermissionsLegacy) {\n return this.privatePermissionsLegacy;\n }\n\n const cacheKey = objectHash({\n id: this.id,\n contextIds: this.contextIds,\n legacy: true,\n });\n let data = userCache.get(cacheKey);\n\n if (!data) {\n ({ data } = await IdentityNetwork.get(`/api/v1/users/${this.id}/authorization-payload-legacy`, { params: { contextIds: this.contextIds } }));\n userCache.set(cacheKey, data);\n }\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: string, clientSecret: string): Promise<UserPayload | undefined> {\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() as Lowercase<typeof ORIGIN_HEADER>;\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 elevatedPermHeaderValue = headers[ELEVATED_PERMISSIONS_HEADER];\n const elevatedPermissionsFromHeader = elevatedPermHeaderValue?.length && elevatedPermHeaderValue.length > 0 ? JSON.parse(elevatedPermHeaderValue 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, type AuthFromUserIdHeaderOptions } from './common';\n\ndeclare module 'express-serve-static-core' {\n interface Request {\n user: ApiUser;\n }\n}\n\ntype Asyncify<T extends (...a: any[]) => any> = (...a: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n\nexport const middleware = (options: AuthFromUserIdHeaderOptions = {}): Asyncify<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 {\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} = {}): Asyncify<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}): Asyncify<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 as Error).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: Asyncify<Handler> = async (req, res, next) => {\n await req.user.getUserPermissions();\n next();\n};\n\nexport const getDecodedBearer = (req: Request): any => {\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): Promise<void> => {\n const userObject = new ApiUser(userId);\n\n await userObject.getUserPermissions();\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 { type AuthFromUserIdHeaderOptions, authFromUserIdHeader } from './common';\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n user?: ApiUser;\n }\n}\n\nexport const authFromUserIdHeaderPlugin: FastifyPluginCallback<AuthFromUserIdHeaderOptions> = (fastify, options, done) => {\n fastify.decorateRequest('user', undefined);\n fastify.addHook('onRequest', async (request, reply) => {\n try {\n const user = await authFromUserIdHeader(options, request.headers);\n if (user) {\n request.user = user;\n }\n } catch {\n reply.status(401).send({ error: 'cannot authenticate user' });\n }\n });\n\n done();\n};\nObject.defineProperty(authFromUserIdHeaderPlugin, Symbol.for('skip-override'), { value: true }); // Prevent Fastify from overriding the plugin\n","import { getCurrentContext } from '@autofleet/outbreak';\nimport { USER_OBJECT } from './user/const';\nimport type ApiUser from './user/ApiUser';\nimport type { UserPayload } from './user/ApiUser';\n\nexport const getUser = (): ApiUser | undefined => getCurrentContext().nonHeaderContext?.get(USER_OBJECT) as ApiUser | undefined;\n\nexport const isUserExist = (): string | undefined => 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): boolean => checkUserPermissions(fleetId, 'fleets');\nexport const checkBusinessModelPermission = (businessModelId: string): boolean => checkUserPermissions(businessModelId, 'businessModels');\nexport const checkDemandSourcePermission = (demandSourceId: string): boolean => checkUserPermissions(demandSourceId, 'demandSources');\n","import type ApiUser from './user';\n\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 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 NodeCache from 'node-cache';\n\ntype EntityPermissions = Record<string, string[]>;\n\nexport class PermissionCache {\n private cache: NodeCache;\n\n private ttl = 10;\n\n /**\n * Creates a new PermissionCache instance\n * @param cache - Optional NodeCache instance. If not provided, creates a new one with default TTL of 10 seconds\n */\n constructor(cache?: NodeCache, ttl?: number) {\n if (ttl) {\n this.ttl = ttl;\n }\n this.cache = cache ?? new NodeCache({ stdTTL: this.ttl });\n }\n\n private static getCacheKeys(cacheName: string, userId: string, contextIds: string[]) {\n const baseCacheKey = `${cacheName}-${userId}`;\n const cacheKeys = contextIds.map(contextId => `${baseCacheKey}-${contextId}`);\n\n return { baseCacheKey, cacheKeys };\n }\n\n /**\n * Retrieves user permissions for multiple contexts from cache\n * @param userId - The user identifier\n * @param contextIds - Array of context identifiers to fetch permissions for\n * @returns An object mapping context IDs to permission arrays\n */\n public getUserPermissions(userId: string, contextIds: string[]): EntityPermissions {\n try {\n const { baseCacheKey, cacheKeys } = PermissionCache.getCacheKeys('perm', userId, contextIds);\n const cacheResult = this.cache.mget(cacheKeys) as Record<string, string[]>;\n\n const result: EntityPermissions = {};\n Object.entries(cacheResult)\n .filter(([, permissions]) => permissions)\n .forEach(([key, permissions]) => {\n const contextId = key.replace(`${baseCacheKey}-`, '');\n result[contextId] = permissions;\n });\n\n return result;\n } catch {\n return {};\n }\n }\n\n /**\n * Stores user permissions for multiple contexts in cache\n * @param userId - The user identifier\n * @param PermissionsByContextId - Object mapping context IDs to permission arrays\n * @param ttl - Optional time to live in seconds. Defaults to 10 seconds\n * @returns An object indicating success/failure\n */\n public setUserPermissions(userId: string, PermissionsByContextId: EntityPermissions): { success: boolean; } {\n try {\n const cacheKey = (contextId: string) => `perm-${userId}-${contextId}`;\n\n const cacheEntries = Object.entries(PermissionsByContextId).map(([contextId, permissions]) => ({\n key: cacheKey(contextId),\n val: permissions,\n ttl: this.ttl,\n }));\n\n this.cache.mset(cacheEntries);\n\n return { success: true };\n } catch {\n return { success: false };\n }\n }\n\n /**\n * Retrieves denied permissions status for multiple contexts from cache.\n * \"Denied\" permissions indicate that a user has already been evaluated for a specific set of\n * required permissions in a given context, avoiding redundant permission checks.\n * @param userId - The user identifier\n * @param contextIds - Array of context identifiers to check\n * @returns An object mapping context IDs to arrays of denied permissions\n */\n public getCachedDeniedPermissions(userId: string, contextIds: string[]): Record<string, string[]> {\n try {\n const { baseCacheKey, cacheKeys } = PermissionCache.getCacheKeys('seen', userId, contextIds);\n const cacheResult = this.cache.mget(cacheKeys) as Record<string, string[]>;\n\n const result: Record<string, string[]> = {};\n Object.entries(cacheResult)\n .filter(([, permissions]) => permissions)\n .forEach(([key, permissions]) => {\n const contextId = key.replace(`${baseCacheKey}-`, '');\n result[contextId] = permissions;\n });\n\n return result;\n } catch {\n return {};\n }\n }\n\n /**\n * Marks permissions as seen for multiple contexts in cache.\n * \"Seen\" permissions are used to track that a user has already been evaluated for a specific\n * set of required permissions in given contexts, preventing duplicate permission evaluations.\n * @param userId - The user identifier\n * @param contextIds - Array of context identifiers to mark as seen\n * @param deniedPermissions - Array of permissions that were evaluated and denied\n * @param ttl - Optional time to live in seconds. Defaults to 10 seconds\n * @returns An object indicating success/failure\n */\n public setCachedDeniedPermissions(userId: string, contextIds: string[], deniedPermissions: string[]): { success: boolean; } {\n try {\n const seenKey = (contextId: string) => `seen-${userId}-${contextId}`;\n\n const cacheEntries = contextIds.map(contextId => ({\n key: seenKey(contextId),\n val: deniedPermissions,\n ttl: this.ttl,\n }));\n\n this.cache.mset(cacheEntries);\n\n return { success: true };\n } catch {\n return { success: false };\n }\n }\n}\n\nexport const permissionCache: PermissionCache = new PermissionCache();\n","export const PERMISSIONS_EVALUATION_OPERATORS = {\n AND: 'and',\n OR: 'or',\n};\n\nexport const PERMISSION_ERROR_TYPES = {\n USER_NOT_FOUND: 'USER_NOT_FOUND',\n INSUFFICIENT_PERMISSIONS: 'INSUFFICIENT_PERMISSIONS',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n API_ERROR: 'API_ERROR',\n NO_REQUIRED_PERMISSIONS: 'NO_REQUIRED_PERMISSIONS',\n UNAUTHORIZED: 'UNAUTHORIZED',\n BAD_REQUEST: 'BAD_REQUEST',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n};\n\nexport const PERMISSION_ERROR_MESSAGES = {\n USER_NOT_FOUND: 'User not found',\n INSUFFICIENT_PERMISSIONS: 'User does not have sufficient permissions',\n VALIDATION_ERROR: 'Validation error occurred',\n API_ERROR: 'API error occurred',\n NO_REQUIRED_PERMISSIONS: 'No required permissions provided for evaluation',\n UNAUTHORIZED: 'User is not authorized to perform this action',\n BAD_REQUEST: 'Bad request, please check the input parameters',\n INTERNAL_ERROR: 'Internal server error occurred while checking permissions',\n};\n","import { getUser } from '../../check-permission';\nimport { IdentityNetwork } from '../../services';\nimport type {\n PermissionsEvaluationOperator,\n EvaluatePermissionsParams,\n PermissionsEvaluationByContextId,\n PermissionCheckResult,\n ResolvePermissionsParams,\n Logger,\n PermissionsByContextId,\n} from './types';\nimport type { PermissionErrorType } from './errors';\nimport { permissionCache } from './permissionCache';\nimport { PERMISSIONS_EVALUATION_OPERATORS, PERMISSION_ERROR_TYPES } from './consts';\n\n/**\n * Evaluates whether user permissions meet requirements based on AND/OR operator\n * @param permissions - User's actual permissions\n * @param requiredPermissions - Required permissions to check against\n * @param operator - {@link PermissionsEvaluationOperator} AND (all required) or OR (at least one required)\n * @returns true if permissions meet requirements\n */\nconst evaluatePermissionsByOperator = (\n permissions: string[],\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): boolean => {\n const permissionsSet = new Set(permissions);\n const matchingPermissions = requiredPermissions.filter(permission => permissionsSet.has(permission));\n\n return operator === PERMISSIONS_EVALUATION_OPERATORS.AND\n ? matchingPermissions.length === requiredPermissions.length // All required permissions must be present\n : matchingPermissions.length > 0; // At least one required permission must be present\n};\n\n/**\n * Creates empty permissions result for cases with no required permissions\n * @param contextIds - Context IDs to create results for\n * @returns {@link PermissionsEvaluationByContextId} with empty permissions and granted access\n */\nconst createEmptyPermissionsResult = (contextIds: string[]): PermissionsEvaluationByContextId => Object.fromEntries(\n contextIds.map(contextId => [\n contextId,\n { permissions: [], hasRequiredPermissions: true },\n ]),\n);\n\n/**\n * Checks if permission requirements are met across all contexts\n * @param permissionsEvaluationByContextId - {@link PermissionsEvaluationByContextId} Permission evaluation results by context\n * @param requireAll - Whether all contexts must satisfy requirements (true) or just one (false)\n * @returns true if requirements are met\n */\nexport const checkAuthorizeRequirements = (permissionsEvaluationByContextId: PermissionsEvaluationByContextId, requireAll: boolean): boolean => {\n const permissionsEvaluationValues = Object.values(permissionsEvaluationByContextId);\n\n if (requireAll) {\n return permissionsEvaluationValues.every(evaluation => evaluation.hasRequiredPermissions);\n }\n return permissionsEvaluationValues.some(evaluation => evaluation.hasRequiredPermissions);\n};\n\nexport const formatResultsWithOrOperator = (\n contextsPermissionsEvaluations: PermissionsEvaluationByContextId,\n requiredPermissions: string[],\n): PermissionsEvaluationByContextId => {\n const permissionsEvaluationByContextId: PermissionsEvaluationByContextId = {};\n Object.entries(contextsPermissionsEvaluations).forEach(([contextId, evaluation]) => {\n const permissions = evaluation?.permissions || [];\n const hasRequiredPermissions = evaluatePermissionsByOperator(\n permissions,\n requiredPermissions,\n PERMISSIONS_EVALUATION_OPERATORS.OR,\n );\n\n permissionsEvaluationByContextId[contextId] = {\n permissions,\n hasRequiredPermissions,\n };\n });\n\n return permissionsEvaluationByContextId;\n};\n\n/**\n * Resolves permissions from Identity Service API\n * @param params - {@link ResolvePermissionsParams}\n * @returns {@link PermissionsEvaluationByContextId} Permission evaluation results by context ID\n */\nexport const resolvePermissions = async ({\n user,\n contextIds,\n requiredPermissions,\n options,\n}: ResolvePermissionsParams): Promise<PermissionsEvaluationByContextId> => {\n if (!requiredPermissions?.length) {\n return createEmptyPermissionsResult(contextIds);\n }\n\n const response = await IdentityNetwork.post('/api/v1/permissions/resolve', {\n userId: user.id,\n contextIds,\n requiredPermissions,\n }, {\n timeout: options.timeout,\n });\n\n const data: PermissionsEvaluationByContextId = response?.data || {};\n\n if (!Object.keys(data || {}).length) {\n throw new Error('Failed to resolve permissions');\n }\n\n if (options.permissionsEvaluationOperator === PERMISSIONS_EVALUATION_OPERATORS.AND) {\n return data;\n }\n\n // Re-evaluate with OR operator\n return formatResultsWithOrOperator(data, requiredPermissions);\n};\n\nconst validateInput = (contextIds: string[]): string[] => {\n const errors: string[] = [];\n\n if (!contextIds?.length) {\n errors.push('contextIds cannot be empty');\n }\n\n return errors;\n};\n\nconst createErrorResult = (\n error: PermissionErrorType,\n requiredPermissions: string[],\n contextIds: string[],\n message?: string,\n): PermissionCheckResult => ({\n isAuthorized: false,\n error,\n resolvedPermissions: {},\n requiredPermissions,\n contextIds,\n ...(message && { message }),\n});\n\n/**\n * Caches permission results based on whether they meet requirements\n * - Caches granted permissions directly\n * - Groups denied permissions by identical sets to optimize cache storage\n * @param userId - User ID\n * @param resolvedPermissions - Permissions evaluation results to cache\n * @param requiredPermissions - Required permissions used for evaluation\n */\nconst cachePermissionsResults = (\n userId: string,\n resolvedPermissions: PermissionsEvaluationByContextId,\n requiredPermissions: string[],\n logger?: Logger,\n): void => {\n const permissionsToCache: PermissionsByContextId = {};\n const deniedPermissionsMap = new Map<string, string[]>();\n\n logger?.debug('Start caching permissions results', {\n userId,\n resolvedPermissions,\n requiredPermissions,\n });\n\n Object.entries(resolvedPermissions).forEach(([contextId, evaluation]) => {\n if (evaluation?.permissions) {\n const userPermissionsSet = new Set(evaluation.permissions);\n const effectivePermissions = requiredPermissions.filter(permission => userPermissionsSet.has(permission));\n const deniedPermissions = requiredPermissions.filter(permission => !userPermissionsSet.has(permission));\n\n if (effectivePermissions.length) {\n // Store only effective permissions (intersection of user and required permissions)\n permissionsToCache[contextId] = effectivePermissions;\n }\n\n if (deniedPermissions.length) {\n // Calculate which required permissions were denied by filtering out the ones the user has\n const deniedPermissionsKey = deniedPermissions.sort().join(',');\n\n if (!deniedPermissionsMap.has(deniedPermissionsKey)) {\n deniedPermissionsMap.set(deniedPermissionsKey, []);\n }\n deniedPermissionsMap.get(deniedPermissionsKey)!.push(contextId);\n }\n }\n });\n\n if (Object.keys(permissionsToCache).length > 0) {\n const pastCache = permissionCache.getUserPermissions(userId, Object.keys(permissionsToCache));\n\n Object.keys(pastCache ?? {}).forEach((contextId) => {\n if (permissionsToCache[contextId]) {\n // Merge with any previously cached permissions to avoid overwriting\n const mergedPermissions = Array.from(new Set([...(pastCache[contextId] || []), ...permissionsToCache[contextId]]));\n permissionsToCache[contextId] = mergedPermissions;\n }\n });\n\n logger?.debug('Caching granted permissions', { userId, permissionsToCache, pastCache });\n const { success } = permissionCache.setUserPermissions(userId, permissionsToCache);\n if (!success) {\n logger?.error('Failed to cache granted permissions', { userId, permissionsToCache });\n }\n }\n\n // Cache denied permissions grouped by the same denied permissions to utilize mset efficiently\n Array.from(deniedPermissionsMap.entries()).map(([deniedPermissionsKey, contextIds]) => {\n const deniedPermissions = deniedPermissionsKey.split(',');\n return permissionCache.setCachedDeniedPermissions(userId, contextIds, deniedPermissions);\n });\n\n logger?.debug('Caching denied permissions', {\n userId,\n deniedPermissionsGroups: Array.from(deniedPermissionsMap.entries()).map(([key, contexts]) => ({\n deniedPermissions: key.split(','),\n contextIds: contexts,\n })),\n });\n};\n\n/**\n * Determines if a context can be resolved from denied permissions cache\n * @param deniedPermissions - Previously denied permissions for the context\n * @param requiredPermissions - Currently required permissions\n * @param operator - Evaluation operator (AND/OR)\n * @returns Object indicating if context is resolvable from cache and the result\n */\nconst isResolvableFromDeniedCache = (\n deniedPermissions: string[],\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): { isResolvableFromCache: boolean; hasRequiredPermissions: boolean; } => {\n if (!deniedPermissions.length) {\n return { isResolvableFromCache: false, hasRequiredPermissions: false };\n }\n\n const deniedSet = new Set(deniedPermissions);\n const deniedRequiredPermissions = requiredPermissions.filter(permission => deniedSet.has(permission));\n\n if (operator === PERMISSIONS_EVALUATION_OPERATORS.AND) {\n // For AND: if any required permission was denied, we can resolve as false\n return {\n isResolvableFromCache: deniedRequiredPermissions.length > 0,\n hasRequiredPermissions: false,\n };\n }\n\n // For OR: only if ALL required permissions were denied, we can resolve as false\n return {\n isResolvableFromCache: deniedRequiredPermissions.length === requiredPermissions.length,\n hasRequiredPermissions: false,\n };\n};\n\n/**\n * Gets contexts that need API calls (unseen + partially resolvable seen contexts)\n * @param unseenContextIds - Context IDs that have no cached data\n * @param deniedContextIds - Context IDs that have cached denied permissions\n * @param deniedContextEntries - Context IDs that were fully resolved from cache\n * @returns Array of context IDs that need API calls\n */\nconst getContextsNeedingAPI = (\n unseenContextIds: string[],\n deniedContextIds: string[],\n deniedContextEntries: PermissionsEvaluationByContextId,\n): string[] => {\n const contextIdsNeedingAPI = [...unseenContextIds];\n\n // Add denied contexts that couldn't be resolved from cache\n const unresolvedDeniedContextIds = deniedContextIds.filter(contextId => !deniedContextEntries[contextId]);\n contextIdsNeedingAPI.push(...unresolvedDeniedContextIds);\n\n return contextIdsNeedingAPI;\n};\n\n/**\n * Processes denied contexts that can be resolved from denied permissions cache\n * @param deniedContextIds - Context IDs that have cached denied permissions\n * @param deniedPermissions - Denied permissions cache data\n * @param requiredPermissions - Currently required permissions\n * @param operator - Evaluation operator (AND/OR)\n * @returns Object with cache-resolvable contexts and their evaluations\n */\nconst processCachedDeniedContexts = (\n deniedContextIds: string[],\n seenPermissions: Record<string, string[]>,\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): PermissionsEvaluationByContextId => {\n const result: PermissionsEvaluationByContextId = {};\n\n deniedContextIds.forEach((contextId) => {\n const deniedPermissions = seenPermissions[contextId];\n const cacheResult = isResolvableFromDeniedCache(deniedPermissions, requiredPermissions, operator);\n\n if (cacheResult.isResolvableFromCache) {\n result[contextId] = {\n permissions: [],\n hasRequiredPermissions: cacheResult.hasRequiredPermissions,\n };\n }\n });\n\n return result;\n};\n\n/**\n * Processes cached permissions into evaluation format\n * @param cachedPermissions - Raw permissions from cache\n * @param requiredPermissions - Required permissions to evaluate against\n * @param operator - Evaluation operator (AND/OR)\n * @returns Processed permissions evaluation\n */\nconst processCachedPermissions = (\n cachedPermissions: Record<string, string[]>,\n requiredPermissions: string[],\n operator: PermissionsEvaluationOperator,\n): PermissionsEvaluationByContextId => {\n const processedPermissions: PermissionsEvaluationByContextId = {};\n\n if (Object.keys(cachedPermissions || {}).length) {\n Object.entries(cachedPermissions).forEach(([contextId, permissions]) => {\n const hasRequiredPermissions = evaluatePermissionsByOperator(\n permissions,\n requiredPermissions,\n operator,\n );\n\n // Only include contexts that can be fully resolved from cache\n // Since we only cache effective permissions we won't have all of the user's permissions to fully resolve\n if (hasRequiredPermissions) {\n processedPermissions[contextId] = {\n permissions,\n hasRequiredPermissions,\n };\n }\n });\n }\n\n return processedPermissions;\n};\n\n/**\n * Calls the Identity API to resolve permissions for unseen contexts\n * @param userId - User ID\n * @param contextIds - Context IDs to resolve\n * @param requiredPermissions - Required permissions\n * @param options - API call options\n * @returns Resolved permissions from API\n */\nconst callIdentityAPI = async (\n userId: string,\n contextIds: string[],\n requiredPermissions: string[],\n options: { permissionsEvaluationOperator: PermissionsEvaluationOperator; timeout: number; },\n): Promise<PermissionsEvaluationByContextId> => {\n const response = await IdentityNetwork.post('/api/v1/permissions/resolve', {\n userId,\n contextIds,\n requiredPermissions,\n }, {\n timeout: options.timeout,\n });\n\n const data: PermissionsEvaluationByContextId = response?.data || {};\n\n if (!Object.keys(data || {}).length) {\n throw new Error('Failed to resolve permissions');\n }\n\n // If using AND operator, return data as-is. For OR, re-evaluate.\n if (options.permissionsEvaluationOperator === PERMISSIONS_EVALUATION_OPERATORS.AND) {\n return data;\n }\n\n // Re-evaluate with OR operator\n const reEvaluatedPermissions: PermissionsEvaluationByContextId = {};\n Object.entries(data).forEach(([contextId, evaluation]) => {\n const permissions = evaluation?.permissions || [];\n const hasRequiredPermissions = evaluatePermissionsByOperator(\n permissions,\n requiredPermissions,\n options.permissionsEvaluationOperator,\n );\n\n reEvaluatedPermissions[contextId] = {\n permissions,\n hasRequiredPermissions,\n };\n });\n\n return reEvaluatedPermissions;\n};\n\n/**\n * Validates user context and required permissions for evaluation\n * @param contextIds - Context IDs to validate\n * @param requiredPermissions - Required permissions to validate\n * @param userId - User ID to validate\n * @param logger - Logger instance for warnings\n * @returns Error result if validation fails, null if validation passes\n */\nconst validateEvaluationInput = (\n contextIds: string[],\n requiredPermissions: string[],\n userId: string | null,\n logger?: Logger,\n): PermissionCheckResult | null => {\n const validationErrors = validateInput(contextIds);\n if (validationErrors.length) {\n return createErrorResult(PERMISSION_ERROR_TYPES.VALIDATION_ERROR, requiredPermissions, contextIds, validationErrors.join(', '));\n }\n\n if (!userId) {\n logger?.warn('User not found in context, cannot check permissions', {\n contextIds,\n requiredPermissions,\n });\n return createErrorResult(PERMISSION_ERROR_TYPES.USER_NOT_FOUND, requiredPermissions, contextIds);\n }\n\n if (!requiredPermissions?.length) {\n logger?.info('No requiredPermissions provided', {\n userId,\n contextIds,\n });\n return {\n isAuthorized: false,\n userId,\n resolvedPermissions: {},\n requiredPermissions,\n contextIds,\n error: PERMISSION_ERROR_TYPES.NO_REQUIRED_PERMISSIONS,\n };\n }\n\n return null;\n};\n\n/**\n * Resolves permissions from Identity API and combines with existing resolved permissions\n * @param userId - User ID\n * @param contextIdsNeedingAPI - Context IDs that need API resolution\n * @param requiredPermissions - Required permissions to check\n * @param options - API call options {@link ResolvePermissionsParams}\n * @param resolvedPermissions - Already resolved permissions from cache and denied cache\n * @returns Combined permissions including those resolved from API\n */\nconst resolvePermissionsFromAPI = async (\n userId: string,\n contextIdsNeedingAPI: string[],\n requiredPermissions: string[],\n options: { permissionsEvaluationOperator: PermissionsEvaluationOperator; timeout: number; },\n resolvedPermissions: PermissionsEvaluationByContextId,\n): Promise<PermissionsEvaluationByContextId> => {\n let newResolvedPermissions: PermissionsEvaluationByContextId = { ...resolvedPermissions };\n // Call Identity API for unresolved contexts\n const resolvedPermissionsFromIdentityMS = await callIdentityAPI(\n userId,\n contextIdsNeedingAPI,\n requiredPermissions,\n options,\n );\n\n // Combine all resolved permissions\n newResolvedPermissions = {\n ...resolvedPermissions,\n ...resolvedPermissionsFromIdentityMS,\n };\n\n cachePermissionsResults(userId, resolvedPermissionsFromIdentityMS, requiredPermissions);\n\n return newResolvedPermissions;\n};\n\n/**\n * Resolves permissions from multiple sources (cache, seen contexts, API)\n * @param userId - User ID\n * @param contextIds - Context IDs to resolve permissions for\n * @param requiredPermissions - Required permissions to check\n * @param options - Evaluation options\n * @returns Combined permissions from all sources: cache, denied cache, and API\n */\nconst resolveAllPermissions = async (\n userId: string,\n contextIds: string[],\n requiredPermissions: string[],\n options: {\n permissionsEvaluationOperator: PermissionsEvaluationOperator;\n timeout: number;\n logger?: Logger;\n },\n): Promise<PermissionsEvaluationByContextId> => {\n const { logger } = options;\n // Cached allowed permissions\n const cachedAllowedPermissions = permissionCache.getUserPermissions(userId, contextIds);\n const resolvedPermissionsFromCache = processCachedPermissions(\n cachedAllowedPermissions,\n requiredPermissions,\n options.permissionsEvaluationOperator,\n );\n let resolvedPermissions = { ...resolvedPermissionsFromCache };\n\n // Context ids without allowed permissions in cache\n const contextIdsWithoutAllowedCache = contextIds.filter(contextId => !resolvedPermissionsFromCache[contextId]);\n\n // Handle denied cache permissions\n const cachedDeniedPermissions = permissionCache.getCachedDeniedPermissions(userId, contextIdsWithoutAllowedCache);\n\n // Context ids that have never been seen before (not in allowed or denied cache)\n const unseenContextIds = contextIdsWithoutAllowedCache.filter(contextId => !cachedDeniedPermissions[contextId]);\n\n // Process denied permissions cache\n const deniedContextIds = contextIdsWithoutAllowedCache.filter(contextId => cachedDeniedPermissions[contextId]);\n const deniedContextEntries = processCachedDeniedContexts(\n deniedContextIds,\n cachedDeniedPermissions,\n requiredPermissions,\n options.permissionsEvaluationOperator,\n );\n\n // Combine resolved permissions with those resolved from denied cache\n resolvedPermissions = { ...resolvedPermissions, ...deniedContextEntries };\n\n // Resolve the remaining contexts using the Identity API\n const contextIdsNeedingAPI = getContextsNeedingAPI(unseenContextIds, deniedContextIds, deniedContextEntries);\n if (contextIdsNeedingAPI.length) {\n // Call Identity API for unresolved contexts\n return resolvePermissionsFromAPI(\n userId,\n contextIdsNeedingAPI,\n requiredPermissions,\n options,\n resolvedPermissions,\n );\n }\n\n logger?.debug('Final resolved permissions', {\n userId,\n requiredPermissions,\n resolvedPermissions,\n });\n\n return resolvedPermissions;\n};\n\n/**\n * Main SDK function to evaluate user permissions\n * Checks both cached and API-resolved permissions to determine access\n * @param params - {@link EvaluatePermissionsParams}\n * @returns {@link PermissionCheckResult} Detailed permission check result with access status and context\n */\nexport const evaluatePermissions = async ({\n requiredPermissions,\n contextIds,\n logger,\n userId,\n options: {\n requireAll = true,\n permissionsEvaluationOperator = PERMISSIONS_EVALUATION_OPERATORS.AND,\n timeout = 10000,\n },\n}: EvaluatePermissionsParams): Promise<PermissionCheckResult> => {\n const resolvedUserId = userId || getUser()?.id || null;\n\n const validationError = validateEvaluationInput(contextIds, requiredPermissions, resolvedUserId, logger);\n if (validationError) {\n return validationError;\n }\n\n const resolvedPermissions = await resolveAllPermissions(\n resolvedUserId!,\n contextIds,\n requiredPermissions,\n { permissionsEvaluationOperator, timeout, logger },\n );\n\n const isAuthorized = checkAuthorizeRequirements(resolvedPermissions, requireAll);\n\n logger?.info('Resolved permissions', {\n userId: resolvedUserId,\n requiredPermissions,\n resolvedPermissions,\n isAuthorized,\n requireAll,\n permissionsEvaluationOperator,\n contextIds,\n });\n\n return {\n isAuthorized,\n userId: resolvedUserId!,\n resolvedPermissions,\n requiredPermissions,\n contextIds,\n ...(isAuthorized ? {} : { error: PERMISSION_ERROR_TYPES.INSUFFICIENT_PERMISSIONS }),\n };\n};\n\nexport default evaluatePermissions;\n","import type { Request, Response, NextFunction } from 'express';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentContext, newTrace, traceTypes } from '@autofleet/outbreak';\nimport { evaluatePermissions } from '../SDK/evaluatePermissions';\nimport type { EvaluatePermissionsOpts, Logger } from '../SDK/types';\nimport ApiUser, { CONTEXTS_IDS_HEADER } from '../../user/ApiUser';\nimport { PERMISSION_ERROR_MESSAGES, PERMISSION_ERROR_TYPES, PERMISSIONS_EVALUATION_OPERATORS } from '../SDK/consts';\nimport { decodeBearer } from '../../utils';\nimport { IdentityNetwork } from '../../services';\nimport { USER_OBJECT } from '../../user/const';\nimport { getUser } from '../../check-permission';\n\nexport interface RequirePermissionsOptions extends EvaluatePermissionsOpts {\n logger?: LoggerInstanceManager;\n}\n\nconst getContextIds = (req: Request, logger?: Logger): string[] => {\n logger?.debug('Extracting context IDs from request', {\n headers: req.headers,\n query: req.query,\n body: req.body,\n });\n\n const contextIdsFromHeader = (req.headers?.[CONTEXTS_IDS_HEADER] as string)?.split(',') || [];\n const contextFromAFContextHeader = req.headers?.['af-context'] ? [req.headers['af-context'] as string] : [];\n const contextIdsFromQuery = (req.query?.contextIds as string)?.split(',') || [];\n const contextIdFromQuery = (req.query?.contextId as string) ? [req.query.contextId as string] : [];\n const contextFromQuery = req.query?.context ? [req.query.context as string] : [];\n const contextIdsFromBody = (req.body?.contextIds as string[]) || [];\n const contextIdFromBody = (req.body?.contextId as string) ? [req.body.contextId as string] : [];\n\n return Array.from(new Set([\n ...contextIdsFromHeader,\n ...contextFromAFContextHeader,\n ...contextIdsFromQuery,\n ...contextIdFromQuery,\n ...contextFromQuery,\n ...contextIdsFromBody,\n ...contextIdFromBody,\n ])).filter(Boolean);\n};\n\nconst handleError = (\n errorLabel: string,\n message: string,\n code: number,\n enforce: boolean | undefined,\n res: Response,\n req: Request,\n next: NextFunction,\n logger?: LoggerInstanceManager,\n additionalInfo?: { requiredPermissions?: string[]; },\n) => {\n if (enforce) {\n logger?.error(message, {\n url: req.url,\n method: req.method,\n requiredPermissions: additionalInfo?.requiredPermissions ?? [],\n ...additionalInfo,\n });\n\n res.status(code).json({\n error: errorLabel,\n message,\n ...(additionalInfo?.requiredPermissions && { requiredPermissions: additionalInfo.requiredPermissions }),\n });\n return;\n }\n\n logger?.warn(message, {\n url: req.url,\n method: req.method,\n requiredPermissions: additionalInfo?.requiredPermissions ?? [],\n ...additionalInfo,\n });\n next();\n};\n\nconst createNewUserTrace = (userId: string, contextIds: string[], logger?: Logger) => {\n try {\n newTrace(traceTypes.HTTP_REQUEST);\n const apiUser = new ApiUser(userId, undefined, undefined, contextIds);\n getCurrentContext().nonHeaderContext?.set(USER_OBJECT, apiUser);\n } catch (error) {\n logger?.error('Error creating new user trace', { error, userId, contextIds });\n }\n};\n\nconst getUserContextsFromIdentity = async (userId: string, timeout?: number): Promise<string[]> => {\n try {\n const response = await IdentityNetwork.get(`/api/v1/users/${userId}/contexts`, { timeout });\n const contextIds = (response?.data || []).map((context: { id: string; }) => context.id);\n\n createNewUserTrace(userId, contextIds);\n\n return contextIds;\n } catch {\n return [];\n }\n};\n\n/**\n * Express middleware that requires specific permissions for route access\n *\n * @param requiredPermissions - Array of permissions required to access the route\n * @param options - Configuration options for permission checking\n * @returns Express middleware function\n */\nexport const requirePermissions = (\n requiredPermissions: string[],\n options: RequirePermissionsOptions = {\n enforce: false,\n requireAll: true,\n permissionsEvaluationOperator: PERMISSIONS_EVALUATION_OPERATORS.AND,\n },\n) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const {\n logger,\n enforce,\n requireAll,\n permissionsEvaluationOperator,\n } = options;\n\n const handleErrorWrapper = (errorLabel: string, message: string, code: number) => handleError(\n errorLabel,\n message,\n code,\n enforce,\n res,\n req,\n next,\n logger,\n { requiredPermissions },\n );\n\n let decodedToken: { user?: { id?: string; }; } | null = null;\n try {\n decodedToken = decodeBearer(req.headers.authorization || '');\n } catch { /* no-op */ }\n const user = getUser() ?? decodedToken?.user;\n if (!user?.id) {\n handleErrorWrapper(\n PERMISSION_ERROR_TYPES.UNAUTHORIZED,\n PERMISSION_ERROR_MESSAGES.UNAUTHORIZED,\n 401,\n );\n return;\n }\n\n const contextIdsFromRequest: string[] = getContextIds(req, logger);\n // If no context IDs are provided in the request, fetch them from the Identity service\n const contextIdsFromIdentity = !contextIdsFromRequest?.length ? await getUserContextsFromIdentity(user.id, options.timeout) : [];\n\n // Combine and remove deduplicate context IDs from request and identity service\n const contextIds = Array.from(new Set([...contextIdsFromRequest, ...contextIdsFromIdentity]));\n\n if (!contextIds?.length) {\n handleErrorWrapper(\n PERMISSION_ERROR_TYPES.BAD_REQUEST,\n PERMISSION_ERROR_MESSAGES.BAD_REQUEST,\n 400,\n );\n return;\n }\n\n // Evaluate permissions using SDK\n const result = await evaluatePermissions({\n requiredPermissions,\n contextIds,\n logger,\n userId: user.id,\n options: {\n requireAll: requireAll ?? true,\n permissionsEvaluationOperator: permissionsEvaluationOperator ?? PERMISSIONS_EVALUATION_OPERATORS.AND,\n timeout: 10000,\n ...(logger && { logger }),\n },\n });\n\n if (result.isAuthorized) {\n logger?.info('User has required permissions', {\n userId: user.id,\n requiredPermissions,\n contextIds,\n url: req.url,\n method: req.method,\n });\n next();\n return;\n }\n\n if (!enforce) {\n logger?.warn('User does not have required permissions, skipping enforcement', {\n userId: user.id,\n requiredPermissions,\n contextIds,\n url: req.url,\n method: req.method,\n });\n next();\n return;\n }\n\n res.status(403).json({\n error: PERMISSION_ERROR_TYPES.INSUFFICIENT_PERMISSIONS,\n message: PERMISSION_ERROR_MESSAGES.INSUFFICIENT_PERMISSIONS,\n required: requiredPermissions,\n contexts: contextIds,\n userId: result.userId,\n });\n } catch (error) {\n const requestLogger = options.logger;\n requestLogger?.error('Error in requirePermissions middleware', {\n error,\n requiredPermissions,\n url: req.url,\n method: req.method,\n });\n\n if (!options.enforce) {\n options.logger?.error('Error during permission check, skipping enforcement', {\n error,\n url: req.url,\n method: req.method,\n });\n next();\n return;\n }\n\n res.status(500).json({\n error: PERMISSION_ERROR_TYPES.INTERNAL_ERROR,\n message: PERMISSION_ERROR_MESSAGES.INTERNAL_ERROR,\n });\n }\n};\n\nexport default requirePermissions;\n","import { evaluatePermissions } from './SDK/evaluatePermissions';\nimport { requirePermissions } from './middleware/requirePermissions';\n\ninterface SdkExports {\n evaluatePermissions: typeof evaluatePermissions;\n}\n\ninterface MiddlewareExports {\n requirePermissions: typeof requirePermissions;\n}\n\ninterface PermissionsModule {\n sdk: SdkExports;\n middlewares: MiddlewareExports;\n}\n\nexport const sdk: SdkExports = {\n evaluatePermissions,\n};\n\nexport const middlewares: MiddlewareExports = {\n requirePermissions,\n};\n\nexport default {\n sdk,\n middlewares,\n} as PermissionsModule;\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';\nimport * as permissions from './permissions';\n\nconst getCurrentPayload: typeof outbreak.getCurrentContext = 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: typeof outbreak.traceTypes = outbreak.traceTypes;\nconst newTrace: typeof outbreak.newTrace = outbreak.newTrace;\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 permissions,\n};\n\ninterface Default {\n traceTypes: typeof outbreak.traceTypes;\n newTrace: typeof outbreak.newTrace;\n User: typeof User;\n middleware: typeof middleware;\n middlewareWithDecode: typeof middlewareWithDecode;\n eagerLoadPermissionsMiddleware: typeof eagerLoadPermissionsMiddleware;\n getCurrentPayload: typeof outbreak.getCurrentContext;\n getDecodedBearer: typeof getDecodedBearer;\n checkFleetPermission: typeof checkFleetPermission;\n checkBusinessModelPermission: typeof checkBusinessModelPermission;\n checkDemandSourcePermission: typeof checkDemandSourcePermission;\n isUserExist: typeof isUserExist;\n getUser: typeof getUser;\n UnauthorizedAccessError: typeof UnauthorizedAccessError;\n appMiddleware: typeof appMiddleware;\n createOrSetRabbitTrace: typeof createOrSetRabbitTrace;\n outbreak: typeof outbreak;\n AUTHORIZATION_METHODS: typeof AUTHORIZATION_METHODS;\n getAuthorizationHeader: typeof getAuthorizationHeader;\n CONTEXTS_IDS_HEADER: typeof CONTEXTS_IDS_HEADER;\n authFromUserIdHeaderPlugin: typeof authFromUserIdHeaderPlugin;\n permissions: typeof permissions;\n}\n\nconst zehutDefault: 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 permissions,\n};\n\nexport default zehutDefault;\n"],"mappings":"oTAGA,KAAM,CACJ,wBAAuB,iBACvB,gCAA+B,qBAC/B,8BACE,QAAQ,IAEN,GAAqB,EAA2B,EAA0B,IAA8B,CAC5G,IAAM,EAAkB,EAAO,SAAS,GAA8B,GAAI,IAAM,KAChF,GAAI,CACF,IAAIA,EACJ,GAAI,EAAO,CACT,GAAM,CAAE,OAAQ,EAAI,OAAO,GAC3B,EAAW,EAAO,EAAO,UAEzB,EAAW,IAEb,OAAO,EAAS,SAAS,GAAmB,EAAmB,OACzD,CACN,OAAO,IAIE,GAAyB,GAA2B,EAAkB,EAAO,EAAgC,GAC7G,EAAkB,GAA2B,EAAkB,EAAO,EAAwB,GCV9F,EAAqB,GAA2B,EAAO,QAAQ,UAAW,IAE1E,GAAgB,EAAgB,IAA4B,CACvE,IAAM,EAAQ,EAAkB,GAC1B,EAAU,EAAI,OAAO,EAAO,GAAa,EAAe,IAC9D,OAAO,GA2DH,EAAoB,WAEpB,GAAiB,OACrB,OAAO,EAAkB,MAAM,EAAkB,WAA2B,EAAkB,YAAY,EAAkB,MAAM,EAAkB,kFACpJ,KAEF,SAAg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