levix-bot 4.7.0 → 4.9.1
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/README.md +21 -7
- package/SETUP.md +21 -2
- package/app.cjs +69 -23
- package/package.json +3 -2
- package/public/dashboard/assets/index-B1sOW2VX.js +561 -0
- package/public/dashboard/assets/index-CK8osB4o.css +2 -0
- package/public/dashboard/index.html +2 -2
- package/public/dashboard.css +50 -0
- package/public/dashboard.js +25 -2
- package/public/gateway-i18n.js +26 -0
- package/src/bootstrap/session-startup-policy.js +6 -6
- package/src/commands/group/antilink.cjs +82 -59
- package/src/commands/group/antispam.cjs +112 -0
- package/src/commands/group/clearwarns.cjs +6 -6
- package/src/commands/group/demote.cjs +11 -13
- package/src/commands/group/flagged.cjs +52 -0
- package/src/commands/group/kick.cjs +25 -15
- package/src/commands/group/media.cjs +65 -29
- package/src/commands/group/policy.cjs +215 -0
- package/src/commands/group/promote.cjs +11 -12
- package/src/commands/group/rules.cjs +9 -6
- package/src/commands/group/setwarn.cjs +17 -27
- package/src/commands/group/warn.cjs +13 -63
- package/src/commands/group.cjs +5 -2
- package/src/commands/md.cjs +44 -0
- package/src/commands/mod.cjs +101 -26
- package/src/commands/translate.cjs +585 -0
- package/src/config/ai-identity.cjs +53 -1
- package/src/config/ai-persona.md +32 -73
- package/src/config/defaults.cjs +3 -0
- package/src/config/secrets.cjs +71 -3
- package/src/config/settings.cjs +22 -1
- package/src/core/socket.js +27 -5
- package/src/db/db.cjs +66 -0
- package/src/db/store.cjs +264 -16
- package/src/diagnostics/crashReports.cjs +35 -9
- package/src/diagnostics/debugLog.cjs +405 -0
- package/src/handlers/command.handler.js +3 -1
- package/src/handlers/group.handler.js +32 -1
- package/src/handlers/message.handler.js +53 -17
- package/src/middleware/antispam.middleware.js +95 -48
- package/src/panel/feedback.cjs +32 -5
- package/src/panel/one-time-code.cjs +156 -0
- package/src/panel/password-reset.cjs +187 -91
- package/src/panel/recovery-email.cjs +333 -0
- package/src/routes/dashboard.api.esm.js +341 -29
- package/src/services/aiAgent.cjs +25 -3
- package/src/services/moderationPolicy.cjs +895 -0
- package/src/services/settingsTransfer.cjs +4 -2
- package/src/utils/linkedCreds.cjs +22 -0
- package/src/utils/logger.cjs +93 -34
- package/src/utils/markdownParser.cjs +208 -136
- package/src/utils/moderationAction.cjs +637 -0
- package/src/utils/moderationSummary.cjs +225 -0
- package/src/utils/permissions.cjs +70 -0
- package/src/utils/permissions.esm.js +48 -8
- package/src/utils/storage.cjs +8 -0
- package/src/utils/storage.esm.js +4 -0
- package/views/login.ejs +100 -28
- package/public/dashboard/assets/index-RnT7DAde.js +0 -540
- package/public/dashboard/assets/index-UcqCdCvG.css +0 -2
- package/src/commands/group/antiSpam.cjs +0 -97
|
@@ -11,9 +11,22 @@ import { resolveGroupMetadata } from "../utils/groupMetadataCache.cjs";
|
|
|
11
11
|
|
|
12
12
|
const require = createRequire(import.meta.url);
|
|
13
13
|
const logger = require("../utils/logger.cjs");
|
|
14
|
-
const {
|
|
14
|
+
const { enforceGroupRule } = require("../utils/moderationAction.cjs");
|
|
15
|
+
const { featureActionOf } = require("../utils/moderationSummary.cjs");
|
|
15
16
|
|
|
16
17
|
const userMessageTimestamps = new Map();
|
|
18
|
+
const seenMessageIds = [];
|
|
19
|
+
const spamHitIds = [];
|
|
20
|
+
|
|
21
|
+
function rememberCapped(list, id) {
|
|
22
|
+
if (!id || list.includes(id)) return;
|
|
23
|
+
list.push(id);
|
|
24
|
+
if (list.length > 200) list.shift();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function spamHit(rule = "spam") {
|
|
28
|
+
return { rule, reason: "antispam" };
|
|
29
|
+
}
|
|
17
30
|
|
|
18
31
|
function stableSenderId(candidates) {
|
|
19
32
|
const phoneJid = candidates.find((jid) => jid.endsWith("@s.whatsapp.net"));
|
|
@@ -27,6 +40,70 @@ function stableSenderId(candidates) {
|
|
|
27
40
|
return candidates[0] || null;
|
|
28
41
|
}
|
|
29
42
|
|
|
43
|
+
function identityKeys(groupId, candidates) {
|
|
44
|
+
const ids = new Set();
|
|
45
|
+
const stable = stableSenderId(candidates);
|
|
46
|
+
if (stable) ids.add(stable);
|
|
47
|
+
for (const candidate of candidates) {
|
|
48
|
+
if (candidate) ids.add(candidate);
|
|
49
|
+
try {
|
|
50
|
+
const mapped = getPnForLid(candidate);
|
|
51
|
+
if (mapped) ids.add(mapped);
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
return [...ids].map((id) => `${groupId}::${id}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function mergeSpamBucket(groupId, candidates, now, timeWindow) {
|
|
58
|
+
const keys = identityKeys(groupId, candidates);
|
|
59
|
+
const timestamps = [];
|
|
60
|
+
for (const key of keys) {
|
|
61
|
+
const bucket = userMessageTimestamps.get(key);
|
|
62
|
+
if (bucket?.timestamps) timestamps.push(...bucket.timestamps);
|
|
63
|
+
}
|
|
64
|
+
timestamps.push(now);
|
|
65
|
+
const recent = timestamps.filter((ts) => now - ts < timeWindow);
|
|
66
|
+
const canonical = `${groupId}::${stableSenderId(candidates) || candidates[0]}`;
|
|
67
|
+
for (const key of keys) {
|
|
68
|
+
if (key !== canonical) userMessageTimestamps.delete(key);
|
|
69
|
+
}
|
|
70
|
+
userMessageTimestamps.set(canonical, { timestamps: recent, lastSeen: now });
|
|
71
|
+
return { recent, canonical };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Record one message and return a spam hit when the window is exceeded.
|
|
75
|
+
// Disabled anti-spam does not record. A message id is observed once; a hit id
|
|
76
|
+
// still reports a hit after the bucket is cleared so a redelivery can retry.
|
|
77
|
+
// Callers with no id (older tests) record on every call.
|
|
78
|
+
export async function observeAntiSpam(sock, msg, settings) {
|
|
79
|
+
const groupId = msg?.key?.remoteJid;
|
|
80
|
+
if (!groupId?.endsWith("@g.us")) return null;
|
|
81
|
+
const spamConfig = settings?.antispam ?? getGroupSettings(groupId)?.antispam;
|
|
82
|
+
if (!spamConfig?.enabled) return null;
|
|
83
|
+
|
|
84
|
+
const messageId = msg.key?.id || null;
|
|
85
|
+
const stamp = messageId ? `${groupId}:${messageId}` : null;
|
|
86
|
+
if (stamp && spamHitIds.includes(stamp)) return spamHit();
|
|
87
|
+
if (stamp && seenMessageIds.includes(stamp)) return null;
|
|
88
|
+
|
|
89
|
+
const senderCandidates = getSenderCandidates(msg, sock);
|
|
90
|
+
if (!senderCandidates.length) return null;
|
|
91
|
+
|
|
92
|
+
const now = Date.now();
|
|
93
|
+
const timeWindow = (spamConfig.time_window || 10) * 1000;
|
|
94
|
+
for (const [key, entry] of userMessageTimestamps) {
|
|
95
|
+
if (now - entry.lastSeen > timeWindow) userMessageTimestamps.delete(key);
|
|
96
|
+
}
|
|
97
|
+
const { recent, canonical } = mergeSpamBucket(groupId, senderCandidates, now, timeWindow);
|
|
98
|
+
if (stamp) rememberCapped(seenMessageIds, stamp);
|
|
99
|
+
if (recent.length > (spamConfig.message_count || 5)) {
|
|
100
|
+
userMessageTimestamps.delete(canonical);
|
|
101
|
+
if (stamp) rememberCapped(spamHitIds, stamp);
|
|
102
|
+
return spamHit();
|
|
103
|
+
}
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
30
107
|
// Handle anti-spam detection and action
|
|
31
108
|
export async function handleAntiSpam(sock, msg) {
|
|
32
109
|
const groupId = msg.key.remoteJid;
|
|
@@ -40,11 +117,8 @@ export async function handleAntiSpam(sock, msg) {
|
|
|
40
117
|
|
|
41
118
|
if (!spamConfig || !spamConfig.enabled) return;
|
|
42
119
|
|
|
43
|
-
// Owners and admins are immune.
|
|
44
|
-
//
|
|
45
|
-
// counted as spammers — the centralized check fixes that.
|
|
46
|
-
// Cache-first: antispam runs on EVERY group message, so this read must not
|
|
47
|
-
// be a live query (see utils/groupMetadataCache.cjs).
|
|
120
|
+
// Owners and admins are immune. Checked before observe so a protected
|
|
121
|
+
// sender is not recorded. Cache-first: antispam runs on every group message.
|
|
48
122
|
const groupMetadata = await resolveGroupMetadata(sock, groupId);
|
|
49
123
|
const protectedSender = senderCandidates.some(
|
|
50
124
|
(candidate) =>
|
|
@@ -56,46 +130,19 @@ export async function handleAntiSpam(sock, msg) {
|
|
|
56
130
|
|
|
57
131
|
if (protectedSender) return;
|
|
58
132
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
// Check if user exceeded message count
|
|
76
|
-
if (recentTimestamps.length > (spamConfig.message_count || 5)) {
|
|
77
|
-
logger.warn({ user: senderId, group: groupId }, "Spam detected, taking action.");
|
|
78
|
-
|
|
79
|
-
// Take action based on config
|
|
80
|
-
if (spamConfig.action === "KICK") {
|
|
81
|
-
await sock.sendMessage(groupId, {
|
|
82
|
-
text: tr(
|
|
83
|
-
`🚫 @${senderId.split("@")[0]} was removed for spamming.`,
|
|
84
|
-
`🚫 تم حذف @${senderId.split("@")[0]} بسبب الإزعاج (Spam).`,
|
|
85
|
-
),
|
|
86
|
-
mentions: [senderId],
|
|
87
|
-
});
|
|
88
|
-
await sock.groupParticipantsUpdate(groupId, [senderId], "remove");
|
|
89
|
-
} else {
|
|
90
|
-
await sock.sendMessage(groupId, {
|
|
91
|
-
text: tr(
|
|
92
|
-
`⚠️ Warning, @${senderId.split("@")[0]}! Please don't spam.`,
|
|
93
|
-
`⚠️ تحذير لـ @${senderId.split("@")[0]}! الرجاء عدم إرسال رسائل مزعجة.`,
|
|
94
|
-
),
|
|
95
|
-
mentions: [senderId],
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
userMessageTimestamps.delete(bucketKey);
|
|
100
|
-
}
|
|
133
|
+
const hit = await observeAntiSpam(sock, msg, settings);
|
|
134
|
+
if (!hit) return;
|
|
135
|
+
|
|
136
|
+
logger.warn({ user: senderId, group: groupId }, "Spam detected, taking action.");
|
|
137
|
+
const kickNow = featureActionOf(settings, "antispam") === "KICK";
|
|
138
|
+
await enforceGroupRule(sock, {
|
|
139
|
+
msg,
|
|
140
|
+
groupMetadata,
|
|
141
|
+
rule: "spam",
|
|
142
|
+
warningReason: "antispam",
|
|
143
|
+
deleteMessage: false,
|
|
144
|
+
recordWarning: true,
|
|
145
|
+
kickImmediately: kickNow,
|
|
146
|
+
targetCandidates: senderCandidates,
|
|
147
|
+
});
|
|
101
148
|
}
|
package/src/panel/feedback.cjs
CHANGED
|
@@ -21,6 +21,7 @@ const fs = require("node:fs");
|
|
|
21
21
|
const logger = require("../utils/logger.cjs");
|
|
22
22
|
const settings = require("../config/settings.cjs");
|
|
23
23
|
const { buildDiagnostics } = require("../diagnostics/device.cjs");
|
|
24
|
+
const { readDebugTail, readDebugSnapshot, storeDebugSnapshot } = require("../diagnostics/debugLog.cjs");
|
|
24
25
|
|
|
25
26
|
const DEFAULT_ENDPOINT = "https://levix.leviro.net/api/feedback";
|
|
26
27
|
|
|
@@ -153,6 +154,27 @@ function safeRemoteError(value) {
|
|
|
153
154
|
return text || null;
|
|
154
155
|
}
|
|
155
156
|
|
|
157
|
+
/**
|
|
158
|
+
* The preview's diagnostics object plus the debug tail it is showing, frozen
|
|
159
|
+
* under `debugLogId`. Send does not call this: it redeems that id.
|
|
160
|
+
*
|
|
161
|
+
* @param {unknown} diagnosticsClient
|
|
162
|
+
* @returns {{ diagnostics: Record<string, unknown>, debugLog: string, debugLogId: string }}
|
|
163
|
+
*/
|
|
164
|
+
function buildDiagnosticsAttachment(diagnosticsClient) {
|
|
165
|
+
let debugLog = "";
|
|
166
|
+
try {
|
|
167
|
+
debugLog = readDebugTail();
|
|
168
|
+
} catch {
|
|
169
|
+
debugLog = "";
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
diagnostics: buildDiagnostics(diagnosticsClient),
|
|
173
|
+
debugLog,
|
|
174
|
+
debugLogId: storeDebugSnapshot(debugLog),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
156
178
|
/**
|
|
157
179
|
* Forward one validated submission. An attachment (already size-checked by
|
|
158
180
|
* the route) turns the forward into multipart: the fields travel as a JSON
|
|
@@ -160,17 +182,19 @@ function safeRemoteError(value) {
|
|
|
160
182
|
* Telegram as a document instead of a message.
|
|
161
183
|
*
|
|
162
184
|
* `diagnosticsClient` is the raw section 1 client object, present only when the
|
|
163
|
-
* operator ticked the diagnostics box. When present the
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
185
|
+
* operator ticked the diagnostics box. When present the envelope gets
|
|
186
|
+
* `diagnostics`. `debugLog` is added only when `debugLogId` still names the
|
|
187
|
+
* snapshot the preview stored — a missing or expired id attaches no debug log,
|
|
188
|
+
* never a fresh unread one. When diagnostics were not requested the envelope
|
|
189
|
+
* has neither key.
|
|
167
190
|
*
|
|
168
191
|
* @param {{ message: string, topic: string, rating: number|null, contact: string|null }} feedback
|
|
169
192
|
* @param {{ buffer: Buffer, name: string, type: string, size: number } | null} attachment
|
|
170
193
|
* @param {object} [diagnosticsClient]
|
|
194
|
+
* @param {unknown} [debugLogId]
|
|
171
195
|
* @returns {Promise<{ ok: true } | { ok: false, status: number, error: string }>}
|
|
172
196
|
*/
|
|
173
|
-
async function submitFeedback(feedback, attachment = null, diagnosticsClient = undefined) {
|
|
197
|
+
async function submitFeedback(feedback, attachment = null, diagnosticsClient = undefined, debugLogId = undefined) {
|
|
174
198
|
const endpoint = process.env.LEVIX_FEEDBACK_URL || DEFAULT_ENDPOINT;
|
|
175
199
|
const runtime = describeRuntime();
|
|
176
200
|
|
|
@@ -184,6 +208,8 @@ async function submitFeedback(feedback, attachment = null, diagnosticsClient = u
|
|
|
184
208
|
|
|
185
209
|
if (diagnosticsClient !== undefined && diagnosticsClient !== null) {
|
|
186
210
|
envelope.diagnostics = buildDiagnostics(diagnosticsClient);
|
|
211
|
+
const debugLog = readDebugSnapshot(debugLogId);
|
|
212
|
+
if (typeof debugLog === "string") envelope.debugLog = debugLog;
|
|
187
213
|
}
|
|
188
214
|
|
|
189
215
|
let response;
|
|
@@ -267,5 +293,6 @@ module.exports = {
|
|
|
267
293
|
validateFeedback,
|
|
268
294
|
describeRuntime,
|
|
269
295
|
feedbackRetryAfter,
|
|
296
|
+
buildDiagnosticsAttachment,
|
|
270
297
|
submitFeedback,
|
|
271
298
|
};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// One in-memory code, shared by every channel that proves the operator.
|
|
2
|
+
//
|
|
3
|
+
// WhatsApp and email password resets use a local 6-digit code, hashed in
|
|
4
|
+
// memory, dead after 10 minutes or five wrong guesses. Recovery-email
|
|
5
|
+
// verification uses the relay's own code and attempts. Both reuse the send
|
|
6
|
+
// throttle here so a loop cannot turn into a stream of messages.
|
|
7
|
+
// This file does not know about WhatsApp, email, or the password.
|
|
8
|
+
|
|
9
|
+
const crypto = require("node:crypto");
|
|
10
|
+
|
|
11
|
+
const CODE_TTL_MS = 10 * 60 * 1000;
|
|
12
|
+
const MAX_CODE_ATTEMPTS = 5;
|
|
13
|
+
const REQUEST_WINDOW_MS = 15 * 60 * 1000;
|
|
14
|
+
const MAX_REQUESTS_PER_WINDOW = 3;
|
|
15
|
+
const GLOBAL_COOLDOWN_MS = 60 * 1000;
|
|
16
|
+
|
|
17
|
+
function hashCode(code, salt) {
|
|
18
|
+
return crypto.createHash("sha256").update(`${salt}:${code}`).digest("hex");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A fresh code plus the record to keep. The plaintext `code` is for the
|
|
23
|
+
* delivery step only — callers must not store it.
|
|
24
|
+
*
|
|
25
|
+
* @param {number} [now]
|
|
26
|
+
* @returns {{ code: string, pending: { salt: string, hash: string, expiresAt: number, attempts: number } }}
|
|
27
|
+
*/
|
|
28
|
+
function generateCode(now = Date.now()) {
|
|
29
|
+
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");
|
|
30
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
31
|
+
return {
|
|
32
|
+
code,
|
|
33
|
+
pending: {
|
|
34
|
+
salt,
|
|
35
|
+
hash: hashCode(code, salt),
|
|
36
|
+
expiresAt: now + CODE_TTL_MS,
|
|
37
|
+
attempts: 0,
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Check a guess. Increments `pending.attempts`. Does not delete the record —
|
|
44
|
+
* `clear: true` means the caller should drop it (expired, or no attempts left).
|
|
45
|
+
* A matching code returns `{ ok: true }` and leaves the record in place so the
|
|
46
|
+
* caller can still reject a bad new password without burning the code.
|
|
47
|
+
*
|
|
48
|
+
* @param {{ salt: string, hash: string, expiresAt: number, attempts: number } | null} pending
|
|
49
|
+
* @param {unknown} code
|
|
50
|
+
* @param {number} [now]
|
|
51
|
+
*/
|
|
52
|
+
function checkAttempt(pending, code, now = Date.now()) {
|
|
53
|
+
if (!pending) return { ok: false, reason: "no_pending" };
|
|
54
|
+
if (now > pending.expiresAt) return { ok: false, reason: "expired", clear: true };
|
|
55
|
+
|
|
56
|
+
pending.attempts += 1;
|
|
57
|
+
const expected = Buffer.from(pending.hash, "hex");
|
|
58
|
+
const actual = Buffer.from(hashCode(String(code ?? "").trim(), pending.salt), "hex");
|
|
59
|
+
const matches = expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
|
60
|
+
if (!matches) {
|
|
61
|
+
const attemptsLeft = MAX_CODE_ATTEMPTS - pending.attempts;
|
|
62
|
+
if (attemptsLeft <= 0) return { ok: false, reason: "too_many_attempts", clear: true };
|
|
63
|
+
return { ok: false, reason: "wrong_code", attemptsLeft };
|
|
64
|
+
}
|
|
65
|
+
return { ok: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Per-purpose send throttle. Password reset uses one instance for every
|
|
70
|
+
* channel (a WhatsApp send and an email send share the cooldown). Recovery
|
|
71
|
+
* verification uses a second instance so adding an address does not lock the
|
|
72
|
+
* operator out of resetting the password, or the reverse.
|
|
73
|
+
*/
|
|
74
|
+
function createThrottle() {
|
|
75
|
+
let lastRequestAt = 0;
|
|
76
|
+
const requests = new Map();
|
|
77
|
+
|
|
78
|
+
function check(peer, now = Date.now()) {
|
|
79
|
+
for (const [key, entry] of requests) {
|
|
80
|
+
if (now - entry.firstAt > REQUEST_WINDOW_MS) requests.delete(key);
|
|
81
|
+
}
|
|
82
|
+
const entry = requests.get(peer);
|
|
83
|
+
if (entry && entry.count >= MAX_REQUESTS_PER_WINDOW) {
|
|
84
|
+
return {
|
|
85
|
+
ok: false,
|
|
86
|
+
reason: "throttled",
|
|
87
|
+
retryAfter: Math.ceil((REQUEST_WINDOW_MS - (now - entry.firstAt)) / 1000),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
const sinceLast = now - lastRequestAt;
|
|
91
|
+
if (lastRequestAt && sinceLast < GLOBAL_COOLDOWN_MS) {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
reason: "throttled",
|
|
95
|
+
retryAfter: Math.ceil((GLOBAL_COOLDOWN_MS - sinceLast) / 1000),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
return { ok: true, entry: entry || null };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function record(peer, entry, now = Date.now()) {
|
|
102
|
+
lastRequestAt = now;
|
|
103
|
+
if (entry) entry.count += 1;
|
|
104
|
+
else requests.set(peer, { count: 1, firstAt: now });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Take one slot before any await. Concurrent callers then see the cooldown
|
|
109
|
+
* instead of all passing `check` while the first delivery is still running.
|
|
110
|
+
* `release` gives the slot back when delivery fails — a failed send must not
|
|
111
|
+
* spend the cooldown.
|
|
112
|
+
*/
|
|
113
|
+
function reserve(peer, now = Date.now()) {
|
|
114
|
+
const gate = check(peer, now);
|
|
115
|
+
if (!gate.ok) return gate;
|
|
116
|
+
const reservation = {
|
|
117
|
+
peer,
|
|
118
|
+
previousLast: lastRequestAt,
|
|
119
|
+
entry: gate.entry,
|
|
120
|
+
previousCount: gate.entry ? gate.entry.count : 0,
|
|
121
|
+
previousFirstAt: gate.entry ? gate.entry.firstAt : 0,
|
|
122
|
+
};
|
|
123
|
+
record(peer, gate.entry, now);
|
|
124
|
+
return { ok: true, reservation };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function release(reservation) {
|
|
128
|
+
if (!reservation) return;
|
|
129
|
+
lastRequestAt = reservation.previousLast;
|
|
130
|
+
if (!reservation.entry) {
|
|
131
|
+
requests.delete(reservation.peer);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
reservation.entry.count = reservation.previousCount;
|
|
135
|
+
reservation.entry.firstAt = reservation.previousFirstAt;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function reset() {
|
|
139
|
+
lastRequestAt = 0;
|
|
140
|
+
requests.clear();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return { check, record, reserve, release, reset };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = {
|
|
147
|
+
CODE_TTL_MS,
|
|
148
|
+
MAX_CODE_ATTEMPTS,
|
|
149
|
+
REQUEST_WINDOW_MS,
|
|
150
|
+
MAX_REQUESTS_PER_WINDOW,
|
|
151
|
+
GLOBAL_COOLDOWN_MS,
|
|
152
|
+
hashCode,
|
|
153
|
+
generateCode,
|
|
154
|
+
checkAttempt,
|
|
155
|
+
createThrottle,
|
|
156
|
+
};
|