forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauditService.js
More file actions
140 lines (129 loc) · 4 KB
/
Copy pathauditService.js
File metadata and controls
140 lines (129 loc) · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// services/audit/auditService.js
//
// Non-blocking, redaction-safe helper for writing audit rows.
//
// Usage (fire-and-forget — do NOT await at call site):
//
// recordAudit({
// action: AUDIT_ACTIONS.AUTH_LOGIN_SUCCESS,
// actor: user._id, // null for anonymous/pre-auth
// req, // pass the Express request for IP/UA/reqId
// targetType: "User",
// targetId: user._id.toString(),
// status: "success",
// metadata: { email: user.email }, // only allowlisted keys are stored
// });
//
// The function schedules the write via Promise microtask and catches all
// errors internally, so a DB write failure NEVER propagates to the caller.
import mongoose from "mongoose";
import AuditLog from "../../models/AuditLog.js";
import logger from "../../config/logger.js";
// ── Metadata redaction allowlist ───────────────────────────────────────────
// ONLY keys listed here will be persisted in metadata.
// Add keys here when instrumenting new actions — never use a denylist approach.
const METADATA_ALLOWLIST = new Set([
// Identity / context
"email",
"role",
"assignedRole",
"name",
// Wallet
"publicKey",
"network",
"previousPublicKey",
// Payment
"transactionId",
"itemType",
"itemId",
"itemTitle",
"amount",
"stellarTxHash",
"stellarLedger",
"settlementMode",
"failureReason",
// Entitlement
"accessGranted",
// Payout / ledger (extension — #28)
"batchId",
"payoutAmount",
"educatorId",
// Role change (extension — #20)
"previousRole",
"newRole",
"changedBy",
// Generic error context
"reason",
"conflictUserId",
]);
/**
* Strip any metadata key not in the allowlist.
* Returns null if metadata is null/undefined/empty.
*
* @param {object|null} metadata
* @returns {object|null}
*/
export function redactMetadata(metadata) {
if (!metadata || typeof metadata !== "object") return null;
const safe = {};
for (const key of Object.keys(metadata)) {
if (METADATA_ALLOWLIST.has(key)) {
safe[key] = metadata[key];
}
}
return Object.keys(safe).length > 0 ? safe : null;
}
/**
* Record a security/financial audit event. Always fire-and-forget relative
* to the caller — the write is scheduled in a microtask and errors are
* swallowed (logged only).
*
* @param {object} opts
* @param {string} opts.action - One of AUDIT_ACTIONS values
* @param {string|ObjectId|null} opts.actor - User._id or null
* @param {import("express").Request} [opts.req] - Express request (for IP/UA/reqId)
* @param {string|null} [opts.targetType]
* @param {string|null} [opts.targetId]
* @param {"success"|"failure"} opts.status
* @param {object|null} [opts.metadata] - Will be allowlist-filtered
*/
export function recordAudit({
action,
actor = null,
req = null,
targetType = null,
targetId = null,
status,
metadata = null,
}) {
// Schedule asynchronously — do not block caller
Promise.resolve()
.then(async () => {
// If DB is not connected and AuditLog.create is not mocked (e.g. unit tests without DB),
// skip write to prevent 10s Mongoose buffer timeouts.
if (mongoose.connection.readyState !== 1 && !AuditLog.create.mock) {
return;
}
const actorIp = req?.ip ?? null;
const actorUserAgent = req?.headers?.["user-agent"] ?? null;
const requestId = req?.id ?? null;
await AuditLog.create({
action,
actor: actor || null,
actorIp,
actorUserAgent,
targetType,
targetId: targetId ? String(targetId) : null,
status,
metadata: redactMetadata(metadata),
requestId,
});
})
.catch((err) => {
// Never let an audit failure surface to the user.
logger.error(
{ err, action, actor, targetType, targetId },
"audit: failed to write audit log row"
);
});
}