shuttlepro-shared 1.5.49 → 1.5.50
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/functions.js +2 -0
- package/models/SettingsAuditLog.js +63 -0
- package/models.js +2 -0
- package/package.json +1 -1
- package/utils/settingsAudit.js +260 -0
package/functions.js
CHANGED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const mongoose = require("mongoose");
|
|
2
|
+
const { Schema } = mongoose;
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Who changed which setting, and how (collection `settingsauditlogs`).
|
|
6
|
+
* One row per save that changed something: automations, chatbots, AI bot,
|
|
7
|
+
* members, roles, workspace settings, integrations, and so on.
|
|
8
|
+
*
|
|
9
|
+
* Rows are only ever added, never edited or deleted.
|
|
10
|
+
* module / action / actor.type are plain strings on purpose (no enum): a new
|
|
11
|
+
* value must never make an older installed copy of this package reject the
|
|
12
|
+
* write. The known values are listed in utils/settingsAudit.js.
|
|
13
|
+
*/
|
|
14
|
+
const changeSchema = new Schema(
|
|
15
|
+
{
|
|
16
|
+
field: { type: String, default: "" },
|
|
17
|
+
label: { type: String, default: "" },
|
|
18
|
+
from: { type: Schema.Types.Mixed, default: null },
|
|
19
|
+
to: { type: Schema.Types.Mixed, default: null },
|
|
20
|
+
},
|
|
21
|
+
{ _id: false }
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
const settingsAuditLogSchema = new Schema(
|
|
25
|
+
{
|
|
26
|
+
workspaceId: { type: Schema.Types.ObjectId, ref: "Workspace", default: null },
|
|
27
|
+
actor: {
|
|
28
|
+
userId: { type: Schema.Types.ObjectId, ref: "User", default: null },
|
|
29
|
+
name: { type: String, default: "" },
|
|
30
|
+
email: { type: String, default: "" },
|
|
31
|
+
role: { type: String, default: "" },
|
|
32
|
+
type: { type: String, default: "user" }, // user | super_admin | system
|
|
33
|
+
},
|
|
34
|
+
module: { type: String, required: true },
|
|
35
|
+
action: { type: String, required: true },
|
|
36
|
+
target: {
|
|
37
|
+
type: { type: String, default: "" },
|
|
38
|
+
id: { type: String, default: "" },
|
|
39
|
+
name: { type: String, default: "" },
|
|
40
|
+
},
|
|
41
|
+
changes: { type: [changeSchema], default: [] },
|
|
42
|
+
summary: { type: String, default: "" },
|
|
43
|
+
source: {
|
|
44
|
+
app: { type: String, default: "" },
|
|
45
|
+
method: { type: String, default: "" },
|
|
46
|
+
route: { type: String, default: "" },
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
timestamps: { createdAt: true, updatedAt: false },
|
|
51
|
+
versionKey: false,
|
|
52
|
+
collection: "settingsauditlogs",
|
|
53
|
+
}
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
settingsAuditLogSchema.index({ workspaceId: 1, createdAt: -1 });
|
|
57
|
+
settingsAuditLogSchema.index({ workspaceId: 1, module: 1, createdAt: -1 });
|
|
58
|
+
settingsAuditLogSchema.index({ workspaceId: 1, "actor.userId": 1, createdAt: -1 });
|
|
59
|
+
settingsAuditLogSchema.index({ "target.id": 1, createdAt: -1 });
|
|
60
|
+
|
|
61
|
+
const SettingsAuditLog = mongoose.model("SettingsAuditLog", settingsAuditLogSchema);
|
|
62
|
+
|
|
63
|
+
module.exports = SettingsAuditLog;
|
package/models.js
CHANGED
|
@@ -112,6 +112,7 @@ const Workspace = require("./models/Workspace");
|
|
|
112
112
|
const Shop = require("./models/Shop");
|
|
113
113
|
const Call = require("./models/Call");
|
|
114
114
|
const Webhook = require("./models/Webhook");
|
|
115
|
+
const SettingsAuditLog = require("./models/SettingsAuditLog");
|
|
115
116
|
|
|
116
117
|
module.exports = {
|
|
117
118
|
Activity,
|
|
@@ -228,4 +229,5 @@ module.exports = {
|
|
|
228
229
|
Shop,
|
|
229
230
|
Call,
|
|
230
231
|
Webhook,
|
|
232
|
+
SettingsAuditLog,
|
|
231
233
|
};
|
package/package.json
CHANGED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings change log helpers (collection `settingsauditlogs`).
|
|
3
|
+
*
|
|
4
|
+
* const { recordSettingsChange, actorFromRequest } = sharedFunctions;
|
|
5
|
+
* await recordSettingsChange({
|
|
6
|
+
* workspaceId, actor: actorFromRequest(req),
|
|
7
|
+
* module: "automation", action: "updated",
|
|
8
|
+
* target: { type: "automation", id: doc._id, name: doc.name },
|
|
9
|
+
* before: oldDoc, after: newDoc,
|
|
10
|
+
* source: { app: "conversationApp", method: req.method, route: req.originalUrl },
|
|
11
|
+
* });
|
|
12
|
+
*
|
|
13
|
+
* recordSettingsChange never throws: a failed log write must not fail the save it describes.
|
|
14
|
+
*/
|
|
15
|
+
const { Types } = require("mongoose");
|
|
16
|
+
const SettingsAuditLog = require("../models/SettingsAuditLog");
|
|
17
|
+
const { getBodyFromDecodeToken } = require("./index");
|
|
18
|
+
const logger = require("./logger");
|
|
19
|
+
|
|
20
|
+
// Known values (the schema accepts any string; these keep callers consistent).
|
|
21
|
+
const SETTINGS_AUDIT_MODULES = Object.freeze({
|
|
22
|
+
AUTOMATION: "automation",
|
|
23
|
+
CHATBOT: "chatbot",
|
|
24
|
+
AI_BOT: "ai_bot",
|
|
25
|
+
MEMBER: "member",
|
|
26
|
+
ROLE: "role",
|
|
27
|
+
PERMISSION: "permission",
|
|
28
|
+
WORKSPACE: "workspace",
|
|
29
|
+
SETTINGS: "settings",
|
|
30
|
+
SHIFT_KPI: "shift_kpi",
|
|
31
|
+
NOTIFICATION_SETTINGS: "notification_settings",
|
|
32
|
+
INTEGRATION: "integration",
|
|
33
|
+
ESCALATION: "escalation",
|
|
34
|
+
INBOX_SETUP: "inbox_setup",
|
|
35
|
+
ORDERS_SETUP: "orders_setup",
|
|
36
|
+
TASK_MANAGER_SETUP: "task_manager_setup",
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const SETTINGS_AUDIT_ACTIONS = Object.freeze({
|
|
40
|
+
CREATED: "created",
|
|
41
|
+
UPDATED: "updated",
|
|
42
|
+
ENABLED: "enabled",
|
|
43
|
+
DISABLED: "disabled",
|
|
44
|
+
DELETED: "deleted",
|
|
45
|
+
RESTORED: "restored",
|
|
46
|
+
CONNECTED: "connected",
|
|
47
|
+
DISCONNECTED: "disconnected",
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const ACTOR_TYPES = Object.freeze({
|
|
51
|
+
USER: "user",
|
|
52
|
+
SUPER_ADMIN: "super_admin",
|
|
53
|
+
SYSTEM: "system",
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const MASK = "[hidden]";
|
|
57
|
+
// Only string values under these names are masked, so toggles such as
|
|
58
|
+
// `chatbotTokenSaving: true` still show their real value.
|
|
59
|
+
const SECRET_NAME = /(api[_-]?key|secret|token|passw|private[_-]?key|access[_-]?key|credential|authorization|^key$)/i;
|
|
60
|
+
const IGNORED_FIELDS = new Set(["_id", "__v", "id", "createdAt", "updatedAt"]);
|
|
61
|
+
const MAX_DEPTH = 8;
|
|
62
|
+
const MAX_CHANGES = 200;
|
|
63
|
+
const MAX_VALUE_CHARS = 2000;
|
|
64
|
+
|
|
65
|
+
const plain = (value) => {
|
|
66
|
+
if (value === undefined) return undefined;
|
|
67
|
+
try {
|
|
68
|
+
return JSON.parse(JSON.stringify(value));
|
|
69
|
+
} catch (err) {
|
|
70
|
+
return String(value);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
75
|
+
const lastSegment = (path) => String(path).split(".").pop().replace(/\[.*\]$/, "");
|
|
76
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
77
|
+
|
|
78
|
+
const maskValue = (value, path) => {
|
|
79
|
+
if (value === undefined) return null;
|
|
80
|
+
if (typeof value === "string" && value !== "" && SECRET_NAME.test(lastSegment(path))) return MASK;
|
|
81
|
+
if (isObject(value) || Array.isArray(value)) {
|
|
82
|
+
const masked = Array.isArray(value)
|
|
83
|
+
? value.map((item) => maskValue(item, path))
|
|
84
|
+
: Object.fromEntries(Object.entries(value).map(([k, v]) => [k, maskValue(v, `${path}.${k}`)]));
|
|
85
|
+
const text = JSON.stringify(masked);
|
|
86
|
+
return text.length > MAX_VALUE_CHARS ? `<large value, ${text.length} chars>` : masked;
|
|
87
|
+
}
|
|
88
|
+
if (typeof value === "string" && value.length > MAX_VALUE_CHARS) {
|
|
89
|
+
return `${value.slice(0, MAX_VALUE_CHARS)}…`;
|
|
90
|
+
}
|
|
91
|
+
return value;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// Arrays of records with an _id (automation rules, ticket lists, ...) are matched
|
|
95
|
+
// item by item, so "rule X disabled" shows as one change instead of the whole array.
|
|
96
|
+
const itemKey = (item) => (isObject(item) && (item._id || item.id) ? String(item._id || item.id) : null);
|
|
97
|
+
const itemName = (item) =>
|
|
98
|
+
(isObject(item) && (item.name || item.title || item.label)) || itemKey(item) || "";
|
|
99
|
+
|
|
100
|
+
const walk = (before, after, path, label, out, depth) => {
|
|
101
|
+
if (out.length >= MAX_CHANGES || same(before, after)) return;
|
|
102
|
+
|
|
103
|
+
if (isObject(before) && isObject(after) && depth < MAX_DEPTH) {
|
|
104
|
+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
105
|
+
for (const key of keys) {
|
|
106
|
+
if (IGNORED_FIELDS.has(key)) continue;
|
|
107
|
+
walk(
|
|
108
|
+
before[key],
|
|
109
|
+
after[key],
|
|
110
|
+
path ? `${path}.${key}` : key,
|
|
111
|
+
label ? `${label}.${key}` : key,
|
|
112
|
+
out,
|
|
113
|
+
depth + 1
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (Array.isArray(before) && Array.isArray(after) && depth < MAX_DEPTH) {
|
|
120
|
+
const keyed = [...before, ...after].length > 0 && [...before, ...after].every(itemKey);
|
|
121
|
+
if (keyed) {
|
|
122
|
+
const oldById = new Map(before.map((item) => [itemKey(item), item]));
|
|
123
|
+
const newById = new Map(after.map((item) => [itemKey(item), item]));
|
|
124
|
+
for (const [id, item] of oldById) {
|
|
125
|
+
const itemLabel = `${label}[${itemName(newById.get(id) || item)}]`;
|
|
126
|
+
if (!newById.has(id)) out.push({ field: `${path}[${id}]`, label: itemLabel, from: itemName(item), to: null });
|
|
127
|
+
else walk(item, newById.get(id), `${path}[${id}]`, itemLabel, out, depth + 1);
|
|
128
|
+
}
|
|
129
|
+
for (const [id, item] of newById) {
|
|
130
|
+
if (!oldById.has(id)) {
|
|
131
|
+
out.push({ field: `${path}[${id}]`, label: `${label}[${itemName(item)}]`, from: null, to: itemName(item) });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
out.push({ field: path, label, from: before, to: after });
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Field-level differences between two versions of a settings record.
|
|
143
|
+
* @param before old record (mongoose doc or plain object), null on create
|
|
144
|
+
* @param after new record, null on delete
|
|
145
|
+
* @param options.labels { "field.path": "Readable name" }
|
|
146
|
+
* @param options.ignore extra field paths to leave out (e.g. ["logs"])
|
|
147
|
+
* @returns [{ field, label, from, to }] with secrets masked and large values shortened
|
|
148
|
+
*/
|
|
149
|
+
const diffSettings = (before, after, options = {}) => {
|
|
150
|
+
const { labels = {}, ignore = [] } = options;
|
|
151
|
+
const out = [];
|
|
152
|
+
walk(plain(before) ?? null, plain(after) ?? null, "", "", out, 0);
|
|
153
|
+
const skip = new Set(ignore);
|
|
154
|
+
return out
|
|
155
|
+
.filter((change) => change.field && !skip.has(change.field) && ![...skip].some((p) => change.field.startsWith(`${p}.`) || change.field.startsWith(`${p}[`)))
|
|
156
|
+
.map((change) => ({
|
|
157
|
+
field: change.field,
|
|
158
|
+
label: labels[change.field] || change.label || change.field,
|
|
159
|
+
from: maskValue(change.from, change.field),
|
|
160
|
+
to: maskValue(change.to, change.field),
|
|
161
|
+
}));
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const toObjectIdOrNull = (value) => {
|
|
165
|
+
const text = value == null ? "" : String(value);
|
|
166
|
+
return Types.ObjectId.isValid(text) && /^[a-f0-9]{24}$/i.test(text) ? new Types.ObjectId(text) : null;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const nameOf = (user = {}) =>
|
|
170
|
+
user.name || [user.firstName, user.lastName].filter(Boolean).join(" ").trim();
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The person making the request, from the login token (req.user when checkPermission
|
|
174
|
+
* already ran, otherwise the Authorization header). Never from body or query userId,
|
|
175
|
+
* which anyone can change. Main super admin (role "super") is marked super_admin;
|
|
176
|
+
* callers that know better (e.g. delegated super admins) can override actor.type.
|
|
177
|
+
*/
|
|
178
|
+
const actorFromRequest = (req) => {
|
|
179
|
+
let user = req?.user;
|
|
180
|
+
if (!user?.id) {
|
|
181
|
+
const header = req?.headers?.authorization || "";
|
|
182
|
+
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
|
|
183
|
+
user = token ? getBodyFromDecodeToken(token) : null;
|
|
184
|
+
}
|
|
185
|
+
if (!user) return { type: ACTOR_TYPES.SYSTEM };
|
|
186
|
+
return {
|
|
187
|
+
userId: user.id || user._id || null,
|
|
188
|
+
name: nameOf(user),
|
|
189
|
+
email: user.email || "",
|
|
190
|
+
role: typeof user.role === "string" ? user.role : "",
|
|
191
|
+
type: user.role === "super" ? ACTOR_TYPES.SUPER_ADMIN : ACTOR_TYPES.USER,
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Saves one settings change. Pass `changes` yourself, or `before` / `after` to have them
|
|
197
|
+
* worked out. An "updated" call where nothing changed saves nothing.
|
|
198
|
+
* @returns the saved row, or null when skipped or when saving failed (never throws)
|
|
199
|
+
*/
|
|
200
|
+
const recordSettingsChange = async ({
|
|
201
|
+
workspaceId = null,
|
|
202
|
+
actor = {},
|
|
203
|
+
module,
|
|
204
|
+
action,
|
|
205
|
+
target = {},
|
|
206
|
+
before,
|
|
207
|
+
after,
|
|
208
|
+
changes,
|
|
209
|
+
diffOptions,
|
|
210
|
+
summary = "",
|
|
211
|
+
source = {},
|
|
212
|
+
} = {}) => {
|
|
213
|
+
try {
|
|
214
|
+
if (!module || !action) {
|
|
215
|
+
logger.error("[SettingsAudit] module and action are required", { module, action });
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
const list =
|
|
219
|
+
changes ??
|
|
220
|
+
(before !== undefined || after !== undefined ? diffSettings(before, after, diffOptions) : []);
|
|
221
|
+
if (action === SETTINGS_AUDIT_ACTIONS.UPDATED && !list.length) return null;
|
|
222
|
+
|
|
223
|
+
return await SettingsAuditLog.create({
|
|
224
|
+
workspaceId: toObjectIdOrNull(workspaceId),
|
|
225
|
+
actor: {
|
|
226
|
+
userId: toObjectIdOrNull(actor.userId),
|
|
227
|
+
name: actor.name || "",
|
|
228
|
+
email: actor.email || "",
|
|
229
|
+
role: actor.role || "",
|
|
230
|
+
type: actor.type || ACTOR_TYPES.USER,
|
|
231
|
+
},
|
|
232
|
+
module,
|
|
233
|
+
action,
|
|
234
|
+
target: {
|
|
235
|
+
type: target.type || "",
|
|
236
|
+
id: target.id == null ? "" : String(target.id),
|
|
237
|
+
name: target.name || "",
|
|
238
|
+
},
|
|
239
|
+
changes: list.slice(0, MAX_CHANGES),
|
|
240
|
+
summary,
|
|
241
|
+
source: {
|
|
242
|
+
app: source.app || "",
|
|
243
|
+
method: source.method || "",
|
|
244
|
+
route: source.route || "",
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
} catch (err) {
|
|
248
|
+
logger.error(`[SettingsAudit] Could not record ${module}/${action}: ${err?.message || err}`);
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
module.exports = {
|
|
254
|
+
recordSettingsChange,
|
|
255
|
+
diffSettings,
|
|
256
|
+
actorFromRequest,
|
|
257
|
+
SETTINGS_AUDIT_MODULES,
|
|
258
|
+
SETTINGS_AUDIT_ACTIONS,
|
|
259
|
+
SETTINGS_AUDIT_ACTOR_TYPES: ACTOR_TYPES,
|
|
260
|
+
};
|