@autofleet/shtinker 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/common-BWTPt3jo.cjs +2 -0
- package/dist/common-BWTPt3jo.cjs.map +1 -0
- package/dist/common-CJByaCJF.js +2 -0
- package/dist/common-CJByaCJF.js.map +1 -0
- package/dist/const-CC0vE16d.d.cts +99 -0
- package/dist/const-DrgE261l.d.ts +99 -0
- package/dist/fastify.cjs +11 -0
- package/dist/fastify.cjs.map +1 -0
- package/dist/fastify.d.cts +25 -0
- package/dist/fastify.d.ts +25 -0
- package/dist/fastify.js +11 -0
- package/dist/fastify.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -91
- package/dist/index.d.ts +2 -91
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +16 -6
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";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/outbreak`)),d=s(require(`@autofleet/logger`)),f=s(require(`@autofleet/network`));let p=/* @__PURE__ */ 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}({}),m=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),h=/* @__PURE__ */ function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const g=`audit-log-context`,_=`audit-log-rows`,v=`auditLogContext`,y=`x-af-automation-id`,b=(0,d.default)();b.addContextMiddleware(()=>({traceId:(0,u.getCurrentContextTraceId)()}));var x=b;const S=`customFields`,C=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(v);return t},w={[p.BULK_CREATE]:p.BULK_CREATE,[p.BULK_EDIT]:p.BULK_EDIT,[p.BULK_ASSIGN]:p.BULK_ASSIGN,[p.BULK_DISPATCH]:p.BULK_DISPATCH,[p.BULK_UPSERT]:p.BULK_UPSERT},T=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,E=e=>Object.hasOwn(w,e),D=(e,t)=>e.filter(e=>!T(t.get(e))||!T(t.previous(e))),O=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=D(n.filter(e=>e!==S),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},k=e=>{let t=e.changed(),n=t&&t.includes(S);if(!n)return[];let r=e.get(S),i=e.previous(S),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!T(t)||!T(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${S}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var A=class{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||x,this.excludeModels=e.excludeModels??[]}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{try{let r=C();if(!r)return;let{id:i}=t;r?.entityType?.toLowerCase()===e?.toLowerCase()&&E(r.action)&&(r.entityId=i);let a=O(t,n),o=k(t),s={entityType:e,entityId:i,rows:[...a,...o]};this.sendAuditLogRows(s)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(_,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},j=A;const M=new f.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:x}),N=async e=>{let{data:t}=await M.get(`api/v1/audit-logs/${e}`);return t},P={getByEntityId:N};var F=P;let I;const L=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(I=new j(e),I.registerHooks(),!0),R=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&h.USER||i&&h.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(v,c),c},z=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let i=R({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[y]});if(!E(r)){await I.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await I?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){x.error(`couldn't set audit context`,e)}},B=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let a=R({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await I.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return B}});
|
|
2
|
+
//# sourceMappingURL=common-BWTPt3jo.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common-BWTPt3jo.cjs","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions<any> | InstanceUpdateOptions<any>","changedFields: string[]","property: string","options: AuditLoggerOptions","payload: AuditLogPayload","context: AuditLogContext","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","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 type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: 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: any;\n newValue: any;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: 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 { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: 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,\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<any> | InstanceUpdateOptions<any>) => {\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) => {\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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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 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 try {\n const auditContext = getAuditContext();\n if (!auditContext) {\n return;\n }\n const { id: entityId } = instance as unknown as { id: string; };\n if (auditContext?.entityType?.toLowerCase() === modelName?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = entityId;\n }\n const changedFieldsRows = getChangedFieldsRows(instance, options);\n const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);\n const payload: AuditLogPayload = {\n entityType: modelName,\n entityId,\n rows: [...changedFieldsRows, ...changedCustomFieldsRows],\n };\n this.sendAuditLogRows(payload);\n } catch (error) {\n this.logger.error('Failed to send audit log rows', error);\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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,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,KAAM,GAAY,oBAAoB,EAAgB,AACvD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n}from"@autofleet/zehut";import{getCurrentContextTraceId as r}from"@autofleet/outbreak";import i from"@autofleet/logger";import a from"@autofleet/network";let o=/* @__PURE__ */ 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=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=/* @__PURE__ */ 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()}));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{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{try{let r=g();if(!r)return;let{id:i}=t;r?.entityType?.toLowerCase()===e?.toLowerCase()&&y(r.action)&&(r.entityId=i);let a=x(t,n),o=S(t),s={entityType:e,entityId:i,rows:[...a,...o]};this.sendAuditLogRows(s)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}})})}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-CJByaCJF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"common-CJByaCJF.js","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions<any> | InstanceUpdateOptions<any>","changedFields: string[]","property: string","options: AuditLoggerOptions","payload: AuditLogPayload","context: AuditLogContext","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","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 type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: 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: any;\n newValue: any;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: 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 { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: 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,\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<any> | InstanceUpdateOptions<any>) => {\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) => {\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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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 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 try {\n const auditContext = getAuditContext();\n if (!auditContext) {\n return;\n }\n const { id: entityId } = instance as unknown as { id: string; };\n if (auditContext?.entityType?.toLowerCase() === modelName?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = entityId;\n }\n const changedFieldsRows = getChangedFieldsRows(instance, options);\n const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);\n const payload: AuditLogPayload = {\n entityType: modelName,\n entityId,\n rows: [...changedFieldsRows, ...changedCustomFieldsRows],\n };\n this.sendAuditLogRows(payload);\n } catch (error) {\n this.logger.error('Failed to send audit log rows', error);\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":"kPAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,O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7FC,EAAmC,CACvC,aACA,SACA,WACA,SACA,cACA,cACD,EACK,EAAe,GAAmB,CAGxC,MAFA,GAAa,iBAAiB,IAAI,EAAuB,EAAgB,CAElE,CACR,EAQY,EAAuB,MAAOC,EAAqBC,EAAeC,EAAoBC,IAAkC,CACnI,GAAI,CACF,GAAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,SAAU,EAAI,IACd,aACA,OAAQ,EAAI,OACZ,OAAQ,GAAS,EAAE,GACnB,aAAc,EAAI,QAAQ,EAC3B,EAAC,CAEF,IAAK,EAAmB,EAAO,CAAE,CAC/B,KAAM,GAAY,oBAAoB,EAAgB,CACtD,MACD,CAED,IAAM,EAA2B,SAAY,CAI3C,AAHA,EAAI,IAAI,SAAU,EAAyB,CAC3C,EAAI,IAAI,QAAS,EAAyB,CAC1C,EAAI,IAAI,QAAS,EAAyB,CAC1C,KAAM,IAAa,oBAAoB,EAAgB,AACxD,EAGD,AAFA,EAAI,KAAK,SAAU,EAAyB,CAC5C,EAAI,KAAK,QAAS,EAAyB,CAC3C,EAAI,KAAK,QAAS,EAAyB,AAC5C,OAAQ,EAAK,CACZ,EAAO,MAAM,6BAA+B,EAAI,AACjD,CACF,EAEY,EAAwB,CAACD,EAAoBC,IAAmB,MAAOC,EAAkB,CAAE,SAAQ,eAAuD,GAAoB,CACzL,GAAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,KAAM,GAAY,oBAAoB,EAAgB,AACvD"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { FastifyInstance } from "fastify";
|
|
2
|
+
import { Model, ModelStatic } from "sequelize";
|
|
3
|
+
import { Sequelize } from "sequelize-typescript";
|
|
4
|
+
import RabbitMq from "@autofleet/rabbit";
|
|
5
|
+
import { LoggerInstanceManager } from "@autofleet/logger";
|
|
6
|
+
import { IRouter } from "express";
|
|
7
|
+
|
|
8
|
+
//#region src/types.d.ts
|
|
9
|
+
type AuditLoggerOptions = {
|
|
10
|
+
rabbit: RabbitMq;
|
|
11
|
+
sequelize: Sequelize;
|
|
12
|
+
logger: LoggerInstanceManager;
|
|
13
|
+
router?: IRouter;
|
|
14
|
+
fastify?: FastifyInstance;
|
|
15
|
+
excludeModels?: string[];
|
|
16
|
+
entityScopedModelMap?: {
|
|
17
|
+
[modelName: string]: ModelStatic<Model>;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
interface AuditLogContext {
|
|
21
|
+
entityType: string;
|
|
22
|
+
entityId?: string;
|
|
23
|
+
action: string;
|
|
24
|
+
performedBy: string | null;
|
|
25
|
+
endpoint: string;
|
|
26
|
+
method: string;
|
|
27
|
+
actionOrigin?: string | null;
|
|
28
|
+
}
|
|
29
|
+
interface AuditLogRow {
|
|
30
|
+
property: string;
|
|
31
|
+
previousValue: any;
|
|
32
|
+
newValue: any;
|
|
33
|
+
}
|
|
34
|
+
interface AuditLogPayload {
|
|
35
|
+
entityType: string;
|
|
36
|
+
entityId: string;
|
|
37
|
+
rows: AuditLogRow[];
|
|
38
|
+
}
|
|
39
|
+
declare enum Action {
|
|
40
|
+
CREATE = "create",
|
|
41
|
+
BULK_CREATE = "bulk-create",
|
|
42
|
+
BULK_EDIT = "bulk-edit",
|
|
43
|
+
DELETE = "delete",
|
|
44
|
+
UPDATE = "update",
|
|
45
|
+
CANCEL = "cancel",
|
|
46
|
+
FAIL = "fail",
|
|
47
|
+
UNASSIGN = "unassign",
|
|
48
|
+
BULK_ASSIGN = "bulk-assign",
|
|
49
|
+
REASSIGN = "reassign",
|
|
50
|
+
DISPATCH = "dispatch",
|
|
51
|
+
BULK_DISPATCH = "bulk-dispatch",
|
|
52
|
+
BULK_UPSERT = "bulk-upsert",
|
|
53
|
+
UPSERT = "upsert",
|
|
54
|
+
JOIN = "join",
|
|
55
|
+
MOVE = "move",
|
|
56
|
+
REOPTIMIZATION = "reoptimization",
|
|
57
|
+
}
|
|
58
|
+
declare enum EntityType {
|
|
59
|
+
RIDE = "Ride",
|
|
60
|
+
VEHICLE = "Vehicle",
|
|
61
|
+
DRIVER = "Driver",
|
|
62
|
+
PRICE_CALCULATION = "PriceCalculation",
|
|
63
|
+
}
|
|
64
|
+
declare const enum ActionOrigin {
|
|
65
|
+
USER = "user",
|
|
66
|
+
AUTOMATION = "automation",
|
|
67
|
+
} //#endregion
|
|
68
|
+
//#region src/audit-logger.d.ts
|
|
69
|
+
declare class AuditLogger {
|
|
70
|
+
private rabbit;
|
|
71
|
+
private sequelize;
|
|
72
|
+
private logger;
|
|
73
|
+
private excludeModels;
|
|
74
|
+
constructor(options: AuditLoggerOptions);
|
|
75
|
+
registerHooks(): void;
|
|
76
|
+
sendAuditLogContext(context: AuditLogContext): Promise<void>;
|
|
77
|
+
private sendAuditLogRows;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/common.d.ts
|
|
82
|
+
declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, {
|
|
83
|
+
userId,
|
|
84
|
+
automationId
|
|
85
|
+
}: {
|
|
86
|
+
userId: string;
|
|
87
|
+
automationId: string;
|
|
88
|
+
}) => Promise<void>;
|
|
89
|
+
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/const.d.ts
|
|
92
|
+
declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
|
|
93
|
+
declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
|
|
94
|
+
declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
|
|
95
|
+
declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
|
|
96
|
+
|
|
97
|
+
//#endregion
|
|
98
|
+
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 };
|
|
99
|
+
//# sourceMappingURL=const-CC0vE16d.d.cts.map
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { LoggerInstanceManager } from "@autofleet/logger";
|
|
2
|
+
import { FastifyInstance } from "fastify";
|
|
3
|
+
import { Model, ModelStatic } from "sequelize";
|
|
4
|
+
import { Sequelize } from "sequelize-typescript";
|
|
5
|
+
import RabbitMq from "@autofleet/rabbit";
|
|
6
|
+
import { IRouter } from "express";
|
|
7
|
+
|
|
8
|
+
//#region src/types.d.ts
|
|
9
|
+
type AuditLoggerOptions = {
|
|
10
|
+
rabbit: RabbitMq;
|
|
11
|
+
sequelize: Sequelize;
|
|
12
|
+
logger: LoggerInstanceManager;
|
|
13
|
+
router?: IRouter;
|
|
14
|
+
fastify?: FastifyInstance;
|
|
15
|
+
excludeModels?: string[];
|
|
16
|
+
entityScopedModelMap?: {
|
|
17
|
+
[modelName: string]: ModelStatic<Model>;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
interface AuditLogContext {
|
|
21
|
+
entityType: string;
|
|
22
|
+
entityId?: string;
|
|
23
|
+
action: string;
|
|
24
|
+
performedBy: string | null;
|
|
25
|
+
endpoint: string;
|
|
26
|
+
method: string;
|
|
27
|
+
actionOrigin?: string | null;
|
|
28
|
+
}
|
|
29
|
+
interface AuditLogRow {
|
|
30
|
+
property: string;
|
|
31
|
+
previousValue: any;
|
|
32
|
+
newValue: any;
|
|
33
|
+
}
|
|
34
|
+
interface AuditLogPayload {
|
|
35
|
+
entityType: string;
|
|
36
|
+
entityId: string;
|
|
37
|
+
rows: AuditLogRow[];
|
|
38
|
+
}
|
|
39
|
+
declare enum Action {
|
|
40
|
+
CREATE = "create",
|
|
41
|
+
BULK_CREATE = "bulk-create",
|
|
42
|
+
BULK_EDIT = "bulk-edit",
|
|
43
|
+
DELETE = "delete",
|
|
44
|
+
UPDATE = "update",
|
|
45
|
+
CANCEL = "cancel",
|
|
46
|
+
FAIL = "fail",
|
|
47
|
+
UNASSIGN = "unassign",
|
|
48
|
+
BULK_ASSIGN = "bulk-assign",
|
|
49
|
+
REASSIGN = "reassign",
|
|
50
|
+
DISPATCH = "dispatch",
|
|
51
|
+
BULK_DISPATCH = "bulk-dispatch",
|
|
52
|
+
BULK_UPSERT = "bulk-upsert",
|
|
53
|
+
UPSERT = "upsert",
|
|
54
|
+
JOIN = "join",
|
|
55
|
+
MOVE = "move",
|
|
56
|
+
REOPTIMIZATION = "reoptimization",
|
|
57
|
+
}
|
|
58
|
+
declare enum EntityType {
|
|
59
|
+
RIDE = "Ride",
|
|
60
|
+
VEHICLE = "Vehicle",
|
|
61
|
+
DRIVER = "Driver",
|
|
62
|
+
PRICE_CALCULATION = "PriceCalculation",
|
|
63
|
+
}
|
|
64
|
+
declare const enum ActionOrigin {
|
|
65
|
+
USER = "user",
|
|
66
|
+
AUTOMATION = "automation",
|
|
67
|
+
} //#endregion
|
|
68
|
+
//#region src/audit-logger.d.ts
|
|
69
|
+
declare class AuditLogger {
|
|
70
|
+
private rabbit;
|
|
71
|
+
private sequelize;
|
|
72
|
+
private logger;
|
|
73
|
+
private excludeModels;
|
|
74
|
+
constructor(options: AuditLoggerOptions);
|
|
75
|
+
registerHooks(): void;
|
|
76
|
+
sendAuditLogContext(context: AuditLogContext): Promise<void>;
|
|
77
|
+
private sendAuditLogRows;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/common.d.ts
|
|
82
|
+
declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, {
|
|
83
|
+
userId,
|
|
84
|
+
automationId
|
|
85
|
+
}: {
|
|
86
|
+
userId: string;
|
|
87
|
+
automationId: string;
|
|
88
|
+
}) => Promise<void>;
|
|
89
|
+
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/const.d.ts
|
|
92
|
+
declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
|
|
93
|
+
declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
|
|
94
|
+
declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
|
|
95
|
+
declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
|
|
96
|
+
|
|
97
|
+
//#endregion
|
|
98
|
+
export { AUDIT_LOG_CONTEXT_KEY as AUDIT_LOG_CONTEXT_KEY$1, AUDIT_LOG_CONTEXT_QUEUE as AUDIT_LOG_CONTEXT_QUEUE$1, AUDIT_LOG_ROWS_QUEUE as AUDIT_LOG_ROWS_QUEUE$1, AUTOMATION_ID_HEADER as AUTOMATION_ID_HEADER$1, Action as Action$1, ActionOrigin as ActionOrigin$1, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType as EntityType$1, setRabbitAuditContext as setRabbitAuditContext$1 };
|
|
99
|
+
//# sourceMappingURL=const-DrgE261l.d.ts.map
|
package/dist/fastify.cjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,`__esModule`,{value:!0});
|
|
2
|
+
/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
|
|
3
|
+
const e=require(`./common-BWTPt3jo.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};async 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)})})}
|
|
4
|
+
/**
|
|
5
|
+
* A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
|
|
6
|
+
* @param entityType The type of the entity being audited.
|
|
7
|
+
* @param action The action being performed on the entity.
|
|
8
|
+
* @returns A Fastify `onRequest` hook.
|
|
9
|
+
*/
|
|
10
|
+
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;
|
|
11
|
+
//# sourceMappingURL=fastify.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fastify.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":";;AAKA,mFAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAAA,sBAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAA,iBAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAda,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAA,qBAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe,EAAA"}
|
|
@@ -0,0 +1,25 @@
|
|
|
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-CC0vE16d.cjs";
|
|
2
|
+
import { onRequestAsyncHookHandler } from "fastify";
|
|
3
|
+
|
|
4
|
+
//#region src/audit-api/fastify.d.ts
|
|
5
|
+
/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
|
|
6
|
+
/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
|
|
7
|
+
declare const SWAGGER_TAG: {
|
|
8
|
+
name: string;
|
|
9
|
+
description: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/fastify.d.ts
|
|
14
|
+
declare const enableAuditing: (options: AuditLoggerOptions) => void;
|
|
15
|
+
/**
|
|
16
|
+
* A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
|
|
17
|
+
* @param entityType The type of the entity being audited.
|
|
18
|
+
* @param action The action being performed on the entity.
|
|
19
|
+
* @returns A Fastify `onRequest` hook.
|
|
20
|
+
*/
|
|
21
|
+
declare const setAuditContext: (entityType: string, action: string) => onRequestAsyncHookHandler;
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, SWAGGER_TAG, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
|
|
25
|
+
//# sourceMappingURL=fastify.d.cts.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DrgE261l.js";
|
|
2
|
+
import { onRequestAsyncHookHandler } from "fastify";
|
|
3
|
+
|
|
4
|
+
//#region src/audit-api/fastify.d.ts
|
|
5
|
+
/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
|
|
6
|
+
/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
|
|
7
|
+
declare const SWAGGER_TAG: {
|
|
8
|
+
name: string;
|
|
9
|
+
description: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/fastify.d.ts
|
|
14
|
+
declare const enableAuditing: (options: AuditLoggerOptions) => void;
|
|
15
|
+
/**
|
|
16
|
+
* A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
|
|
17
|
+
* @param entityType The type of the entity being audited.
|
|
18
|
+
* @param action The action being performed on the entity.
|
|
19
|
+
* @returns A Fastify `onRequest` hook.
|
|
20
|
+
*/
|
|
21
|
+
declare const setAuditContext: (entityType: string, action: string) => onRequestAsyncHookHandler;
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, SWAGGER_TAG, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
|
|
25
|
+
//# sourceMappingURL=fastify.d.ts.map
|
package/dist/fastify.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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-CJByaCJF.js";import{ResourceNotFoundError as f}from"@autofleet/errors";
|
|
2
|
+
/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
|
|
3
|
+
const p={name:`audit`,description:`Audit logs API`};async 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)})})}
|
|
4
|
+
/**
|
|
5
|
+
* A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
|
|
6
|
+
* @param entityType The type of the entity being audited.
|
|
7
|
+
* @param action The action being performed on the entity.
|
|
8
|
+
* @returns A Fastify `onRequest` hook.
|
|
9
|
+
*/
|
|
10
|
+
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};
|
|
11
|
+
//# sourceMappingURL=fastify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fastify.js","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":";;AAKA,MAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAda,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,`__esModule`,{value:!0});
|
|
1
|
+
"use strict";Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-BWTPt3jo.cjs`),t=e.__toESM(require(`@autofleet/errors`));async 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)=>(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.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["logger: LoggerInstanceManager","action: string","fields: string[]","instance: Model","options: CreateOptions<any> | InstanceUpdateOptions<any>","changedFields: string[]","property: string","options: AuditLoggerOptions","payload: AuditLogPayload","context: AuditLogContext","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction","auditLogContext: AuditLogContext","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/audit-api.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable no-shadow */\nimport 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';\n\nexport type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: string]: ModelStatic<Model> };\n};\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string;\n endpoint: string;\n method: string;\n actionOrigin?: string;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: any;\n newValue: any;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: 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 Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger(null);\nexport default logger;\n","import 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 { isEqual } from 'lodash';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action,\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) => {\n if ([null, undefined].includes(field)) {\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).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => !ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT[action];\n\nconst filterOutEmptyFields = (fields: string[], instance) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions<any> | InstanceUpdateOptions<any>) => {\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) => {\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);\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)) && !isEqual(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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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 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 try {\n const auditContext = getAuditContext();\n if (!auditContext) {\n return;\n }\n if (auditContext?.entityType?.toLowerCase() === modelName?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = (instance as any).id;\n }\n const changedFieldsRows = getChangedFieldsRows(instance, options);\n const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);\n const payload: AuditLogPayload = {\n entityType: modelName,\n entityId: (instance as any).id,\n rows: [...changedFieldsRows, ...changedCustomFieldsRows],\n };\n this.sendAuditLogRows(payload);\n } catch (error) {\n this.logger.error('Failed to send audit log rows', error);\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 { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from './audit-ms';\nimport { AuditLoggerOptions } from './types';\n\nexport default async ({\n router,\n logger,\n entityScopedModelMap,\n}: AuditLoggerOptions): Promise<void> => {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n};\n","import { getCurrentPayload as getCurrentTrace, getUser } from '@autofleet/zehut';\nimport type { Request, Response, NextFunction } from 'express';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport addAuditApi from './audit-api';\nimport logger from './logger';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return;\n }\n auditLogger = new AuditLogger(options);\n addAuditApi(options);\n auditLogger.registerHooks();\n};\n\nexport const setAuditContext = (\n entityType: string,\n action: string,\n) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return next();\n }\n const user = getUser();\n const automationId = req.headers[AUTOMATION_ID_HEADER] as string | undefined;\n const { performedBy, actionOrigin } = user?.id\n ? { performedBy: user.id, actionOrigin: ActionOrigin.USER }\n : { performedBy: automationId ?? null, actionOrigin: automationId ? ActionOrigin.AUTOMATION : null };\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint: req.url,\n method: req.method,\n performedBy,\n actionOrigin,\n };\n\n const currentTrace = getCurrentTrace();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\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 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 } else {\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n }\n } catch (err) {\n logger.error('coudln\\'t set audit context', err);\n }\n return next();\n};\n\nexport const setRabbitAuditContext = (\n entityType: string,\n action: string,\n) => 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 currentTrace = getCurrentTrace();\n if (currentTrace?.context?.get) {\n const { performedBy, actionOrigin } = userId\n ? { performedBy: userId, actionOrigin: ActionOrigin.USER }\n : { performedBy: automationId ?? null, actionOrigin: automationId ? ActionOrigin.AUTOMATION : null };\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method: 'rabbit',\n performedBy,\n actionOrigin,\n };\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n await auditLogger.sendAuditLogContext(auditLogContext);\n }\n};\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"usBAiEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA,YAAA,cACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,KAAA,OACA,EAAA,eAAA,kBACD,EAAA,CAAA,EAAA,CAEW,kBAAA,SAAA,EAAL,QACL,EAAA,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,IAAM,EAAe,CAAA,EAAA,EAAA,oBAAiB,CACtC,GAAI,GAAc,SAAS,IAAK,CAI9B,GAHM,CAAE,cAAa,eAAc,CAAG,EAClC,CAAE,YAAa,EAAQ,aAAc,EAAa,IAAM,EACxD,CAAE,YAAa,GAAgB,KAAM,aAAc,EAAe,EAAa,WAAa,IAAM,EAChGD,EAAmC,CACvC,aACA,SACA,WACA,OAAQ,SACR,cACA,cACD,EAED,AADA,EAAa,iBAAiB,IAAI,EAAuB,EAAgB,CACzE,KAAM,GAAY,oBAAoB,EAAgB,AACvD,CACF,EAKD,IAAA,EAAe"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"uJAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,sBAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAA,iBAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,gBAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCTD,MARa,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAA,qBAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe,EAAA"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,98 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { Sequelize } from "sequelize-typescript";
|
|
4
|
-
import RabbitMq from "@autofleet/rabbit";
|
|
5
|
-
import { LoggerInstanceManager } from "@autofleet/logger";
|
|
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-CC0vE16d.cjs";
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
6
3
|
|
|
7
|
-
//#region src/types.d.ts
|
|
8
|
-
type AuditLoggerOptions = {
|
|
9
|
-
rabbit: RabbitMq;
|
|
10
|
-
sequelize: Sequelize;
|
|
11
|
-
logger: LoggerInstanceManager;
|
|
12
|
-
router?: IRouter;
|
|
13
|
-
excludeModels?: string[];
|
|
14
|
-
entityScopedModelMap?: {
|
|
15
|
-
[modelName: string]: ModelStatic<Model>;
|
|
16
|
-
};
|
|
17
|
-
};
|
|
18
|
-
interface AuditLogContext {
|
|
19
|
-
entityType: string;
|
|
20
|
-
entityId?: string;
|
|
21
|
-
action: string;
|
|
22
|
-
performedBy: string;
|
|
23
|
-
endpoint: string;
|
|
24
|
-
method: string;
|
|
25
|
-
actionOrigin?: string;
|
|
26
|
-
}
|
|
27
|
-
interface AuditLogRow {
|
|
28
|
-
property: string;
|
|
29
|
-
previousValue: any;
|
|
30
|
-
newValue: any;
|
|
31
|
-
}
|
|
32
|
-
interface AuditLogPayload {
|
|
33
|
-
entityType: string;
|
|
34
|
-
entityId: string;
|
|
35
|
-
rows: AuditLogRow[];
|
|
36
|
-
}
|
|
37
|
-
declare enum Action {
|
|
38
|
-
CREATE = "create",
|
|
39
|
-
BULK_CREATE = "bulk-create",
|
|
40
|
-
BULK_EDIT = "bulk-edit",
|
|
41
|
-
DELETE = "delete",
|
|
42
|
-
UPDATE = "update",
|
|
43
|
-
CANCEL = "cancel",
|
|
44
|
-
FAIL = "fail",
|
|
45
|
-
UNASSIGN = "unassign",
|
|
46
|
-
BULK_ASSIGN = "bulk-assign",
|
|
47
|
-
REASSIGN = "reassign",
|
|
48
|
-
DISPATCH = "dispatch",
|
|
49
|
-
BULK_DISPATCH = "bulk-dispatch",
|
|
50
|
-
BULK_UPSERT = "bulk-upsert",
|
|
51
|
-
UPSERT = "upsert",
|
|
52
|
-
JOIN = "join",
|
|
53
|
-
MOVE = "move",
|
|
54
|
-
REOPTIMIZATION = "reoptimization",
|
|
55
|
-
}
|
|
56
|
-
declare enum EntityType {
|
|
57
|
-
RIDE = "Ride",
|
|
58
|
-
VEHICLE = "Vehicle",
|
|
59
|
-
DRIVER = "Driver",
|
|
60
|
-
PRICE_CALCULATION = "PriceCalculation",
|
|
61
|
-
}
|
|
62
|
-
declare const enum ActionOrigin {
|
|
63
|
-
USER = "user",
|
|
64
|
-
AUTOMATION = "automation",
|
|
65
|
-
} //#endregion
|
|
66
|
-
//#region src/audit-logger.d.ts
|
|
67
|
-
declare class AuditLogger {
|
|
68
|
-
private rabbit;
|
|
69
|
-
private sequelize;
|
|
70
|
-
private logger;
|
|
71
|
-
private excludeModels;
|
|
72
|
-
constructor(options: AuditLoggerOptions);
|
|
73
|
-
registerHooks(): void;
|
|
74
|
-
sendAuditLogContext(context: AuditLogContext): Promise<void>;
|
|
75
|
-
private sendAuditLogRows;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
//#endregion
|
|
79
|
-
//#region src/const.d.ts
|
|
80
|
-
declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
|
|
81
|
-
declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
|
|
82
|
-
declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
|
|
83
|
-
declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
|
|
84
|
-
|
|
85
|
-
//#endregion
|
|
86
4
|
//#region src/index.d.ts
|
|
87
5
|
declare const enableAuditing: (options: AuditLoggerOptions) => void;
|
|
88
6
|
declare const setAuditContext: (entityType: string, action: string) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
89
|
-
declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, {
|
|
90
|
-
userId,
|
|
91
|
-
automationId
|
|
92
|
-
}: {
|
|
93
|
-
userId: string;
|
|
94
|
-
automationId: string;
|
|
95
|
-
}) => Promise<void>;
|
|
96
7
|
|
|
97
8
|
//#endregion
|
|
98
9
|
export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,98 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { Model, ModelStatic } from "sequelize";
|
|
4
|
-
import { Sequelize } from "sequelize-typescript";
|
|
5
|
-
import RabbitMq from "@autofleet/rabbit";
|
|
1
|
+
import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DrgE261l.js";
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
6
3
|
|
|
7
|
-
//#region src/types.d.ts
|
|
8
|
-
type AuditLoggerOptions = {
|
|
9
|
-
rabbit: RabbitMq;
|
|
10
|
-
sequelize: Sequelize;
|
|
11
|
-
logger: LoggerInstanceManager;
|
|
12
|
-
router?: IRouter;
|
|
13
|
-
excludeModels?: string[];
|
|
14
|
-
entityScopedModelMap?: {
|
|
15
|
-
[modelName: string]: ModelStatic<Model>;
|
|
16
|
-
};
|
|
17
|
-
};
|
|
18
|
-
interface AuditLogContext {
|
|
19
|
-
entityType: string;
|
|
20
|
-
entityId?: string;
|
|
21
|
-
action: string;
|
|
22
|
-
performedBy: string;
|
|
23
|
-
endpoint: string;
|
|
24
|
-
method: string;
|
|
25
|
-
actionOrigin?: string;
|
|
26
|
-
}
|
|
27
|
-
interface AuditLogRow {
|
|
28
|
-
property: string;
|
|
29
|
-
previousValue: any;
|
|
30
|
-
newValue: any;
|
|
31
|
-
}
|
|
32
|
-
interface AuditLogPayload {
|
|
33
|
-
entityType: string;
|
|
34
|
-
entityId: string;
|
|
35
|
-
rows: AuditLogRow[];
|
|
36
|
-
}
|
|
37
|
-
declare enum Action {
|
|
38
|
-
CREATE = "create",
|
|
39
|
-
BULK_CREATE = "bulk-create",
|
|
40
|
-
BULK_EDIT = "bulk-edit",
|
|
41
|
-
DELETE = "delete",
|
|
42
|
-
UPDATE = "update",
|
|
43
|
-
CANCEL = "cancel",
|
|
44
|
-
FAIL = "fail",
|
|
45
|
-
UNASSIGN = "unassign",
|
|
46
|
-
BULK_ASSIGN = "bulk-assign",
|
|
47
|
-
REASSIGN = "reassign",
|
|
48
|
-
DISPATCH = "dispatch",
|
|
49
|
-
BULK_DISPATCH = "bulk-dispatch",
|
|
50
|
-
BULK_UPSERT = "bulk-upsert",
|
|
51
|
-
UPSERT = "upsert",
|
|
52
|
-
JOIN = "join",
|
|
53
|
-
MOVE = "move",
|
|
54
|
-
REOPTIMIZATION = "reoptimization",
|
|
55
|
-
}
|
|
56
|
-
declare enum EntityType {
|
|
57
|
-
RIDE = "Ride",
|
|
58
|
-
VEHICLE = "Vehicle",
|
|
59
|
-
DRIVER = "Driver",
|
|
60
|
-
PRICE_CALCULATION = "PriceCalculation",
|
|
61
|
-
}
|
|
62
|
-
declare const enum ActionOrigin {
|
|
63
|
-
USER = "user",
|
|
64
|
-
AUTOMATION = "automation",
|
|
65
|
-
} //#endregion
|
|
66
|
-
//#region src/audit-logger.d.ts
|
|
67
|
-
declare class AuditLogger {
|
|
68
|
-
private rabbit;
|
|
69
|
-
private sequelize;
|
|
70
|
-
private logger;
|
|
71
|
-
private excludeModels;
|
|
72
|
-
constructor(options: AuditLoggerOptions);
|
|
73
|
-
registerHooks(): void;
|
|
74
|
-
sendAuditLogContext(context: AuditLogContext): Promise<void>;
|
|
75
|
-
private sendAuditLogRows;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
//#endregion
|
|
79
|
-
//#region src/const.d.ts
|
|
80
|
-
declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
|
|
81
|
-
declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
|
|
82
|
-
declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
|
|
83
|
-
declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
|
|
84
|
-
|
|
85
|
-
//#endregion
|
|
86
4
|
//#region src/index.d.ts
|
|
87
5
|
declare const enableAuditing: (options: AuditLoggerOptions) => void;
|
|
88
6
|
declare const setAuditContext: (entityType: string, action: string) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
89
|
-
declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, {
|
|
90
|
-
userId,
|
|
91
|
-
automationId
|
|
92
|
-
}: {
|
|
93
|
-
userId: string;
|
|
94
|
-
automationId: string;
|
|
95
|
-
}) => Promise<void>;
|
|
96
7
|
|
|
97
8
|
//#endregion
|
|
98
9
|
export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
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-CJByaCJF.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";async 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)=>(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/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["logger: LoggerInstanceManager","action: string","fields: string[]","instance: Model","options: CreateOptions<any> | InstanceUpdateOptions<any>","changedFields: string[]","property: string","options: AuditLoggerOptions","payload: AuditLogPayload","context: AuditLogContext","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction","auditLogContext: AuditLogContext","endpoint: string"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/audit-api.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable no-shadow */\nimport 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';\n\nexport type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: string]: ModelStatic<Model> };\n};\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string;\n endpoint: string;\n method: string;\n actionOrigin?: string;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: any;\n newValue: any;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: 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 Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger(null);\nexport default logger;\n","import 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 { isEqual } from 'lodash';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action,\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) => {\n if ([null, undefined].includes(field)) {\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).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => !ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT[action];\n\nconst filterOutEmptyFields = (fields: string[], instance) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions<any> | InstanceUpdateOptions<any>) => {\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) => {\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);\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)) && !isEqual(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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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 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 try {\n const auditContext = getAuditContext();\n if (!auditContext) {\n return;\n }\n if (auditContext?.entityType?.toLowerCase() === modelName?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = (instance as any).id;\n }\n const changedFieldsRows = getChangedFieldsRows(instance, options);\n const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);\n const payload: AuditLogPayload = {\n entityType: modelName,\n entityId: (instance as any).id,\n rows: [...changedFieldsRows, ...changedCustomFieldsRows],\n };\n this.sendAuditLogRows(payload);\n } catch (error) {\n this.logger.error('Failed to send audit log rows', error);\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 { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from './audit-ms';\nimport { AuditLoggerOptions } from './types';\n\nexport default async ({\n router,\n logger,\n entityScopedModelMap,\n}: AuditLoggerOptions): Promise<void> => {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n};\n","import { getCurrentPayload as getCurrentTrace, getUser } from '@autofleet/zehut';\nimport type { Request, Response, NextFunction } from 'express';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport addAuditApi from './audit-api';\nimport logger from './logger';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return;\n }\n auditLogger = new AuditLogger(options);\n addAuditApi(options);\n auditLogger.registerHooks();\n};\n\nexport const setAuditContext = (\n entityType: string,\n action: string,\n) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return next();\n }\n const user = getUser();\n const automationId = req.headers[AUTOMATION_ID_HEADER] as string | undefined;\n const { performedBy, actionOrigin } = user?.id\n ? { performedBy: user.id, actionOrigin: ActionOrigin.USER }\n : { performedBy: automationId ?? null, actionOrigin: automationId ? ActionOrigin.AUTOMATION : null };\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint: req.url,\n method: req.method,\n performedBy,\n actionOrigin,\n };\n\n const currentTrace = getCurrentTrace();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\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 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 } else {\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n }\n } catch (err) {\n logger.error('coudln\\'t set audit context', err);\n }\n return next();\n};\n\nexport const setRabbitAuditContext = (\n entityType: string,\n action: string,\n) => 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 currentTrace = getCurrentTrace();\n if (currentTrace?.context?.get) {\n const { performedBy, actionOrigin } = userId\n ? { performedBy: userId, actionOrigin: ActionOrigin.USER }\n : { performedBy: automationId ?? null, actionOrigin: automationId ? ActionOrigin.AUTOMATION : null };\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method: 'rabbit',\n performedBy,\n actionOrigin,\n };\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n await auditLogger.sendAuditLogContext(auditLogContext);\n }\n};\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"sQAiEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA,YAAA,cACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,KAAA,OACA,EAAA,eAAA,kBACD,EAAA,CAAA,EAAA,CAEW,kBAAA,SAAA,EAAL,QACL,EAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,oBACD,EAAA,CAAA,EAAA,CAEiB,kBAAA,SAAA,EAAX,QACL,EAAA,KAAA,OACA,EAAA,WAAA,cACD,EAAA,CAAA,EAAA,CElED,MDFa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCD9BA,EAAgC,EAAO,KAAK,CAClD,IAAA,EAAe,ECwDf,MA9CM,EAAyB,eAEzB,EAAkB,IAAM,CAE5B,IADM,EAAe,GAAiB,CAChC,EAAe,GAAc,kBAAkB,IAAI,EAAsB,CAC/E,OAAO,CACR,EAEK,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WA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I,IACd,OAAQ,EAAI,OACZ,cACA,cACD,EAEK,EAAe,GAAiB,CACtC,EAAa,iBAAiB,IAAI,EAAuB,EAAgB,CAEzE,IAAM,EAA2B,SAAY,CAI3C,AAHA,EAAI,IAAI,SAAU,EAAyB,CAC3C,EAAI,IAAI,QAAS,EAAyB,CAC1C,EAAI,IAAI,QAAS,EAAyB,CAC1C,KAAM,GAAY,oBAAoB,EAAgB,AACvD,EACD,AAAK,EAAmB,EAAO,EAG7B,EAAI,KAAK,SAAU,EAAyB,CAC5C,EAAI,KAAK,QAAS,EAAyB,CAC3C,EAAI,KAAK,QAAS,EAAyB,EAJ3C,KAAM,GAAY,oBAAoB,EAAgB,AAMzD,OAAQ,EAAK,CACZ,EAAO,MAAM,6BAA+B,EAAI,AACjD,CACD,MAAO,IAAM,AACd,EAEY,EAAwB,CACnCL,EACAC,IACG,MAAOK,EAAkB,CAAE,SAAQ,eAAuD,GAAoB,CACjH,GAAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAe,GAAiB,CACtC,GAAI,GAAc,SAAS,IAAK,CAI9B,GAHM,CAAE,cAAa,eAAc,CAAG,EAClC,CAAE,YAAa,EAAQ,aAAc,EAAa,IAAM,EACxD,CAAE,YAAa,GAAgB,KAAM,aAAc,EAAe,EAAa,WAAa,IAAM,EAChGD,EAAmC,CACvC,aACA,SACA,WACA,OAAQ,SACR,cACA,cACD,EAED,AADA,EAAa,iBAAiB,IAAI,EAAuB,EAAgB,CACzE,KAAM,GAAY,oBAAoB,EAAgB,AACvD,CACF,EAKD,IAAA,EAAe"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0ZAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,GAAY,IAAI,EAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,GAAY,IAAI,EAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCTD,MARa,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autofleet/shtinker",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -12,9 +12,19 @@
|
|
|
12
12
|
"default": "./dist/index.js"
|
|
13
13
|
},
|
|
14
14
|
"require": {
|
|
15
|
-
"types": "./dist/index.
|
|
15
|
+
"types": "./dist/index.d.cts",
|
|
16
16
|
"default": "./dist/index.cjs"
|
|
17
17
|
}
|
|
18
|
+
},
|
|
19
|
+
"./fastify": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/fastify.d.ts",
|
|
22
|
+
"default": "./dist/fastify.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/fastify.d.cts",
|
|
26
|
+
"default": "./dist/fastify.cjs"
|
|
27
|
+
}
|
|
18
28
|
}
|
|
19
29
|
},
|
|
20
30
|
"scripts": {
|
|
@@ -28,11 +38,10 @@
|
|
|
28
38
|
"node": ">=18"
|
|
29
39
|
},
|
|
30
40
|
"dependencies": {
|
|
31
|
-
"@autofleet/network": "^1.
|
|
32
|
-
"lodash": "^4.17.21"
|
|
41
|
+
"@autofleet/network": "^1.8.1"
|
|
33
42
|
},
|
|
34
43
|
"devDependencies": {
|
|
35
|
-
"@autofleet/zehut": "^4.
|
|
44
|
+
"@autofleet/zehut": "^4.2.2",
|
|
36
45
|
"@types/express": "^4.17.17",
|
|
37
46
|
"@types/node": "^18.11.19",
|
|
38
47
|
"@typescript-eslint/eslint-plugin": "^4.8.1",
|
|
@@ -40,6 +49,7 @@
|
|
|
40
49
|
"eslint": "^7.13.0",
|
|
41
50
|
"eslint-config-airbnb-typescript": "^12.0.0",
|
|
42
51
|
"eslint-plugin-import": "^2.22.1",
|
|
52
|
+
"fastify": "^5.4.0",
|
|
43
53
|
"sequelize": "^6.37.6",
|
|
44
54
|
"sequelize-typescript": "^2.1.6",
|
|
45
55
|
"ts-node": "^10.9.1",
|
|
@@ -50,7 +60,7 @@
|
|
|
50
60
|
"peerDependencies": {
|
|
51
61
|
"@autofleet/errors": "^3",
|
|
52
62
|
"@autofleet/logger": "^4.2.1",
|
|
53
|
-
"@autofleet/rabbit": ">=
|
|
63
|
+
"@autofleet/rabbit": ">=5",
|
|
54
64
|
"@autofleet/zehut": "^4"
|
|
55
65
|
},
|
|
56
66
|
"author": "Autofleet",
|