@autofleet/shtinker 3.4.9 → 3.4.10
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/dist/common-BDIWNOOw.cjs +2 -0
- package/dist/common-BDIWNOOw.cjs.map +1 -0
- package/dist/common-CoCVkYgj.js +2 -0
- package/dist/common-CoCVkYgj.js.map +1 -0
- package/dist/{const-Cu9hC4zo.d.ts → const-BHeWcRFO.d.ts} +5 -2
- package/dist/{const-UuDReAlY.d.cts → const-Bo8lzLSU.d.cts} +5 -2
- package/dist/fastify.cjs +1 -1
- package/dist/fastify.d.cts +1 -1
- package/dist/fastify.d.ts +1 -1
- package/dist/fastify.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/common-DcTpGBvn.js +0 -2
- package/dist/common-DcTpGBvn.js.map +0 -1
- package/dist/common-kvWo0enA.cjs +0 -2
- package/dist/common-kvWo0enA.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:util`)),l=s(require(`@autofleet/zehut`)),u=s(require(`@autofleet/logger`)),d=s(require(`@autofleet/network`));let f=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),p=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),m=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const h=`audit-log-context`,g=`audit-log-rows`,_=`auditLogContext`,v=`x-af-automation-id`,y=(0,u.default)();y.addContextMiddleware(()=>({traceId:l.outbreak.getCurrentContextTraceId()}));var b=y;const x=`customFields`,S=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(_);return t},C={[f.BULK_CREATE]:f.BULK_CREATE,[f.BULK_EDIT]:f.BULK_EDIT,[f.BULK_ASSIGN]:f.BULK_ASSIGN,[f.BULK_DISPATCH]:f.BULK_DISPATCH,[f.BULK_UPSERT]:f.BULK_UPSERT},w=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,T=e=>Object.hasOwn(C,e),E=(e,t)=>e.filter(e=>!w(t.get(e))||!w(t.previous(e))),D=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=E(n.filter(e=>e!==x),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},O=e=>{let t=e.changed(),n=t&&t.includes(x);if(!n)return[];let r=e.get(x),i=e.previous(x),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!w(t)||!w(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${x}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var k=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||b,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t},n=this.logAndThrowError){if(e??=S(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&T(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){n(e,t)}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=S();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...D(t,n),...O(t)]},this.logError)})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(h,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}logError=(e,t)=>{let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})};logAndThrowError=(e,t)=>{throw this.logError(e,t),e}},A=k;const j=new d.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:b}),M=async e=>{let{data:t}=await j.get(`api/v1/audit-logs/${e}`);return t},N={getByEntityId:M};var P=N;let F;const I=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(F=new A(e),F.registerHooks(),!0),L=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&m.USER||i&&m.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(_,c),c},R=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let i=L({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[v]});if(!T(r)){await F.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await F?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){b.error(`couldn't set audit context`,e)}},z=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let a=L({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await F.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return z}});
|
|
2
|
+
//# sourceMappingURL=common-BDIWNOOw.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common-BDIWNOOw.cjs","names":["logger: LoggerInstanceManager","outbreak","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","logger","errorHandler: AuditLogRowSendingErrorHandler","context: AuditLogContext","payload: AuditLogPayload","error: unknown","Network","entityId: string","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","AuditLogger","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","logger","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\ntype AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog(\n { auditContext, ...payload }: AuditLogSendData,\n errorHandler: AuditLogRowSendingErrorHandler = this.logAndThrowError,\n ): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n errorHandler(error, payload);\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n },\n this.logError);\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n\n private logError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n };\n\n private logAndThrowError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n this.logError(error, payload);\n throw error;\n };\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"omBAuCA,IAAY,EAAA,SAAA,EAAL,6XAkBN,EAAA,CAAA,EAAA,CAEW,EAAA,SAAA,EAAL,oGAKN,EAAA,CAAA,EAAA,CAEiB,EAAA,SAAA,EAAX,iDAGN,EAAA,CAAA,EAAA,CCrED,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,GAAAA,EAAAA,EAAAA,UAAwC,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAASC,EAAAA,SAAS,0BAA0B,AAAE,GAAE,CACrF,IAAA,EAAe,ECQf,MAAM,EAAyB,eAEzB,EAAkB,IAAM,CAC5B,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GAAI,QAAQ,IAAI,qBAAuB,QAAU,CAAC,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,SAAU,EAAI,IACd,aACA,OAAQ,EAAI,OACZ,QAAA,EAAA,EAAA,UAAiB,EAAE,GACnB,aAAc,EAAI,QAAQ,EAC3B,EAAC,CAEF,GAAI,CAAC,EAAmB,EAAO,CAAE,CAC/B,MAAM,EAAY,oBAAoB,EAAgB,CACtD,MACD,CAED,IAAM,EAA2B,SAAY,CAC3C,EAAI,IAAI,SAAU,EAAyB,CAC3C,EAAI,IAAI,QAAS,EAAyB,CAC1C,EAAI,IAAI,QAAS,EAAyB,CAC1C,MAAM,GAAa,oBAAoB,EAAgB,AACxD,EACD,EAAI,KAAK,SAAU,EAAyB,CAC5C,EAAI,KAAK,QAAS,EAAyB,CAC3C,EAAI,KAAK,QAAS,EAAyB,AAC5C,OAAQ,EAAK,CACZC,EAAO,MAAM,6BAA+B,EAAI,AACjD,CACF,EAEY,EAAwB,CAACF,EAAoBC,IAAmB,MAAOE,EAAkB,CAAE,SAAQ,eAAyD,GAAoB,CAC3L,GAAI,QAAQ,IAAI,qBAAuB,QAAU,CAAC,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,MAAM,EAAY,oBAAoB,EAAgB,AACvD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n,outbreak as r}from"@autofleet/zehut";import i from"@autofleet/logger";import a from"@autofleet/network";let o=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),s=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const l=`audit-log-context`,u=`audit-log-rows`,d=`auditLogContext`,f=`x-af-automation-id`,p=i();p.addContextMiddleware(()=>({traceId:r.getCurrentContextTraceId()}));var m=p;const h=`customFields`,g=()=>{let e=t(),n=e?.nonHeaderContext?.get(d);return n},_={[o.BULK_CREATE]:o.BULK_CREATE,[o.BULK_EDIT]:o.BULK_EDIT,[o.BULK_ASSIGN]:o.BULK_ASSIGN,[o.BULK_DISPATCH]:o.BULK_DISPATCH,[o.BULK_UPSERT]:o.BULK_UPSERT},v=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,y=e=>Object.hasOwn(_,e),b=(e,t)=>e.filter(e=>!v(t.get(e))||!v(t.previous(e))),x=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=b(n.filter(e=>e!==h),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},S=t=>{let n=t.changed(),r=n&&n.includes(h);if(!r)return[];let i=t.get(h),a=t.previous(h),o=Object.keys(i).filter(t=>{let n=i?.[t],r=a?.[t];return(!v(n)||!v(r))&&!e(n,r)});return o.map(e=>({property:`${h}.${e}`,previousValue:a?.[e],newValue:i?.[e]}))};var C=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t},n=this.logAndThrowError){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){n(e,t)}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=g();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...x(t,n),...S(t)]},this.logError)})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(u,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}logError=(e,t)=>{let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})};logAndThrowError=(e,t)=>{throw this.logError(e,t),e}},w=C;const T=new a({serviceName:`AUDIT_MS`,timeout:6e4,logger:m}),E=async e=>{let{data:t}=await T.get(`api/v1/audit-logs/${e}`);return t},D={getByEntityId:E};var O=D;let k;const A=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(k=new w(e),k.registerHooks(),!0),j=({action:e,endpoint:n,entityType:r,method:i,automationId:a,userId:o})=>{let s=o||(a??null),l=o&&c.USER||a&&c.AUTOMATION||null,u={entityType:r,action:e,endpoint:n,method:i,performedBy:s,actionOrigin:l},f=t();return f.nonHeaderContext.set(d,u),u},M=async(e,t,r,i)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:i,endpoint:e.url,entityType:r,method:e.method,userId:n()?.id,automationId:e.headers[f]});if(!y(i)){await k.sendAuditLogContext(a);return}let o=async()=>{t.off(`finish`,o),t.off(`close`,o),t.off(`error`,o),await k?.sendAuditLogContext(a)};t.once(`finish`,o),t.once(`close`,o),t.once(`error`,o)}catch(e){m.error(`couldn't set audit context`,e)}},N=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await k.sendAuditLogContext(a)};export{d as AUDIT_LOG_CONTEXT_KEY,l as AUDIT_LOG_CONTEXT_QUEUE,u as AUDIT_LOG_ROWS_QUEUE,f as AUTOMATION_ID_HEADER,o as Action,c as ActionOrigin,s as EntityType,w as audit_logger_default,O as audit_ms_default,A as innerEnableAuditing,M as innerSetAuditContext,N as setRabbitAuditContext};
|
|
2
|
+
//# sourceMappingURL=common-CoCVkYgj.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common-CoCVkYgj.js","names":["logger: LoggerInstanceManager","getCurrentTrace","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","logger","errorHandler: AuditLogRowSendingErrorHandler","context: AuditLogContext","payload: AuditLogPayload","error: unknown","entityId: string","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","AuditLogger","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","logger","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\ntype AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog(\n { auditContext, ...payload }: AuditLogSendData,\n errorHandler: AuditLogRowSendingErrorHandler = this.logAndThrowError,\n ): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n errorHandler(error, payload);\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n },\n this.logError);\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n\n private logError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n };\n\n private logAndThrowError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n this.logError(error, payload);\n throw error;\n };\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"iMAuCA,IAAY,EAAA,SAAA,EAAL,6XAkBN,EAAA,CAAA,EAAA,CAEW,EAAA,SAAA,EAAL,oGAKN,EAAA,CAAA,EAAA,CAEiB,EAAA,SAAA,EAAX,iDAGN,EAAA,CAAA,EAAA,CCrED,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,EAAgC,GAAQ,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAAS,EAAS,0BAA0B,AAAE,GAAE,CACrF,IAAA,EAAe,ECQf,MAAM,EAAyB,eAEzB,EAAkB,IAAM,CAC5B,IAAM,EAAeC,GAAiB,CAChC,EAAe,GAAc,kBAAkB,IAAI,EAAsB,CAC/E,OAAO,CACR,EAEK,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WAAY,EAAO,WAC1B,EAAO,aAAc,EAAO,aAC5B,EAAO,eAAgB,EAAO,eAC9B,EAAO,aAAc,EAAO,WAC9B,EAEK,EAAU,AAACC,GACX,CAAC,KAAM,IAAA,EAAU,EAAC,SAAS,EAAmB,CACzC,GAEL,MAAM,QAAQ,EAAM,CACf,EAAM,SAAW,EAEtB,OAAO,GAAU,UAAY,EAAE,aAAiB,MAC3C,OAAO,KAAK,EAAiC,CAAC,SAAW,EAE3D,GAGI,EAAqB,AAACsB,GAA4B,OAAO,OAAO,EAAwC,EAAO,CAEtH,EAAuB,CAACpB,EAAkBC,IAAoB,EAAO,OAAO,GAAS,CAAC,EAAQ,EAAS,IAAI,EAAM,CAAC,EAAI,CAAC,EAAQ,EAAS,SAAS,EAAM,CAAC,CAAC,CAEzJ,EAAuB,CAACA,EAAiBC,IAAkE,CAG/G,IAAMC,EAA0B,EAAQ,UAAY,EAAQ,OAAqB,EAAS,SAAS,CAE7F,EAAwB,E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ACD,EAAC,CAEF,MAAM,EAAY,oBAAoB,EAAgB,AACvD"}
|
|
@@ -68,6 +68,7 @@ declare const enum ActionOrigin {
|
|
|
68
68
|
interface AuditLogSendData extends AuditLogPayload {
|
|
69
69
|
auditContext?: AuditLogContext;
|
|
70
70
|
}
|
|
71
|
+
type AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;
|
|
71
72
|
declare class AuditLogger {
|
|
72
73
|
private readonly rabbit;
|
|
73
74
|
private readonly sequelize;
|
|
@@ -77,10 +78,12 @@ declare class AuditLogger {
|
|
|
77
78
|
manualSendAuditLog({
|
|
78
79
|
auditContext,
|
|
79
80
|
...payload
|
|
80
|
-
}: AuditLogSendData): Promise<void>;
|
|
81
|
+
}: AuditLogSendData, errorHandler?: AuditLogRowSendingErrorHandler): Promise<void>;
|
|
81
82
|
registerHooks(): void;
|
|
82
83
|
sendAuditLogContext(context: AuditLogContext): Promise<void>;
|
|
83
84
|
private sendAuditLogRows;
|
|
85
|
+
private logError;
|
|
86
|
+
private logAndThrowError;
|
|
84
87
|
}
|
|
85
88
|
//#endregion
|
|
86
89
|
//#region src/common.d.ts
|
|
@@ -99,4 +102,4 @@ declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
|
|
|
99
102
|
declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
|
|
100
103
|
//#endregion
|
|
101
104
|
export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext };
|
|
102
|
-
//# sourceMappingURL=const-
|
|
105
|
+
//# sourceMappingURL=const-BHeWcRFO.d.ts.map
|
|
@@ -68,6 +68,7 @@ declare const enum ActionOrigin {
|
|
|
68
68
|
interface AuditLogSendData extends AuditLogPayload {
|
|
69
69
|
auditContext?: AuditLogContext;
|
|
70
70
|
}
|
|
71
|
+
type AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;
|
|
71
72
|
declare class AuditLogger {
|
|
72
73
|
private readonly rabbit;
|
|
73
74
|
private readonly sequelize;
|
|
@@ -77,10 +78,12 @@ declare class AuditLogger {
|
|
|
77
78
|
manualSendAuditLog({
|
|
78
79
|
auditContext,
|
|
79
80
|
...payload
|
|
80
|
-
}: AuditLogSendData): Promise<void>;
|
|
81
|
+
}: AuditLogSendData, errorHandler?: AuditLogRowSendingErrorHandler): Promise<void>;
|
|
81
82
|
registerHooks(): void;
|
|
82
83
|
sendAuditLogContext(context: AuditLogContext): Promise<void>;
|
|
83
84
|
private sendAuditLogRows;
|
|
85
|
+
private logError;
|
|
86
|
+
private logAndThrowError;
|
|
84
87
|
}
|
|
85
88
|
//#endregion
|
|
86
89
|
//#region src/common.d.ts
|
|
@@ -99,4 +102,4 @@ declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
|
|
|
99
102
|
declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
|
|
100
103
|
//#endregion
|
|
101
104
|
export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext };
|
|
102
|
-
//# sourceMappingURL=const-
|
|
105
|
+
//# sourceMappingURL=const-Bo8lzLSU.d.cts.map
|
package/dist/fastify.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-
|
|
1
|
+
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-BDIWNOOw.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};function r({fastify:r,logger:i,entityScopedModelMap:a}){!a||!r||Object.entries(a).forEach(([a,o])=>{r.get(`/api/v1/${a}/:id/audit`,{schema:{tags:[n.name],description:`Get audit logs for ${a} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async n=>{let{id:r}=n.params,s=await o.findByPk(r);if(!s){let e=new t.ResourceNotFoundError;throw i.error(`Entity ${a} with id ${r} not found`,{err:e}),e}return e.audit_ms_default.getByEntityId(r)})})}const i=t=>{let n=e.innerEnableAuditing(t);n&&r(t)},a=(t,n)=>async(r,i)=>{await e.innerSetAuditContext(r,i.raw,t,n)};var o=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.SWAGGER_TAG=n,exports.default=o,exports.enableAuditing=i,exports.setAuditContext=a,exports.setRabbitAuditContext=e.setRabbitAuditContext;
|
|
2
2
|
//# sourceMappingURL=fastify.cjs.map
|
package/dist/fastify.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-
|
|
1
|
+
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-Bo8lzLSU.cjs";
|
|
2
2
|
import { onRequestAsyncHookHandler } from "fastify";
|
|
3
3
|
|
|
4
4
|
//#region src/audit-api/fastify.d.ts
|
package/dist/fastify.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-
|
|
1
|
+
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-BHeWcRFO.js";
|
|
2
2
|
import { onRequestAsyncHookHandler } from "fastify";
|
|
3
3
|
|
|
4
4
|
//#region src/audit-api/fastify.d.ts
|
package/dist/fastify.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-
|
|
1
|
+
import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-CoCVkYgj.js";import{ResourceNotFoundError as f}from"@autofleet/errors";const p={name:`audit`,description:`Audit logs API`};function m({fastify:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/api/v1/${n}/:id/audit`,{schema:{tags:[p.name],description:`Get audit logs for ${n} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async e=>{let{id:i}=e.params,a=await r.findByPk(i);if(!a){let e=new f;throw t.error(`Entity ${n} with id ${i} not found`,{err:e}),e}return c.getByEntityId(i)})})}const h=e=>{let t=l(e);t&&m(e)},g=(e,t)=>async(n,r)=>{await u(n,r.raw,e,t)};var _=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,p as SWAGGER_TAG,_ as default,h as enableAuditing,g as setAuditContext,d as setRabbitAuditContext};
|
|
2
2
|
//# sourceMappingURL=fastify.js.map
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-
|
|
1
|
+
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-BDIWNOOw.cjs`),t=e.__toESM(require(`@autofleet/errors`));function n({router:n,logger:r,entityScopedModelMap:i}){!i||!n||Object.entries(i).forEach(([i,a])=>{n.get(`${i}/:id/audit`,async(n,o)=>{try{let{id:s}=n.params,c=await a.findByPk(s);if(!c)return(0,t.handleError)(new t.ResourceNotFoundError,o,{logger:r,message:`Entity ${i} with id ${s} not found`});let l=e.audit_ms_default.getByEntityId(s);return o.json(l)}catch(e){return(0,t.handleError)(new t.UnexpectedError(e),o,{logger:r})}})})}const r=t=>{let r=e.innerEnableAuditing(t);r&&n(t)},i=(t,n)=>async(r,i,a)=>(await e.innerSetAuditContext(r,i,t,n),a());var a=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.default=a,exports.enableAuditing=r,exports.setAuditContext=i,exports.setRabbitAuditContext=e.setRabbitAuditContext;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-
|
|
1
|
+
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-Bo8lzLSU.cjs";
|
|
2
2
|
import { NextFunction, Request, Response } from "express";
|
|
3
3
|
|
|
4
4
|
//#region src/index.d.ts
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-
|
|
1
|
+
import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-BHeWcRFO.js";
|
|
2
2
|
import { NextFunction, Request, Response } from "express";
|
|
3
3
|
|
|
4
4
|
//#region src/index.d.ts
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-
|
|
1
|
+
import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-CoCVkYgj.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";function h({router:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`${n}/:id/audit`,async(e,i)=>{try{let{id:a}=e.params,o=await r.findByPk(a);if(!o)return m(new f,i,{logger:t,message:`Entity ${n} with id ${a} not found`});let s=c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{let t=l(e);t&&h(e)},_=(e,t)=>async(n,r,i)=>(await u(n,r,e,t),i());var v=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,v as default,g as enableAuditing,_ as setAuditContext,d as setRabbitAuditContext};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
package/dist/common-DcTpGBvn.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n,outbreak as r}from"@autofleet/zehut";import i from"@autofleet/logger";import a from"@autofleet/network";let o=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),s=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const l=`audit-log-context`,u=`audit-log-rows`,d=`auditLogContext`,f=`x-af-automation-id`,p=i();p.addContextMiddleware(()=>({traceId:r.getCurrentContextTraceId()}));var m=p;const h=`customFields`,g=()=>{let e=t(),n=e?.nonHeaderContext?.get(d);return n},_={[o.BULK_CREATE]:o.BULK_CREATE,[o.BULK_EDIT]:o.BULK_EDIT,[o.BULK_ASSIGN]:o.BULK_ASSIGN,[o.BULK_DISPATCH]:o.BULK_DISPATCH,[o.BULK_UPSERT]:o.BULK_UPSERT},v=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,y=e=>Object.hasOwn(_,e),b=(e,t)=>e.filter(e=>!v(t.get(e))||!v(t.previous(e))),x=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=b(n.filter(e=>e!==h),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},S=t=>{let n=t.changed(),r=n&&n.includes(h);if(!r)return[];let i=t.get(h),a=t.previous(h),o=Object.keys(i).filter(t=>{let n=i?.[t],r=a?.[t];return(!v(n)||!v(r))&&!e(n,r)});return o.map(e=>({property:`${h}.${e}`,previousValue:a?.[e],newValue:i?.[e]}))};var C=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=g();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...x(t,n),...S(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(u,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},w=C;const T=new a({serviceName:`AUDIT_MS`,timeout:6e4,logger:m}),E=async e=>{let{data:t}=await T.get(`api/v1/audit-logs/${e}`);return t},D={getByEntityId:E};var O=D;let k;const A=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(k=new w(e),k.registerHooks(),!0),j=({action:e,endpoint:n,entityType:r,method:i,automationId:a,userId:o})=>{let s=o||(a??null),l=o&&c.USER||a&&c.AUTOMATION||null,u={entityType:r,action:e,endpoint:n,method:i,performedBy:s,actionOrigin:l},f=t();return f.nonHeaderContext.set(d,u),u},M=async(e,t,r,i)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:i,endpoint:e.url,entityType:r,method:e.method,userId:n()?.id,automationId:e.headers[f]});if(!y(i)){await k.sendAuditLogContext(a);return}let o=async()=>{t.off(`finish`,o),t.off(`close`,o),t.off(`error`,o),await k?.sendAuditLogContext(a)};t.once(`finish`,o),t.once(`close`,o),t.once(`error`,o)}catch(e){m.error(`couldn't set audit context`,e)}},N=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await k.sendAuditLogContext(a)};export{d as AUDIT_LOG_CONTEXT_KEY,l as AUDIT_LOG_CONTEXT_QUEUE,u as AUDIT_LOG_ROWS_QUEUE,f as AUTOMATION_ID_HEADER,o as Action,c as ActionOrigin,s as EntityType,w as audit_logger_default,O as audit_ms_default,A as innerEnableAuditing,M as innerSetAuditContext,N as setRabbitAuditContext};
|
|
2
|
-
//# sourceMappingURL=common-DcTpGBvn.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"common-DcTpGBvn.js","names":["logger: LoggerInstanceManager","getCurrentTrace","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","logger","context: AuditLogContext","payload: AuditLogPayload","entityId: string","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","AuditLogger","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","logger","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog({\n auditContext, ...payload\n }: AuditLogSendData): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n });\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"iMAuCA,IAAY,EAAA,SAAA,EAAL,6XAkBN,EAAA,CAAA,EAAA,CAEW,EAAA,SAAA,EAAL,oGAKN,EAAA,CAAA,EAAA,CAEiB,EAAA,SAAA,EAAX,iDAGN,EAAA,CAAA,EAAA,CCrED,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,EAAgC,GAAQ,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAAS,EAAS,0BAA0B,AAAE,GAAE,CACrF,IAAA,EAAe,ECQf,MAAM,EAAyB,eAEzB,EAAkB,IAAM,CAC5B,IAAM,EAAeC,GAAiB,CAChC,EAAe,GAAc,kBAAkB,IAAI,EAAsB,CAC/E,OAAO,CACR,EAEK,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WAAY,EAAO,WAC1B,EAAO,aAAc,EAAO,aAC5B,EAAO,eAAgB,EAAO,eAC9B,EAAO,aAAc,EAAO,WAC9B,EAEK,EAAU,AAACC,GACX,CAAC,KAAM,IAAA,EAAU,EAAC,SAAS,EAAmB,CACzC,GAEL,MAAM,QAAQ,EAAM,CACf,EAAM,SAAW,EAEtB,OAAO,GAAU,UAAY,EAAE,aAAiB,MAC3C,OAAO,KAAK,EAAiC,CAAC,SAAW,EAE3D,GAGI,EAAqB,AAACoB,GAA4B,OAAO,OAAO,EAAwC,EAAO,CAEtH,EAAuB,CAAClB,EAAkBC,IAAoB,EAAO,OAAO,GAAS,CAAC,EAAQ,EAAS,IAAI,EAAM,CAAC,EAAI,CAAC,EAAQ,EAAS,SAAS,EAAM,CAAC,CAAC,CAEzJ,EAAuB,CAACA,EAAiBC,IAAkE,CAG/G,IAAMC,EAA0B,EAAQ,UAAY,EAAQ,OAAqB,EAAS,SAAS,CAE7F,E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wnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:util`)),l=s(require(`@autofleet/zehut`)),u=s(require(`@autofleet/logger`)),d=s(require(`@autofleet/network`));let f=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),p=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),m=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const h=`audit-log-context`,g=`audit-log-rows`,_=`auditLogContext`,v=`x-af-automation-id`,y=(0,u.default)();y.addContextMiddleware(()=>({traceId:l.outbreak.getCurrentContextTraceId()}));var b=y;const x=`customFields`,S=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(_);return t},C={[f.BULK_CREATE]:f.BULK_CREATE,[f.BULK_EDIT]:f.BULK_EDIT,[f.BULK_ASSIGN]:f.BULK_ASSIGN,[f.BULK_DISPATCH]:f.BULK_DISPATCH,[f.BULK_UPSERT]:f.BULK_UPSERT},w=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,T=e=>Object.hasOwn(C,e),E=(e,t)=>e.filter(e=>!w(t.get(e))||!w(t.previous(e))),D=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=E(n.filter(e=>e!==x),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},O=e=>{let t=e.changed(),n=t&&t.includes(x);if(!n)return[];let r=e.get(x),i=e.previous(x),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!w(t)||!w(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${x}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var k=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||b,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=S(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&T(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=S();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...D(t,n),...O(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(h,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},A=k;const j=new d.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:b}),M=async e=>{let{data:t}=await j.get(`api/v1/audit-logs/${e}`);return t},N={getByEntityId:M};var P=N;let F;const I=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(F=new A(e),F.registerHooks(),!0),L=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&m.USER||i&&m.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(_,c),c},R=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let i=L({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[v]});if(!T(r)){await F.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await F?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){b.error(`couldn't set audit context`,e)}},z=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let a=L({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await F.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return z}});
|
|
2
|
-
//# sourceMappingURL=common-kvWo0enA.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"common-kvWo0enA.cjs","names":["logger: LoggerInstanceManager","outbreak","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","logger","context: AuditLogContext","payload: AuditLogPayload","Network","entityId: string","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","AuditLogger","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","logger","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog({\n auditContext, ...payload\n }: AuditLogSendData): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog({\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n });\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\n }\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"omBAuCA,IAAY,EAAA,SAAA,EAAL,6XAkBN,EAAA,CAAA,EAAA,CAEW,EAAA,SAAA,EAAL,oGAKN,EAAA,CAAA,EAAA,CAEiB,EAAA,SAAA,EAAX,iDAGN,EAAA,CAAA,EAAA,CCrED,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,GAAAA,EAAAA,EAAAA,UAAwC,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAAS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