piper-utils 1.1.65 → 1.1.67

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "piper-utils",
3
- "version": "1.1.65",
3
+ "version": "1.1.67",
4
4
  "description": "Utility library for Piper",
5
5
  "main": "bin/main.js",
6
6
  "scripts": {
@@ -0,0 +1,422 @@
1
+ import _ from 'lodash';
2
+ import Promise from 'bluebird';
3
+ import { getCurrentUser } from '../requestResponse/requestResponse.js';
4
+ import { accessRightsUtils, getCompanySettings } from '../database/dbUtils/queryStringUtils/accessRightsUtils.js';
5
+
6
+ /**
7
+ * @file Audit logging for Sequelize models. Each parent model gets a sibling
8
+ * `<ModelName>Audit` table that records every field-level change made through
9
+ * Sequelize hooks (afterCreate / afterUpsert / afterUpdate / afterDestroy).
10
+ *
11
+ * Typical wiring in a domain service:
12
+ *
13
+ * 1. At model `dbSetup` (one-time, at boot):
14
+ * `await attachAudit(MyModel);`
15
+ *
16
+ * 2. At the top of each route handler that mutates the model:
17
+ * `bindAuditRequest(event, businessId, [MyModel]);`
18
+ *
19
+ * 3. To list audit history for a record:
20
+ * `const filter = getAuditFilter(MyModel, id, { event, offset, limit });`
21
+ * `const audits = await findAll(getAuditModel(MyModel), filter);`
22
+ *
23
+ * Audit is **off by default** for any model whose request hasn't been bound —
24
+ * so cron lambdas, untouched endpoints, and unit tests will not write audit
25
+ * rows unless they explicitly opt in. The on/off switch comes from the
26
+ * `custom:SET.auditEnabled` JWT claim resolved by {@link getCompanySettings}.
27
+ *
28
+ * The user identity stamped on each row is read from the JWT via
29
+ * {@link getCurrentUser}; `changedByUser` stores `claims.email`. There is
30
+ * intentionally no foreign key back to a User table — domain services must
31
+ * not read across other services' databases.
32
+ */
33
+
34
+ /**
35
+ * Registry of `<ModelName>Audit` Sequelize models, keyed by parent model name.
36
+ * Populated by {@link attachAudit}. Exported for tests; do not mutate from app code.
37
+ *
38
+ * @type {Object<string, import('sequelize').ModelStatic<any>>}
39
+ */
40
+ export const auditModels = {};
41
+
42
+ /**
43
+ * Per-model per-request audit context, keyed by parent model name. Populated by
44
+ * {@link bindAuditRequest} or {@link bindAuditRequestForUser}. A model with no
45
+ * entry here (or with `auditEnabled === false`) will not write any audit rows.
46
+ * Exported for tests; do not mutate from app code.
47
+ *
48
+ * @type {Object<string, { user: { username: string, id?: number }, businessId: string|number, auditEnabled: boolean }>}
49
+ */
50
+ export const modelOptions = {};
51
+
52
+ const SENSITIVE_FIELDS_PATTERN = /"(token|password|secret|key|credential|auth|securityCode|cvv|pin|ssn)":\s*"[^"]*"/gi;
53
+
54
+ function getAuditSchema(model) {
55
+ const DataTypes = model.sequelize.Sequelize;
56
+ return {
57
+ field: { type: DataTypes.STRING, allowNull: false },
58
+ type: DataTypes.STRING,
59
+ valueOld: DataTypes.STRING,
60
+ valueNew: DataTypes.STRING,
61
+ changedByUser: { type: DataTypes.STRING, allowNull: false },
62
+ businessId: { type: DataTypes.STRING, allowNull: false }
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Internal hook factory. Returns the async function that Sequelize invokes on
68
+ * each create/upsert/update/destroy. Reads its per-request state from
69
+ * {@link modelOptions}; emits zero rows when audit is disabled for the model.
70
+ *
71
+ * Sensitive fields inside JSON values (token, password, secret, key,
72
+ * credential, auth, securityCode, cvv, pin, ssn) are masked as
73
+ * `***************` before being persisted. String values longer than 255
74
+ * characters are truncated.
75
+ *
76
+ * Exported only so tests can drive the hook directly. Application code should
77
+ * never call this — use {@link attachAudit}.
78
+ *
79
+ * @param {string} modelName name of the parent Sequelize model
80
+ * @returns {(modelInfo: any, options: { type?: string, transaction?: import('sequelize').Transaction }) => Promise<void>}
81
+ * the hook function Sequelize will call on each lifecycle event
82
+ */
83
+ function auditMe(modelName) {
84
+ return async (modelInfo, options) => {
85
+ if (_.isArray(modelInfo)) {
86
+ modelInfo = modelInfo[0];
87
+ }
88
+
89
+ const opts = modelOptions[modelName];
90
+ if (!opts || !opts.auditEnabled) {
91
+ return;
92
+ }
93
+
94
+ const auditModel = auditModels[modelName];
95
+
96
+ const writeAuditRow = async (field, type, valueOld, valueNew) => {
97
+ const data = {
98
+ field,
99
+ type,
100
+ valueOld: String(valueOld).substring(0, 255),
101
+ valueNew: String(valueNew).substring(0, 255),
102
+ businessId: opts.businessId,
103
+ changedByUser: opts.user.username
104
+ };
105
+ data[modelName + 'Id'] = modelInfo.dataValues.id;
106
+
107
+ const newOptions = {};
108
+ if (options.transaction) {
109
+ newOptions.transaction = options.transaction;
110
+ }
111
+ return auditModel.create(data, newOptions);
112
+ };
113
+
114
+ const checkAudit = async (field, type = 'INITIAL', valueOld, valueNew) => {
115
+ if (_.isEqual(valueOld, valueNew)) {
116
+ return;
117
+ }
118
+ if (_.isString(valueOld) && _.isString(valueNew)) {
119
+ type = 'INSERT';
120
+ }
121
+
122
+ if (_.isArray(valueOld) || _.isArray(valueNew)) {
123
+ let oldString = JSON.stringify(valueOld || []);
124
+ let newString = JSON.stringify(valueNew || []);
125
+ oldString = oldString.replace(SENSITIVE_FIELDS_PATTERN, '"$1":"***************"').substring(0, 255);
126
+ newString = newString.replace(SENSITIVE_FIELDS_PATTERN, '"$1":"***************"').substring(0, 255);
127
+ return writeAuditRow(field, 'UPDATE', oldString, newString);
128
+ }
129
+
130
+ if (_.isObject(valueOld) || _.isObject(valueNew)) {
131
+ _.forEach(valueOld, (valueSub, keySub) => {
132
+ checkAudit(field + ' ' + keySub, 'DELETED', valueSub || '', (valueNew || {})[keySub] || '');
133
+ });
134
+ _.forEach(valueNew, (valueSub, keySub) => {
135
+ checkAudit(field + ' ' + keySub, 'INSERT', (valueOld || {})[keySub] || '', valueSub || '');
136
+ });
137
+ return;
138
+ }
139
+
140
+ return writeAuditRow(field, type, valueOld, valueNew);
141
+ };
142
+
143
+ return Promise.map([...modelInfo._changed], async (field) => {
144
+ const valueOld = modelInfo._previousDataValues[field] || '';
145
+ const valueNew = modelInfo.dataValues[field] || '';
146
+ await checkAudit(field, options.type, valueOld, valueNew);
147
+ });
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Define a sibling `<ModelName>Audit` table for the given Sequelize model and
153
+ * wire the four lifecycle hooks (`afterCreate`, `afterUpsert`, `afterUpdate`,
154
+ * `afterDestroy`) that record changes into it.
155
+ *
156
+ * Call this **once per model at boot time** from inside the model's
157
+ * `dbSetup()` function. It is idempotent — calling it again for a model that
158
+ * already has an audit table attached is a no-op.
159
+ *
160
+ * The audit table has no foreign key into any user table; the username of the
161
+ * person who made the change is stamped onto each row from the JWT (set by
162
+ * {@link bindAuditRequest}). This keeps the audit util portable across domain
163
+ * services that own different user models.
164
+ *
165
+ * @example
166
+ * // src/customer/customer.js
167
+ * Customer.dbSetup = async function () {
168
+ * await attachAudit(Customer);
169
+ * };
170
+ *
171
+ * @param {import('sequelize').ModelStatic<any>} model the Sequelize model to audit
172
+ * @returns {Promise<void>} resolves when the audit table's `sync()` completes
173
+ * @see {@link bindAuditRequest} - per-request setup that turns audit on
174
+ * @see {@link getAuditModel} - retrieve the audit model from the parent
175
+ * @see {@link getAuditFilter} - build a filter for an audit history query
176
+ */
177
+ export async function attachAudit(model) {
178
+ if (auditModels[model.name]) {
179
+ return;
180
+ }
181
+
182
+ const auditModel = model.sequelize.define(model.name + 'Audit', getAuditSchema(model), {
183
+ updatedAt: false,
184
+ freezeTableName: true
185
+ });
186
+ auditModel.belongsTo(model, {
187
+ foreignKey: { allowNull: true },
188
+ onDelete: 'SET NULL'
189
+ });
190
+ auditModels[model.name] = auditModel;
191
+
192
+ model.addHook('afterCreate', auditMe(model.name));
193
+ model.addHook('afterUpsert', auditMe(model.name));
194
+ model.addHook('afterUpdate', auditMe(model.name));
195
+ model.addHook('afterDestroy', auditMe(model.name));
196
+
197
+ return auditModel.sync();
198
+ }
199
+
200
+ /**
201
+ * Bind per-request audit context for one or more models. Call this **once at
202
+ * the top of each route handler** that mutates an audited model.
203
+ *
204
+ * Resolves the acting user from the JWT claims on the event
205
+ * (via {@link getCurrentUser}) and reads the company `auditEnabled` flag from
206
+ * the `custom:SET` claim (via {@link getCompanySettings}). If the company has
207
+ * `auditEnabled: false` then no rows will be written for the bound models on
208
+ * this request.
209
+ *
210
+ * Audit is **off by default** for any model that has not been bound this
211
+ * request — a route that omits this call writes no audit rows.
212
+ *
213
+ * @example
214
+ * // src/customer/customerRoutes.js
215
+ * export async function updateCustomer(event) {
216
+ * checkModule('customer', event);
217
+ * const businessId = checkWriteAccess(event);
218
+ * bindAuditRequest(event, businessId, [Customer]);
219
+ * // ...mutate Customer here; rows are written automatically by hooks
220
+ * }
221
+ *
222
+ * @example
223
+ * // Bind several models in one call when a handler touches more than one
224
+ * bindAuditRequest(event, businessId, [Order, Payment, Receivable]);
225
+ *
226
+ * @param {import('aws-lambda').APIGatewayProxyEvent} event API Gateway event
227
+ * with `requestContext.authorizer.claims` (must include `email` and
228
+ * optionally `custom:UID`, `custom:SET`)
229
+ * @param {string|number} businessId business id this request acts on; stamped
230
+ * onto every audit row written for the bound models
231
+ * @param {Array<import('sequelize').ModelStatic<any>>} models Sequelize models
232
+ * to enable audit on for the duration of this request
233
+ * @returns {void}
234
+ * @see {@link bindAuditRequestForUser} - the equivalent for non-JWT contexts
235
+ * (webhooks, integration crons, Cognito triggers)
236
+ * @see {@link attachAudit} - one-time setup that creates the audit table
237
+ */
238
+ export function bindAuditRequest(event, businessId, models) {
239
+ const user = getCurrentUser(event);
240
+ const auditEnabled = !!(getCompanySettings(event) || {}).auditEnabled;
241
+ _.forEach(models, (model) => {
242
+ modelOptions[model.name] = { user, businessId, auditEnabled };
243
+ });
244
+ }
245
+
246
+ /**
247
+ * Bind per-request audit context for **system-driven flows** that do not carry
248
+ * an API Gateway JWT — for example, payment-gateway webhooks, integration
249
+ * crons (QuickBooks/Inbox/etc.), Cognito triggers, or batch jobs.
250
+ *
251
+ * Use {@link bindAuditRequest} instead whenever you have a JWT-authenticated
252
+ * API event; that path automatically resolves the user and the company's
253
+ * `auditEnabled` flag from claims.
254
+ *
255
+ * @example
256
+ * // payment webhook from the gateway — no JWT, but we still want audit
257
+ * import { systemUser } from '../user/user.js';
258
+ *
259
+ * export async function webhook(event) {
260
+ * const businessId = event.queryStringParameters.businessId;
261
+ * bindAuditRequestForUser(systemUser, businessId, [Order, Payment]);
262
+ * // ...mutate Order/Payment; audit rows are written by hooks
263
+ * }
264
+ *
265
+ * @example
266
+ * // turn audit OFF explicitly for a system flow that should not be audited
267
+ * bindAuditRequestForUser(systemUser, businessId, [Order], { auditEnabled: false });
268
+ *
269
+ * @param {{ username: string, id?: number }} user identity stamped onto each
270
+ * audit row's `changedByUser` field. Conventionally the `systemUser`
271
+ * constant exported from your service's user model
272
+ * @param {string|number} businessId business id this flow is acting on
273
+ * @param {Array<import('sequelize').ModelStatic<any>>} models Sequelize models
274
+ * to enable audit on
275
+ * @param {{ auditEnabled?: boolean }} [opts] when `auditEnabled` is `false`,
276
+ * binds context but suppresses writes; defaults to `true`
277
+ * @returns {void}
278
+ * @see {@link bindAuditRequest} - the JWT-driven equivalent for API handlers
279
+ */
280
+ export function bindAuditRequestForUser(user, businessId, models, opts = {}) {
281
+ const auditEnabled = opts.auditEnabled !== false;
282
+ _.forEach(models, (model) => {
283
+ modelOptions[model.name] = { user, businessId, auditEnabled };
284
+ });
285
+ }
286
+
287
+ /**
288
+ * Get the `<ModelName>Audit` Sequelize model that {@link attachAudit} created
289
+ * for a parent model. Returns `undefined` if audit was never attached.
290
+ *
291
+ * @example
292
+ * const audits = await findAll(getAuditModel(Customer), filter);
293
+ *
294
+ * @param {import('sequelize').ModelStatic<any>} model parent Sequelize model
295
+ * @returns {import('sequelize').ModelStatic<any> | undefined} the audit model,
296
+ * or `undefined` if {@link attachAudit} has not been called for this model
297
+ * @see {@link getAuditFilter} - companion filter builder for history queries
298
+ */
299
+ export function getAuditModel(model) {
300
+ return auditModels[model.name];
301
+ }
302
+
303
+ /**
304
+ * Build a Sequelize `findAll`-style filter for an audit-history query, scoped
305
+ * to the businesses the caller is allowed to read (resolved from
306
+ * {@link accessRightsUtils}).
307
+ *
308
+ * The returned filter joins the parent model so callers can render `oldValue`
309
+ * → `newValue` rows in the UI alongside the parent record.
310
+ *
311
+ * @example
312
+ * // GET /customer/{id}/audit
313
+ * export async function getCustomerAudit(event) {
314
+ * bindAuditRequest(event, userDefaultBid(event), [Customer]);
315
+ * const filter = getAuditFilter(Customer, event.pathParameters.id, {
316
+ * event,
317
+ * offset: 0,
318
+ * limit: 10
319
+ * });
320
+ * const audits = await findAll(getAuditModel(Customer), filter);
321
+ * return success(audits);
322
+ * }
323
+ *
324
+ * @param {import('sequelize').ModelStatic<any>} modelToFilter the parent model
325
+ * whose history is being fetched
326
+ * @param {string|number} id parent record id
327
+ * @param {{ event: import('aws-lambda').APIGatewayProxyEvent, offset?: number, limit?: number }} options
328
+ * `event` is required (drives business-id scoping); `offset` and `limit`
329
+ * are pagination passthroughs
330
+ * @returns {{ where: Object, include: Array<{ model: Object }>, order: Array, offset?: number, limit?: number }}
331
+ * a Sequelize `findAll`-compatible filter
332
+ * @see {@link getAuditModel} - call to get the audit model to query against
333
+ */
334
+ export function getAuditFilter(modelToFilter, id, options) {
335
+ const businessIds = accessRightsUtils(options.event);
336
+ const filter = {
337
+ where: {
338
+ businessId: businessIds
339
+ },
340
+ include: [{
341
+ model: modelToFilter
342
+ }],
343
+ order: [
344
+ ['createdAt', 'DESC']
345
+ ]
346
+ };
347
+ filter.where[modelToFilter.name + 'Id'] = id;
348
+
349
+ return { ...filter, ...options };
350
+ }
351
+
352
+ /**
353
+ * Decrement an integer field on a Sequelize instance and write a matching
354
+ * audit row in the same call. Useful for inventory adjustments and other
355
+ * counter-style fields where Sequelize's plain `model.decrement()` would
356
+ * bypass the `afterUpdate` hook.
357
+ *
358
+ * The acting user and businessId come from whatever
359
+ * {@link bindAuditRequest} / {@link bindAuditRequestForUser} was called for
360
+ * this request. If audit is disabled for the model, the decrement still
361
+ * happens but no audit row is written.
362
+ *
363
+ * @example
364
+ * // release inventory on order release
365
+ * await decrementWithAudit('inventory', inventoryEntry, 'quantity', {
366
+ * by: item.quantity,
367
+ * transaction: t
368
+ * });
369
+ *
370
+ * @param {string} modelName name of the parent model (e.g. `'inventory'`)
371
+ * @param {import('sequelize').Model} model the Sequelize instance to mutate
372
+ * @param {string} field the integer/decimal field to decrement
373
+ * @param {{ by?: number, transaction?: import('sequelize').Transaction }} args
374
+ * passed straight through to Sequelize's `decrement()`; transaction is also
375
+ * propagated to the audit write
376
+ * @returns {Promise<import('sequelize').Model>} the updated instance (with
377
+ * `_changed` set on it so internal hooks can observe the change)
378
+ * @see {@link incrementWithAudit} - the +1 counterpart
379
+ */
380
+ export async function decrementWithAudit(modelName, model, field, args) {
381
+ const r = await model.decrement(field, args);
382
+ r._changed = [field];
383
+ const options = {};
384
+ if (args.transaction) {
385
+ options.transaction = args.transaction;
386
+ }
387
+ await auditMe(modelName)(r, options);
388
+ return r;
389
+ }
390
+
391
+ /**
392
+ * Increment an integer field on a Sequelize instance and write a matching
393
+ * audit row in the same call. The mirror of {@link decrementWithAudit}.
394
+ *
395
+ * @example
396
+ * // restock from a receivable
397
+ * await incrementWithAudit('inventory', inventoryEntry, 'quantity', {
398
+ * by: item.quantity,
399
+ * transaction: t
400
+ * });
401
+ *
402
+ * @param {string} modelName name of the parent model (e.g. `'inventory'`)
403
+ * @param {import('sequelize').Model} model the Sequelize instance to mutate
404
+ * @param {string} field the integer/decimal field to increment
405
+ * @param {{ by?: number, transaction?: import('sequelize').Transaction }} args
406
+ * passed straight through to Sequelize's `increment()`; transaction is also
407
+ * propagated to the audit write
408
+ * @returns {Promise<import('sequelize').Model>} the updated instance
409
+ * @see {@link decrementWithAudit} - the -1 counterpart
410
+ */
411
+ export async function incrementWithAudit(modelName, model, field, args) {
412
+ const r = await model.increment(field, args);
413
+ r._changed = [field];
414
+ const options = {};
415
+ if (args.transaction) {
416
+ options.transaction = args.transaction;
417
+ }
418
+ await auditMe(modelName)(r, options);
419
+ return r;
420
+ }
421
+
422
+ export { auditMe };