strapi-plugin-magic-sessionmanager 4.9.1 → 4.11.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +86 -5
  2. package/README.md +427 -91
  3. package/dist/admin/{Analytics-lVDnHBYp.js → Analytics-CBHeWeGn.js} +1 -1
  4. package/dist/admin/{Analytics-dyJmyxO-.mjs → Analytics-D56O8Q6e.mjs} +1 -1
  5. package/dist/admin/{App-CdgiY_Y7.js → App-D4cBPwB_.js} +2 -3
  6. package/dist/admin/{App-Cgf_CSjw.mjs → App-EDIkLJdb.mjs} +2 -3
  7. package/dist/admin/{OnlineUsersWidget-DMPtuIpm.js → OnlineUsersWidget-BF2R2YIy.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-DJC4V1KS.mjs → OnlineUsersWidget-MwUutkKQ.mjs} +1 -1
  9. package/dist/admin/{Settings-0QsyY7fe.js → Settings-CMzEF8EH.js} +21 -5
  10. package/dist/admin/{Settings-DgeuUiMF.mjs → Settings-bLMyi0BN.mjs} +20 -4
  11. package/dist/admin/{de-j0oZH9Pz.mjs → de-CxfuTF6C.mjs} +1 -42
  12. package/dist/admin/{de-BFKoGEVT.js → de-DVNTHmSo.js} +1 -42
  13. package/dist/admin/{en-UY4Tb5tE.mjs → en-BcPIlQYL.mjs} +1 -42
  14. package/dist/admin/{en-s7Ksdkcg.js → en-BuVXIcHA.js} +1 -42
  15. package/dist/admin/{es-07OGMe_5.js → es-CEteHmBO.js} +1 -42
  16. package/dist/admin/{es-DGBcZwQy.mjs → es-DxHpaNA1.mjs} +1 -42
  17. package/dist/admin/{fr-ETj_2UBY.js → fr-BMd2-wW7.js} +1 -42
  18. package/dist/admin/{fr-B6-DWhGO.mjs → fr-Dw43lHg7.mjs} +1 -42
  19. package/dist/admin/{index-D-Nr0TCm.js → index-DvNfekoR.js} +9 -19
  20. package/dist/admin/{index-Ck19e8qw.mjs → index-qa6Qnfkc.mjs} +9 -19
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +1 -1
  23. package/dist/admin/{pt-YMRLm9gx.mjs → pt-7jnxDSX-.mjs} +1 -42
  24. package/dist/admin/{pt-C7PwrQtV.js → pt-BvO63p01.js} +1 -42
  25. package/dist/server/index.js +1322 -827
  26. package/dist/server/index.mjs +1322 -827
  27. package/package.json +32 -13
  28. package/dist/admin/License-1XUfQty5.js +0 -443
  29. package/dist/admin/License-C4WSYoqY.mjs +0 -443
  30. package/dist/admin/maskSensitiveValue-BWcSjow7.js +0 -9
  31. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +0 -10
@@ -85,24 +85,746 @@ var require_logger = __commonJS({
85
85
  }
86
86
  });
87
87
 
88
+ // server/src/utils/coordination.js
89
+ var require_coordination = __commonJS({
90
+ "server/src/utils/coordination.js"(exports, module) {
91
+ "use strict";
92
+ var { AsyncLocalStorage } = __require("node:async_hooks");
93
+ var crypto = __require("node:crypto");
94
+ var os = __require("node:os");
95
+ var heldLocks = new AsyncLocalStorage();
96
+ var TABLES = Object.freeze({
97
+ counters: "magic_sm_counters",
98
+ leases: "magic_sm_leases",
99
+ cache: "magic_sm_cache"
100
+ });
101
+ var PG_LOCK_NAMESPACE = 5067597;
102
+ var NEVER_EXPIRES = 8e15;
103
+ var MAX_KEY_LENGTH = 191;
104
+ var LEASE_SHRINK_MARGIN_MS = 6e4;
105
+ var COUNTER_COLUMNS = Object.freeze(["hits", "window_start", "blocked_until"]);
106
+ var instanceIdCache = null;
107
+ function getInstanceId() {
108
+ if (instanceIdCache) return instanceIdCache;
109
+ let host = "unknown";
110
+ try {
111
+ host = os.hostname() || "unknown";
112
+ } catch {
113
+ }
114
+ const hostHash = crypto.createHash("sha256").update(host).digest("hex").slice(0, 12);
115
+ instanceIdCache = `${hostHash}:${process.pid}:${crypto.randomBytes(4).toString("hex")}`;
116
+ return instanceIdCache;
117
+ }
118
+ function getHostFingerprint() {
119
+ return getInstanceId().split(":")[0];
120
+ }
121
+ function hashedKey(prefix, raw) {
122
+ const digest = crypto.createHash("sha256").update(String(raw)).digest("hex").slice(0, 48);
123
+ return `${prefix}:${digest}`;
124
+ }
125
+ function toNumber(value) {
126
+ if (value === null || value === void 0) return 0;
127
+ const n = Number(value);
128
+ return Number.isFinite(n) ? n : 0;
129
+ }
130
+ function assertKey(key) {
131
+ if (typeof key !== "string" || key.length === 0 || key.length > MAX_KEY_LENGTH) {
132
+ throw new TypeError("coordination key must be a non-empty string of at most 191 characters");
133
+ }
134
+ }
135
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
136
+ var LockTimeoutError = class extends Error {
137
+ constructor(name) {
138
+ super(`Timed out waiting for lock "${name}"`);
139
+ this.name = "LockTimeoutError";
140
+ }
141
+ };
142
+ function createMemoryBackend() {
143
+ const counters = /* @__PURE__ */ new Map();
144
+ const leases = /* @__PURE__ */ new Map();
145
+ const revisions = /* @__PURE__ */ new Map();
146
+ const lockTails = /* @__PURE__ */ new Map();
147
+ const pruneCounters = (now) => {
148
+ if (counters.size < 5e3) return;
149
+ for (const [k, v] of counters) {
150
+ if (v.expiresAt <= now && v.blockedUntil <= now) counters.delete(k);
151
+ }
152
+ };
153
+ return {
154
+ mode: "memory",
155
+ async hit(key, windowMs, now = Date.now()) {
156
+ pruneCounters(now);
157
+ let entry = counters.get(key);
158
+ if (!entry) {
159
+ entry = { hits: 0, windowStart: 0, blockedUntil: 0, expiresAt: 0 };
160
+ counters.set(key, entry);
161
+ }
162
+ if (entry.windowStart <= now - windowMs) {
163
+ entry.hits = 1;
164
+ entry.windowStart = now;
165
+ } else {
166
+ entry.hits += 1;
167
+ }
168
+ entry.expiresAt = Math.max(entry.expiresAt, now + windowMs);
169
+ return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
170
+ },
171
+ async peek(key) {
172
+ const entry = counters.get(key);
173
+ if (!entry) return null;
174
+ return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
175
+ },
176
+ async block(key, untilMs) {
177
+ const entry = counters.get(key) || {
178
+ hits: 0,
179
+ windowStart: 0,
180
+ blockedUntil: 0,
181
+ expiresAt: 0
182
+ };
183
+ if (entry.blockedUntil < untilMs) entry.blockedUntil = untilMs;
184
+ entry.expiresAt = Math.max(entry.expiresAt, untilMs);
185
+ counters.set(key, entry);
186
+ },
187
+ async clear(key) {
188
+ counters.delete(key);
189
+ },
190
+ async release(key) {
191
+ const entry = counters.get(key);
192
+ if (entry && entry.hits > 0) entry.hits -= 1;
193
+ },
194
+ async getRevision(name) {
195
+ return revisions.get(name) || 0;
196
+ },
197
+ async bumpRevision(name) {
198
+ const next = (revisions.get(name) || 0) + 1;
199
+ revisions.set(name, next);
200
+ return next;
201
+ },
202
+ async tryAcquireLease(name, ttlMs, owner, now = Date.now()) {
203
+ const lease = leases.get(name);
204
+ if (lease && lease.until > now && lease.owner !== owner && lease.until <= now + ttlMs + LEASE_SHRINK_MARGIN_MS) {
205
+ return false;
206
+ }
207
+ leases.set(name, { owner, until: now + ttlMs });
208
+ return true;
209
+ },
210
+ async releaseLease(name, owner) {
211
+ const lease = leases.get(name);
212
+ if (lease && lease.owner === owner) leases.delete(name);
213
+ },
214
+ async withLock(name, fn) {
215
+ const previous = lockTails.get(name) || Promise.resolve();
216
+ let release;
217
+ const current = new Promise((resolve) => {
218
+ release = resolve;
219
+ });
220
+ const tail = previous.then(() => current);
221
+ lockTails.set(name, tail);
222
+ await previous;
223
+ try {
224
+ return await fn();
225
+ } finally {
226
+ release();
227
+ if (lockTails.get(name) === tail) lockTails.delete(name);
228
+ }
229
+ },
230
+ // The shared cache is an L2 behind per-module L1 caches; in memory mode
231
+ // the L1 caches already cover the process, so this layer stays empty.
232
+ async cacheGet() {
233
+ return null;
234
+ },
235
+ async cacheSet() {
236
+ },
237
+ async prune(now = Date.now()) {
238
+ let removed = 0;
239
+ for (const [k, v] of counters) {
240
+ if (v.expiresAt <= now && v.blockedUntil <= now) {
241
+ counters.delete(k);
242
+ removed++;
243
+ }
244
+ }
245
+ return removed;
246
+ },
247
+ reset() {
248
+ counters.clear();
249
+ leases.clear();
250
+ revisions.clear();
251
+ lockTails.clear();
252
+ }
253
+ };
254
+ }
255
+ function normalizeDialect(client) {
256
+ const value = String(client || "").toLowerCase();
257
+ if (value === "postgres" || value === "pg" || value === "postgresql") return "postgres";
258
+ if (value === "mysql" || value === "mysql2" || value === "mariadb") return "mysql";
259
+ if (value === "sqlite" || value === "sqlite3" || value === "better-sqlite3") return "sqlite";
260
+ return "other";
261
+ }
262
+ async function ensureTables(knex) {
263
+ const definitions = [
264
+ [
265
+ TABLES.counters,
266
+ (table) => {
267
+ table.string("k", MAX_KEY_LENGTH).notNullable().primary();
268
+ table.integer("hits").notNullable().defaultTo(0);
269
+ table.bigInteger("window_start").notNullable().defaultTo(0);
270
+ table.bigInteger("blocked_until").notNullable().defaultTo(0);
271
+ table.bigInteger("expires_at").notNullable().defaultTo(0);
272
+ table.index(["expires_at"], "magic_sm_counters_expires_idx");
273
+ }
274
+ ],
275
+ [
276
+ TABLES.leases,
277
+ (table) => {
278
+ table.string("name", MAX_KEY_LENGTH).notNullable().primary();
279
+ table.string("owner", MAX_KEY_LENGTH).notNullable().defaultTo("");
280
+ table.bigInteger("lease_until").notNullable().defaultTo(0);
281
+ }
282
+ ],
283
+ [
284
+ TABLES.cache,
285
+ (table) => {
286
+ table.string("k", MAX_KEY_LENGTH).notNullable().primary();
287
+ table.text("v");
288
+ table.bigInteger("expires_at").notNullable().defaultTo(0);
289
+ table.index(["expires_at"], "magic_sm_cache_expires_idx");
290
+ }
291
+ ]
292
+ ];
293
+ for (const [name, build] of definitions) {
294
+ if (await knex.schema.hasTable(name)) continue;
295
+ try {
296
+ await knex.schema.createTable(name, build);
297
+ } catch (err) {
298
+ if (!await knex.schema.hasTable(name)) throw err;
299
+ }
300
+ }
301
+ }
302
+ function createDatabaseBackend({ knex, dialect }) {
303
+ const kind = normalizeDialect(dialect);
304
+ const readCounter = async (key) => {
305
+ const row = await knex(TABLES.counters).select("hits", "window_start", "blocked_until").where({ k: key }).first();
306
+ if (!row) return null;
307
+ return {
308
+ hits: toNumber(row.hits),
309
+ windowStart: toNumber(row.window_start),
310
+ blockedUntil: toNumber(row.blocked_until)
311
+ };
312
+ };
313
+ const ensureCounterRow = (key, expiresAt) => knex(TABLES.counters).insert({ k: key, hits: 0, window_start: 0, blocked_until: 0, expires_at: expiresAt }).onConflict("k").ignore();
314
+ const supportsReturning = kind === "postgres" || kind === "sqlite";
315
+ const toCounter = (row) => row ? {
316
+ hits: toNumber(row.hits),
317
+ windowStart: toNumber(row.window_start),
318
+ blockedUntil: toNumber(row.blocked_until)
319
+ } : null;
320
+ const updateCounterReturning = async (key, withReturning, withoutReturning) => {
321
+ if (supportsReturning) {
322
+ const rows = await withReturning(knex(TABLES.counters).where({ k: key }));
323
+ return Array.isArray(rows) && rows.length > 0 ? toCounter(rows[0]) : null;
324
+ }
325
+ return knex.transaction(async (trx) => {
326
+ if (toNumber(await withoutReturning(trx)) === 0) return null;
327
+ const row = await trx(TABLES.counters).select(...COUNTER_COLUMNS).where({ k: key }).forUpdate().first();
328
+ return toCounter(row);
329
+ });
330
+ };
331
+ const tryAcquireLease = async (name, ttlMs, owner, now = Date.now()) => {
332
+ await knex(TABLES.leases).insert({ name, owner: "", lease_until: 0 }).onConflict("name").ignore();
333
+ const changed = await knex(TABLES.leases).where({ name }).andWhere((qb) => {
334
+ qb.where("lease_until", "<=", now).orWhere("owner", owner).orWhere("lease_until", ">", now + ttlMs + LEASE_SHRINK_MARGIN_MS);
335
+ }).update({ owner, lease_until: now + ttlMs });
336
+ return toNumber(changed) === 1;
337
+ };
338
+ const releaseLease = async (name, owner) => {
339
+ await knex(TABLES.leases).where({ name, owner }).update({ lease_until: 0 });
340
+ };
341
+ return {
342
+ mode: "database",
343
+ dialect: kind,
344
+ /**
345
+ * Increments a fixed-window counter in one atomic UPDATE and returns the
346
+ * value written by THIS update. The CASE expressions only read
347
+ * `window_start`, which is assigned last, so the result is the same under
348
+ * MySQL's left-to-right SET evaluation and the all-old-values semantics
349
+ * of PostgreSQL and SQLite.
350
+ *
351
+ * Reading the row in a separate statement after the UPDATE would return
352
+ * the count after later concurrent increments as well, so under a burst
353
+ * most callers would see a number above the limit and be rejected
354
+ * (measured: 2 of 48 parallel requests allowed with a limit of 10).
355
+ * PostgreSQL and SQLite therefore use `UPDATE ... RETURNING` (knex
356
+ * `returning`, SQLite >= 3.35); other dialects run UPDATE and SELECT in
357
+ * one transaction, where the row lock taken by the UPDATE keeps other
358
+ * writers out until the read is done.
359
+ */
360
+ async hit(key, windowMs, now = Date.now()) {
361
+ const cutoff = now - windowMs;
362
+ const data = {
363
+ hits: knex.raw("CASE WHEN window_start <= ? THEN 1 ELSE hits + 1 END", [cutoff]),
364
+ expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
365
+ now + windowMs,
366
+ now + windowMs
367
+ ]),
368
+ window_start: knex.raw("CASE WHEN window_start <= ? THEN ? ELSE window_start END", [
369
+ cutoff,
370
+ now
371
+ ])
372
+ };
373
+ const update = () => updateCounterReturning(
374
+ key,
375
+ (qb) => qb.update(data, [...COUNTER_COLUMNS]),
376
+ (trx) => trx(TABLES.counters).where({ k: key }).update(data)
377
+ );
378
+ let row = await update();
379
+ if (!row) {
380
+ await ensureCounterRow(key, now + windowMs);
381
+ row = await update();
382
+ }
383
+ return row || await readCounter(key) || { hits: 1, windowStart: now, blockedUntil: 0 };
384
+ },
385
+ /**
386
+ * Gives back one attempt counted by `hit` (for example when the request
387
+ * ended with a server error and must not count as a failed login).
388
+ */
389
+ async release(key) {
390
+ await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
391
+ },
392
+ peek: readCounter,
393
+ async block(key, untilMs) {
394
+ await ensureCounterRow(key, untilMs);
395
+ await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
396
+ blocked_until: untilMs,
397
+ expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
398
+ untilMs,
399
+ untilMs
400
+ ])
401
+ });
402
+ },
403
+ async clear(key) {
404
+ await knex(TABLES.counters).where({ k: key }).del();
405
+ },
406
+ async getRevision(name) {
407
+ const row = await knex(TABLES.counters).select("hits").where({ k: `rev:${name}` }).first();
408
+ return row ? toNumber(row.hits) : 0;
409
+ },
410
+ async bumpRevision(name) {
411
+ const key = `rev:${name}`;
412
+ await ensureCounterRow(key, NEVER_EXPIRES);
413
+ const data = { hits: knex.raw("hits + 1"), expires_at: NEVER_EXPIRES };
414
+ const row = await updateCounterReturning(
415
+ key,
416
+ (qb) => qb.update(data, [...COUNTER_COLUMNS]),
417
+ (trx) => trx(TABLES.counters).where({ k: key }).update(data)
418
+ );
419
+ return row ? row.hits : this.getRevision(name);
420
+ },
421
+ tryAcquireLease,
422
+ releaseLease,
423
+ /**
424
+ * Runs `fn` while holding a cluster-wide named lock.
425
+ *
426
+ * PostgreSQL: a transaction-level advisory lock (`pg_advisory_xact_lock`)
427
+ * on a dedicated transaction; it is released when that transaction ends,
428
+ * also when the process dies. `fn` runs on other connections, so it must
429
+ * not depend on that transaction. Other dialects: a lease row, polled
430
+ * until it is free or `waitMs` elapses; the lease expires after `ttlMs`
431
+ * if the holder dies.
432
+ */
433
+ async withLock(name, fn, { waitMs = 15e3, ttlMs = 3e4, owner } = {}) {
434
+ if (kind === "postgres") {
435
+ const timeout = Math.max(1, Math.floor(waitMs));
436
+ return knex.transaction(async (trx) => {
437
+ try {
438
+ await trx.raw(`SET LOCAL lock_timeout = '${timeout}ms'`);
439
+ await trx.raw("SELECT pg_advisory_xact_lock(?, hashtext(?))", [
440
+ PG_LOCK_NAMESPACE,
441
+ name
442
+ ]);
443
+ } catch (err) {
444
+ if (err?.code === "55P03") throw new LockTimeoutError(name);
445
+ throw err;
446
+ }
447
+ return fn();
448
+ });
449
+ }
450
+ const leaseName = `lock:${name}`;
451
+ const deadline = Date.now() + waitMs;
452
+ let delay = 25;
453
+ while (!await tryAcquireLease(leaseName, ttlMs, owner)) {
454
+ if (Date.now() >= deadline) throw new LockTimeoutError(name);
455
+ await sleep(delay + Math.floor(Math.random() * delay));
456
+ delay = Math.min(delay * 2, 250);
457
+ }
458
+ try {
459
+ return await fn();
460
+ } finally {
461
+ await releaseLease(leaseName, owner).catch(() => {
462
+ });
463
+ }
464
+ },
465
+ async cacheGet(key, now = Date.now()) {
466
+ const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: key }).andWhere("expires_at", ">", now).first();
467
+ if (!row || row.v === null || row.v === void 0) return null;
468
+ try {
469
+ return JSON.parse(row.v);
470
+ } catch {
471
+ return null;
472
+ }
473
+ },
474
+ async cacheSet(key, value, ttlMs, now = Date.now()) {
475
+ const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
476
+ await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
477
+ },
478
+ async prune(now = Date.now()) {
479
+ const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
480
+ const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
481
+ return toNumber(counters) + toNumber(cache);
482
+ }
483
+ };
484
+ }
485
+ var sharedMemory = createMemoryBackend();
486
+ var coordinators = /* @__PURE__ */ new WeakMap();
487
+ function createCoordinator({
488
+ database = null,
489
+ counterStore = null,
490
+ log = null,
491
+ owner = getInstanceId()
492
+ } = {}) {
493
+ let db = database;
494
+ let lastFallbackLogAt = 0;
495
+ const reportFallback = (operation, err) => {
496
+ const now = Date.now();
497
+ if (now - lastFallbackLogAt < 6e4) return;
498
+ lastFallbackLogAt = now;
499
+ log?.warn?.(
500
+ `[COORDINATION] ${operation} failed on the shared store, using process-local state:`,
501
+ err?.name || "Error"
502
+ );
503
+ };
504
+ const run = async (operation, sharedCall, memoryCall) => {
505
+ if (!db) return memoryCall();
506
+ try {
507
+ return await sharedCall(db);
508
+ } catch (err) {
509
+ if (err instanceof LockTimeoutError) throw err;
510
+ reportFallback(operation, err);
511
+ return memoryCall();
512
+ }
513
+ };
514
+ const counterCall = async (operation, method, args) => {
515
+ if (counterStore && typeof counterStore[method] === "function") {
516
+ try {
517
+ return await counterStore[method](...args);
518
+ } catch (err) {
519
+ reportFallback(`${operation} (custom store)`, err);
520
+ }
521
+ }
522
+ return run(
523
+ operation,
524
+ (backend) => backend[method](...args),
525
+ () => sharedMemory[method](...args)
526
+ );
527
+ };
528
+ return {
529
+ owner,
530
+ get mode() {
531
+ if (counterStore) return db ? "custom+database" : "custom+memory";
532
+ return db ? "database" : "memory";
533
+ },
534
+ get dialect() {
535
+ return db?.dialect || null;
536
+ },
537
+ /** Switches the coordinator to the database backend. */
538
+ attachDatabase(backend) {
539
+ db = backend;
540
+ },
541
+ /** Switches the coordinator back to process-local state. */
542
+ detachDatabase() {
543
+ db = null;
544
+ },
545
+ /**
546
+ * Increments the fixed-window counter `key`.
547
+ * @returns {Promise<{hits: number, windowStart: number, blockedUntil: number}>}
548
+ */
549
+ hit(key, windowMs) {
550
+ assertKey(key);
551
+ return counterCall("counter increment", "hit", [key, windowMs]);
552
+ },
553
+ /** @returns {Promise<{hits: number, windowStart: number, blockedUntil: number}|null>} */
554
+ peek(key) {
555
+ assertKey(key);
556
+ return counterCall("counter read", "peek", [key]);
557
+ },
558
+ /** Raises the block deadline of `key` to `untilMs` (never lowers it). */
559
+ block(key, untilMs) {
560
+ assertKey(key);
561
+ return counterCall("counter block", "block", [key, untilMs]);
562
+ },
563
+ /** Removes counter `key`. */
564
+ clear(key) {
565
+ assertKey(key);
566
+ return counterCall("counter clear", "clear", [key]);
567
+ },
568
+ /**
569
+ * Gives back one hit of counter `key`. Optional for a custom
570
+ * `counterStore`: a store without `release` keeps the hit.
571
+ */
572
+ async release(key) {
573
+ assertKey(key);
574
+ if (counterStore && typeof counterStore.release !== "function") return;
575
+ return counterCall("counter release", "release", [key]);
576
+ },
577
+ getRevision(name) {
578
+ return run(
579
+ "revision read",
580
+ (backend) => backend.getRevision(name),
581
+ () => sharedMemory.getRevision(name)
582
+ );
583
+ },
584
+ bumpRevision(name) {
585
+ return run(
586
+ "revision bump",
587
+ (backend) => backend.bumpRevision(name),
588
+ () => sharedMemory.bumpRevision(name)
589
+ );
590
+ },
591
+ /**
592
+ * Takes the lease `name` for `ttlMs` unless another process holds an
593
+ * unexpired lease. Re-acquiring an own lease extends it.
594
+ * @returns {Promise<boolean>}
595
+ */
596
+ tryAcquireLease(name, ttlMs) {
597
+ return run(
598
+ "lease acquire",
599
+ (backend) => backend.tryAcquireLease(name, ttlMs, owner),
600
+ () => sharedMemory.tryAcquireLease(name, ttlMs, owner)
601
+ );
602
+ },
603
+ releaseLease(name) {
604
+ return run(
605
+ "lease release",
606
+ (backend) => backend.releaseLease(name, owner),
607
+ () => sharedMemory.releaseLease(name, owner)
608
+ );
609
+ },
610
+ /**
611
+ * Runs `fn` inside the cluster-wide critical section `name`. A process-
612
+ * local mutex is always taken first, so concurrent callers in one process
613
+ * do not compete for database connections.
614
+ *
615
+ * @template T
616
+ * @param {string} name
617
+ * @param {() => Promise<T>} fn
618
+ * @param {{waitMs?: number, ttlMs?: number}} [options]
619
+ * @returns {Promise<T>}
620
+ * @throws {LockTimeoutError} When the lock could not be taken in time
621
+ */
622
+ withLock(name, fn, options = {}) {
623
+ const held = heldLocks.getStore();
624
+ if (held && held.has(name)) return fn();
625
+ const inner = () => heldLocks.run(/* @__PURE__ */ new Set([...held || [], name]), fn);
626
+ return sharedMemory.withLock(`local:${name}`, async () => {
627
+ if (!db) return inner();
628
+ let entered = false;
629
+ try {
630
+ return await db.withLock(
631
+ name,
632
+ () => {
633
+ entered = true;
634
+ return inner();
635
+ },
636
+ { ...options, owner }
637
+ );
638
+ } catch (err) {
639
+ if (entered || err instanceof LockTimeoutError) throw err;
640
+ reportFallback("lock", err);
641
+ return inner();
642
+ }
643
+ });
644
+ },
645
+ cacheGet(key) {
646
+ assertKey(key);
647
+ return run(
648
+ "cache read",
649
+ (backend) => backend.cacheGet(key),
650
+ () => sharedMemory.cacheGet(key)
651
+ );
652
+ },
653
+ cacheSet(key, value, ttlMs) {
654
+ assertKey(key);
655
+ return run(
656
+ "cache write",
657
+ (backend) => backend.cacheSet(key, value, ttlMs),
658
+ () => sharedMemory.cacheSet(key, value, ttlMs)
659
+ );
660
+ },
661
+ prune() {
662
+ return run(
663
+ "prune",
664
+ (backend) => backend.prune(),
665
+ () => sharedMemory.prune()
666
+ );
667
+ }
668
+ };
669
+ }
670
+ function getCoordinator(strapi2) {
671
+ const key = strapi2 && typeof strapi2 === "object" ? strapi2 : sharedMemory;
672
+ let coordinator = coordinators.get(key);
673
+ if (!coordinator) {
674
+ const config = readCoordinationConfig(strapi2);
675
+ coordinator = createCoordinator({
676
+ counterStore: config.counterStore,
677
+ log: strapi2?.log || null
678
+ });
679
+ coordinators.set(key, coordinator);
680
+ }
681
+ return coordinator;
682
+ }
683
+ function readCoordinationConfig(strapi2) {
684
+ let raw;
685
+ try {
686
+ raw = strapi2?.config?.get?.("plugin::magic-sessionmanager.coordination") || null;
687
+ } catch {
688
+ raw = null;
689
+ }
690
+ const config = raw && typeof raw === "object" ? raw : {};
691
+ const counterStore = config.counterStore && typeof config.counterStore === "object" ? config.counterStore : null;
692
+ return { enabled: config.enabled !== false, counterStore };
693
+ }
694
+ async function initCoordination(strapi2, log = strapi2?.log) {
695
+ const coordinator = getCoordinator(strapi2);
696
+ const config = readCoordinationConfig(strapi2);
697
+ if (!config.enabled) {
698
+ log?.info?.("[COORDINATION] Disabled by config; using process-local state");
699
+ return coordinator;
700
+ }
701
+ const knex = strapi2?.db?.connection;
702
+ if (typeof knex !== "function" || !knex.schema) {
703
+ log?.warn?.("[COORDINATION] No database connection; using process-local state");
704
+ return coordinator;
705
+ }
706
+ try {
707
+ await ensureTables(knex);
708
+ coordinator.attachDatabase(
709
+ createDatabaseBackend({
710
+ knex,
711
+ dialect: strapi2.db?.dialect?.client || knex.client?.config?.client
712
+ })
713
+ );
714
+ log?.info?.(`[COORDINATION] Shared state enabled (${coordinator.mode})`);
715
+ } catch (err) {
716
+ log?.error?.(
717
+ "[COORDINATION] Could not prepare shared tables; using process-local state:",
718
+ err?.name || "Error"
719
+ );
720
+ }
721
+ return coordinator;
722
+ }
723
+ module.exports = {
724
+ TABLES,
725
+ LockTimeoutError,
726
+ createCoordinator,
727
+ createDatabaseBackend,
728
+ createMemoryBackend,
729
+ ensureTables,
730
+ getCoordinator,
731
+ getHostFingerprint,
732
+ getInstanceId,
733
+ hashedKey,
734
+ initCoordination,
735
+ normalizeDialect,
736
+ __resetMemoryForTests() {
737
+ sharedMemory.reset();
738
+ }
739
+ };
740
+ }
741
+ });
742
+
743
+ // server/src/utils/plugin-store.js
744
+ var require_plugin_store = __commonJS({
745
+ "server/src/utils/plugin-store.js"(exports, module) {
746
+ "use strict";
747
+ var { getCoordinator } = require_coordination();
748
+ var PLUGIN_ID = "magic-sessionmanager";
749
+ var CORE_STORE_UID = "strapi::core-store";
750
+ function coreStoreKey(key) {
751
+ return `plugin_${PLUGIN_ID}_${key}`;
752
+ }
753
+ async function collapseDuplicateStoreRows(strapi2, key) {
754
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
755
+ if (!query || typeof query.findMany !== "function") return 0;
756
+ const rows = await query.findMany({
757
+ where: { key: coreStoreKey(key), environment: null, tag: null },
758
+ select: ["id"],
759
+ orderBy: { id: "desc" }
760
+ });
761
+ if (!Array.isArray(rows) || rows.length < 2) return 0;
762
+ const extraIds = rows.slice(1).map((row) => row.id);
763
+ const result = await query.deleteMany({ where: { id: { $in: extraIds } } });
764
+ return Number(result?.count) || 0;
765
+ }
766
+ async function withPluginStoreKey(strapi2, key, fn) {
767
+ const store = strapi2.store({ type: "plugin", name: PLUGIN_ID });
768
+ return getCoordinator(strapi2).withLock(`store:${key}`, async () => {
769
+ try {
770
+ const removed = await collapseDuplicateStoreRows(strapi2, key);
771
+ if (removed > 0) {
772
+ strapi2.log?.warn?.(
773
+ `[magic-sessionmanager] [STORE] Removed ${removed} duplicate store row(s) for "${key}"`
774
+ );
775
+ }
776
+ } catch (err) {
777
+ strapi2.log?.debug?.(
778
+ "[magic-sessionmanager] [STORE] Duplicate check failed:",
779
+ err?.name || "Error"
780
+ );
781
+ }
782
+ return fn(store);
783
+ });
784
+ }
785
+ async function setPluginStoreValue(strapi2, key, value) {
786
+ await withPluginStoreKey(strapi2, key, (store) => store.set({ key, value }));
787
+ }
788
+ var LEGACY_LICENSE_STORE_KEYS = Object.freeze(["licenseKey", "lastValidated", "deviceId"]);
789
+ async function removeLegacyLicenseData(strapi2) {
790
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
791
+ if (!query || typeof query.deleteMany !== "function") return 0;
792
+ const result = await query.deleteMany({
793
+ where: { key: { $in: LEGACY_LICENSE_STORE_KEYS.map(coreStoreKey) } }
794
+ });
795
+ return Number(result?.count) || 0;
796
+ }
797
+ module.exports = {
798
+ LEGACY_LICENSE_STORE_KEYS,
799
+ PLUGIN_ID,
800
+ collapseDuplicateStoreRows,
801
+ coreStoreKey,
802
+ removeLegacyLicenseData,
803
+ setPluginStoreValue,
804
+ withPluginStoreKey
805
+ };
806
+ }
807
+ });
808
+
88
809
  // server/src/utils/content-api-permissions.js
89
810
  var require_content_api_permissions = __commonJS({
90
811
  "server/src/utils/content-api-permissions.js"(exports, module) {
91
812
  "use strict";
813
+ var { withPluginStoreKey } = require_plugin_store();
92
814
  var CONTENT_API_PERMISSIONS_VERSION = 2;
93
- var MAGIC_SESSIONMANAGER_STORE = "magic-sessionmanager";
94
815
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
95
816
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
96
817
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
97
818
  if (role?.type !== "authenticated") return false;
98
- const pluginStore = strapi2.store({ type: "plugin", name: MAGIC_SESSIONMANAGER_STORE });
99
- const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
100
- if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
101
- await pluginStore.set({
102
- key: CONTENT_API_PERMISSIONS_VERSION_KEY,
103
- value: CONTENT_API_PERMISSIONS_VERSION
819
+ return withPluginStoreKey(strapi2, CONTENT_API_PERMISSIONS_VERSION_KEY, async (pluginStore) => {
820
+ const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
821
+ if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
822
+ await pluginStore.set({
823
+ key: CONTENT_API_PERMISSIONS_VERSION_KEY,
824
+ value: CONTENT_API_PERMISSIONS_VERSION
825
+ });
826
+ return true;
104
827
  });
105
- return true;
106
828
  }
107
829
  function createContentApiPermissionsLifecycle(strapi2) {
108
830
  return {
@@ -382,7 +1104,11 @@ var require_encryption = __commonJS({
382
1104
  if (!token) return null;
383
1105
  return crypto.createHash("sha256").update(token).digest("hex");
384
1106
  }
1107
+ function getEncryptionKeyCheck() {
1108
+ return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
1109
+ }
385
1110
  module.exports = {
1111
+ getEncryptionKeyCheck,
386
1112
  encryptToken,
387
1113
  decryptToken,
388
1114
  generateSessionId,
@@ -441,13 +1167,18 @@ var require_resolve_user = __commonJS({
441
1167
  var require_settings_loader = __commonJS({
442
1168
  "server/src/utils/settings-loader.js"(exports, module) {
443
1169
  "use strict";
1170
+ var { getCoordinator } = require_coordination();
444
1171
  var PLUGIN_ID = "magic-sessionmanager";
445
1172
  var SETTINGS_KEY = "settings";
446
1173
  var CACHE_TTL_MS = 30 * 1e3;
1174
+ var REVISION_CHECK_MS = 2 * 1e3;
1175
+ var SETTINGS_REVISION = "settings";
447
1176
  var GEO_IP_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
448
1177
  var GEO_LOOKUP_FAILURE_MODES = /* @__PURE__ */ new Set(["auto", "allow", "block"]);
449
1178
  var cached = null;
450
1179
  var cachedAt = 0;
1180
+ var cachedRevision = null;
1181
+ var revisionCheckedAt = 0;
451
1182
  function toIntInRange(value, fallback, min, max) {
452
1183
  const n = Number.parseInt(value, 10);
453
1184
  if (!Number.isFinite(n)) return fallback;
@@ -561,8 +1292,23 @@ var require_settings_loader = __commonJS({
561
1292
  }
562
1293
  async function getPluginSettings(strapi2) {
563
1294
  const now = Date.now();
1295
+ const coordinator = getCoordinator(strapi2);
564
1296
  if (cached && now - cachedAt < CACHE_TTL_MS) {
565
- return cached;
1297
+ if (now - revisionCheckedAt < REVISION_CHECK_MS) return cached;
1298
+ revisionCheckedAt = now;
1299
+ let revision2;
1300
+ try {
1301
+ revision2 = await coordinator.getRevision(SETTINGS_REVISION);
1302
+ } catch {
1303
+ return cached;
1304
+ }
1305
+ if (revision2 === cachedRevision) return cached;
1306
+ }
1307
+ let revision;
1308
+ try {
1309
+ revision = await coordinator.getRevision(SETTINGS_REVISION);
1310
+ } catch {
1311
+ revision = null;
566
1312
  }
567
1313
  const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
568
1314
  let storedSettings;
@@ -579,6 +1325,8 @@ var require_settings_loader = __commonJS({
579
1325
  const merged = { ...staticConfig, ...storedSettings };
580
1326
  cached = merged;
581
1327
  cachedAt = now;
1328
+ cachedRevision = revision;
1329
+ revisionCheckedAt = now;
582
1330
  return merged;
583
1331
  }
584
1332
  function getPluginSettingsSync(strapi2) {
@@ -588,11 +1336,30 @@ var require_settings_loader = __commonJS({
588
1336
  function invalidateSettingsCache() {
589
1337
  cached = null;
590
1338
  cachedAt = 0;
1339
+ cachedRevision = null;
1340
+ revisionCheckedAt = 0;
1341
+ }
1342
+ async function getSettingsRevision(strapi2) {
1343
+ return getCoordinator(strapi2).getRevision(SETTINGS_REVISION);
1344
+ }
1345
+ async function notifySettingsChanged(strapi2) {
1346
+ invalidateSettingsCache();
1347
+ try {
1348
+ return await getCoordinator(strapi2).bumpRevision(SETTINGS_REVISION);
1349
+ } catch (err) {
1350
+ strapi2?.log?.warn?.(
1351
+ `[${PLUGIN_ID}] settings-loader: could not publish the settings revision:`,
1352
+ err?.name || "Error"
1353
+ );
1354
+ return null;
1355
+ }
591
1356
  }
592
1357
  module.exports = {
593
1358
  getPluginSettings,
594
1359
  getPluginSettingsSync,
595
1360
  invalidateSettingsCache,
1361
+ notifySettingsChanged,
1362
+ getSettingsRevision,
596
1363
  normalizeStoredSettings,
597
1364
  normalizeRetentionDays,
598
1365
  getSessionCreationGraceMs,
@@ -5133,7 +5900,7 @@ var require_bootstrap = __commonJS({
5133
5900
  "server/src/bootstrap.js"(exports, module) {
5134
5901
  "use strict";
5135
5902
  var getClientIp = require_getClientIp();
5136
- var { encryptToken, hashToken } = require_encryption();
5903
+ var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
5137
5904
  var { createLogger } = require_logger();
5138
5905
  var { resolveUserDocumentId } = require_resolve_user();
5139
5906
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -5143,6 +5910,13 @@ var require_bootstrap = __commonJS({
5143
5910
  var { REVOCATION_UID } = require_session_revocation();
5144
5911
  var { getNativeSessionManager } = require_native_session_manager();
5145
5912
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
5913
+ var {
5914
+ getCoordinator,
5915
+ hashedKey,
5916
+ initCoordination,
5917
+ LockTimeoutError
5918
+ } = require_coordination();
5919
+ var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
5146
5920
  var {
5147
5921
  classifyJwtIssuingRequest,
5148
5922
  isFailedLoginTrackedPath,
@@ -5156,6 +5930,12 @@ var require_bootstrap = __commonJS({
5156
5930
  stripAuthTokensFromResponse
5157
5931
  } = require_refresh_token();
5158
5932
  var SESSION_UID = "plugin::magic-sessionmanager.session";
5933
+ var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
5934
+ var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5935
+ var JOB_LEASES = Object.freeze({
5936
+ idleCleanup: "job:idle-cleanup",
5937
+ retention: "job:retention"
5938
+ });
5159
5939
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
5160
5940
  var deferredContentApiPermissionSetup = /* @__PURE__ */ new WeakMap();
5161
5941
  async function getRequestSettings(strapi2, ctx) {
@@ -5170,6 +5950,16 @@ var require_bootstrap = __commonJS({
5170
5950
  }
5171
5951
  return settings;
5172
5952
  }
5953
+ async function removeLegacyLicenseRows(strapi2, log) {
5954
+ try {
5955
+ const removed = await removeLegacyLicenseData(strapi2);
5956
+ if (removed > 0) {
5957
+ log.info(`[CLEANUP] Removed ${removed} stored value(s) of the former license feature`);
5958
+ }
5959
+ } catch (err) {
5960
+ log.warn("[CLEANUP] Could not remove former license data:", err?.name || "Error");
5961
+ }
5962
+ }
5173
5963
  module.exports = async ({ strapi: strapi2 }) => {
5174
5964
  const log = createLogger(strapi2);
5175
5965
  log.info("[START] Bootstrap starting...");
@@ -5180,21 +5970,36 @@ var require_bootstrap = __commonJS({
5180
5970
  throw e;
5181
5971
  }
5182
5972
  try {
5973
+ const coordinator = await initCoordination(strapi2, log);
5974
+ await checkEncryptionKeyConsistency(strapi2, log);
5183
5975
  await ensureSessionLookupIndexes(strapi2, log);
5184
5976
  await registerSessionAwareAuthStrategy(strapi2);
5185
- const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
5186
- await licenseGuardService.initialize();
5187
- log.info("[SUCCESS] Session Manager active - all features are available without a license key");
5977
+ await removeLegacyLicenseRows(strapi2, log);
5188
5978
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
5189
5979
  if (!strapi2.sessionManagerIntervals) {
5190
5980
  strapi2.sessionManagerIntervals = {};
5191
5981
  }
5982
+ const runIdleCleanupIfLeader = async (intervalMs, useDbDirect) => {
5983
+ const leaseMs = Math.max(60 * 1e3, intervalMs - 30 * 1e3);
5984
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.idleCleanup, leaseMs)) {
5985
+ log.debug("[CLEANUP] Another instance holds the cleanup lease; skipping this run");
5986
+ return;
5987
+ }
5988
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
5989
+ await service.cleanupInactiveSessions({ useDbDirect });
5990
+ try {
5991
+ await coordinator.prune();
5992
+ } catch (err) {
5993
+ log.debug("[CLEANUP] Shared counter pruning failed:", err?.name || "Error");
5994
+ }
5995
+ };
5192
5996
  log.info("Running initial session cleanup...");
5193
5997
  try {
5194
5998
  const settings = await getPluginSettings(strapi2);
5195
- await sessionService.cleanupInactiveSessions({
5196
- useDbDirect: settings.cleanupUseDbDirect === true
5197
- });
5999
+ await runIdleCleanupIfLeader(
6000
+ Math.max(5 * 60 * 1e3, settings.cleanupInterval || 30 * 60 * 1e3),
6001
+ settings.cleanupUseDbDirect === true
6002
+ );
5198
6003
  } catch (cleanupErr) {
5199
6004
  log.warn("Initial cleanup failed:", cleanupErr?.name || "Error");
5200
6005
  }
@@ -5209,8 +6014,7 @@ var require_bootstrap = __commonJS({
5209
6014
  }
5210
6015
  const handle = setTimeout(async () => {
5211
6016
  try {
5212
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5213
- await service.cleanupInactiveSessions({ useDbDirect });
6017
+ await runIdleCleanupIfLeader(intervalMs, useDbDirect);
5214
6018
  } catch (err) {
5215
6019
  log.error("Periodic cleanup error:", err?.name || "Error");
5216
6020
  }
@@ -5219,7 +6023,6 @@ var require_bootstrap = __commonJS({
5219
6023
  strapi2.sessionManagerIntervals.cleanupTimeout = handle;
5220
6024
  };
5221
6025
  await scheduleIdleCleanup();
5222
- const RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5223
6026
  const scheduleRetention = async () => {
5224
6027
  let useDbDirect = false;
5225
6028
  try {
@@ -5229,8 +6032,7 @@ var require_bootstrap = __commonJS({
5229
6032
  }
5230
6033
  const handle = setTimeout(async () => {
5231
6034
  try {
5232
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5233
- await service.deleteOldSessions({ useDbDirect });
6035
+ await runRetentionIfLeader(useDbDirect);
5234
6036
  } catch (err) {
5235
6037
  log.error("Retention cleanup error:", err?.name || "Error");
5236
6038
  }
@@ -5238,8 +6040,23 @@ var require_bootstrap = __commonJS({
5238
6040
  }, RETENTION_INTERVAL_MS);
5239
6041
  strapi2.sessionManagerIntervals.retentionTimeout = handle;
5240
6042
  };
6043
+ const runRetentionIfLeader = async (useDbDirect) => {
6044
+ const leaseMs = RETENTION_INTERVAL_MS - 60 * 60 * 1e3;
6045
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.retention, leaseMs)) {
6046
+ log.debug("[RETENTION] Another instance holds the retention lease; skipping this run");
6047
+ return;
6048
+ }
6049
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
6050
+ await service.deleteOldSessions({ useDbDirect });
6051
+ };
5241
6052
  strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
5242
- () => {
6053
+ async () => {
6054
+ try {
6055
+ const settings = await getPluginSettings(strapi2);
6056
+ await runRetentionIfLeader(settings.cleanupUseDbDirect === true);
6057
+ } catch (err) {
6058
+ log.error("Retention cleanup error:", err?.name || "Error");
6059
+ }
5243
6060
  scheduleRetention();
5244
6061
  },
5245
6062
  5 * 60 * 1e3
@@ -5269,6 +6086,24 @@ var require_bootstrap = __commonJS({
5269
6086
  log.error("[ERROR] Bootstrap error:", err?.name || "Error");
5270
6087
  }
5271
6088
  };
6089
+ async function checkEncryptionKeyConsistency(strapi2, log) {
6090
+ const coordinator = getCoordinator(strapi2);
6091
+ if (!coordinator.dialect) return;
6092
+ try {
6093
+ const current = getEncryptionKeyCheck();
6094
+ const stored = await coordinator.cacheGet("instance:encryption-key-check");
6095
+ if (stored && stored !== current) {
6096
+ log.error(
6097
+ "[CONFIG] SESSION_ENCRYPTION_KEY differs from the key another instance used. Set the same value on every replica and worker, otherwise stored tokens cannot be read across instances."
6098
+ );
6099
+ }
6100
+ if (stored !== current) {
6101
+ await coordinator.cacheSet("instance:encryption-key-check", current, Infinity);
6102
+ }
6103
+ } catch (err) {
6104
+ log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
6105
+ }
6106
+ }
5272
6107
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
5273
6108
  strapi2.server.use(async (ctx, next) => {
5274
6109
  if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
@@ -5478,31 +6313,9 @@ var require_bootstrap = __commonJS({
5478
6313
  }
5479
6314
  }
5480
6315
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
5481
- const WINDOW_MS = 15 * 60 * 1e3;
5482
- const failed = /* @__PURE__ */ new Map();
5483
- const prune = (now) => {
5484
- if (failed.size < 5e3) return;
5485
- for (const [k, v] of failed) {
5486
- if (v.blockedUntil < now && now - v.firstFailAt > WINDOW_MS) failed.delete(k);
5487
- }
5488
- };
5489
- const recordFailure = (ip, max) => {
5490
- const now = Date.now();
5491
- prune(now);
5492
- const entry = failed.get(ip) || { count: 0, firstFailAt: now, blockedUntil: 0 };
5493
- if (now - entry.firstFailAt > WINDOW_MS) {
5494
- entry.count = 0;
5495
- entry.firstFailAt = now;
5496
- entry.blockedUntil = 0;
5497
- }
5498
- entry.count += 1;
5499
- if (entry.count >= max) {
5500
- entry.blockedUntil = now + WINDOW_MS;
5501
- }
5502
- failed.set(ip, entry);
5503
- return entry;
5504
- };
5505
- const clearFailures = (ip) => failed.delete(ip);
6316
+ const WINDOW_MS = FAILED_LOGIN_WINDOW_MS;
6317
+ const coordinator = getCoordinator(strapi2);
6318
+ const keyFor = (ip) => hashedKey("lf", ip);
5506
6319
  strapi2.server.use(async (ctx, next) => {
5507
6320
  if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
5508
6321
  const settings = await getRequestSettings(strapi2, ctx);
@@ -5510,10 +6323,15 @@ var require_bootstrap = __commonJS({
5510
6323
  if (maxFailed <= 0) return next();
5511
6324
  const ip = getClientIp(ctx);
5512
6325
  if (!ip || ip === "unknown") return next();
6326
+ const key = keyFor(ip);
5513
6327
  const now = Date.now();
5514
- const existing = failed.get(ip);
5515
- if (existing && existing.blockedUntil > now) {
5516
- const retrySec = Math.ceil((existing.blockedUntil - now) / 1e3);
6328
+ let existing = null;
6329
+ try {
6330
+ existing = await coordinator.peek(key);
6331
+ } catch (err) {
6332
+ log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
6333
+ }
6334
+ const rejectLocked = (retrySec) => {
5517
6335
  ctx.set("Retry-After", String(retrySec));
5518
6336
  log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
5519
6337
  ctx.status = 429;
@@ -5525,20 +6343,80 @@ var require_bootstrap = __commonJS({
5525
6343
  details: { retryAfter: retrySec }
5526
6344
  }
5527
6345
  };
6346
+ };
6347
+ if (existing && existing.blockedUntil > now) {
6348
+ rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
5528
6349
  return;
5529
6350
  }
5530
- await next();
5531
- if (ctx.status === 200 && ctx.body && ctx.body.jwt) {
5532
- clearFailures(ip);
5533
- } else if (ctx.status >= 400 && ctx.status < 500 && ctx.status !== 429) {
5534
- const entry = recordFailure(ip, maxFailed);
5535
- if (entry.blockedUntil > now) {
5536
- log.warn(`[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`);
6351
+ let reserved = null;
6352
+ try {
6353
+ reserved = await coordinator.hit(key, WINDOW_MS);
6354
+ } catch (err) {
6355
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
6356
+ }
6357
+ if (reserved && reserved.hits > maxFailed) {
6358
+ try {
6359
+ await coordinator.release(key);
6360
+ } catch (err) {
6361
+ log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
6362
+ }
6363
+ ctx.set("Retry-After", "1");
6364
+ ctx.status = 429;
6365
+ ctx.body = {
6366
+ error: {
6367
+ status: 429,
6368
+ name: "TooManyRequestsError",
6369
+ message: "Too many login attempts at once. Please try again.",
6370
+ details: { retryAfter: 1 }
6371
+ }
6372
+ };
6373
+ return;
6374
+ }
6375
+ let thrown = null;
6376
+ try {
6377
+ await next();
6378
+ } catch (err) {
6379
+ thrown = err;
6380
+ }
6381
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
6382
+ try {
6383
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) {
6384
+ await coordinator.clear(key);
6385
+ } else if (status >= 400 && status < 500 && status !== 429) {
6386
+ if (reserved && reserved.hits >= maxFailed) {
6387
+ await coordinator.block(key, Date.now() + WINDOW_MS);
6388
+ log.warn(
6389
+ `[LOCKOUT] Client locked for 15min after ${reserved.hits} failed login attempts`
6390
+ );
6391
+ }
6392
+ } else if (reserved) {
6393
+ await coordinator.release(key);
5537
6394
  }
6395
+ } catch (err) {
6396
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
5538
6397
  }
6398
+ if (thrown) throw thrown;
5539
6399
  });
5540
6400
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
5541
6401
  }
6402
+ function statusOfThrownError(err) {
6403
+ const status = Number(err?.status ?? err?.statusCode);
6404
+ if (Number.isInteger(status) && status >= 400 && status < 600) return status;
6405
+ const byName = {
6406
+ UnauthorizedError: 401,
6407
+ ForbiddenError: 403,
6408
+ NotFoundError: 404,
6409
+ PayloadTooLargeError: 413,
6410
+ RateLimitError: 429,
6411
+ NotImplementedError: 501,
6412
+ ApplicationError: 400,
6413
+ ValidationError: 400,
6414
+ YupValidationError: 400,
6415
+ PaginationError: 400,
6416
+ PolicyError: 403
6417
+ };
6418
+ return byName[err?.name] || 500;
6419
+ }
5542
6420
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
5543
6421
  strapi2.server.use(async (ctx, next) => {
5544
6422
  const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
@@ -6017,77 +6895,112 @@ var require_bootstrap = __commonJS({
6017
6895
  }
6018
6896
  async function ensureContentApiPermissions(strapi2, log) {
6019
6897
  try {
6020
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
6021
- const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6022
- if (storedVersion === void 0) {
6023
- const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6024
- if (legacyFlag === true) {
6025
- await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6026
- }
6027
- }
6028
- const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6029
- if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6030
- log.debug("Content-API permissions already at current version (skipping auto-setup)");
6031
- return true;
6032
- }
6033
- const ROLE_UID = "plugin::users-permissions.role";
6034
- const PERMISSION_UID = "plugin::users-permissions.permission";
6035
- const roles = await strapi2.documents(ROLE_UID).findMany({
6036
- filters: { type: "authenticated" },
6037
- fields: ["id"],
6038
- limit: 1
6039
- });
6040
- const authenticatedRole = roles?.[0];
6041
- if (!authenticatedRole) {
6042
- log.warn("Authenticated role not found - skipping permission setup");
6898
+ return await withPluginStoreKey(
6899
+ strapi2,
6900
+ "contentApiPermissionsVersion",
6901
+ (pluginStore) => ensureContentApiPermissionsLocked(strapi2, log, pluginStore)
6902
+ );
6903
+ } catch (err) {
6904
+ if (err instanceof LockTimeoutError) {
6905
+ log.warn("Content-API permission setup is busy on another instance; will retry");
6043
6906
  return false;
6044
6907
  }
6045
- const requiredActions = [
6046
- "plugin::magic-sessionmanager.session.logout",
6047
- "plugin::magic-sessionmanager.session.logoutAll",
6048
- "plugin::magic-sessionmanager.session.logoutOthers",
6049
- "plugin::magic-sessionmanager.session.getOwnSessions",
6050
- "plugin::magic-sessionmanager.session.getUserSessions",
6051
- "plugin::magic-sessionmanager.session.getCurrentSession",
6052
- "plugin::magic-sessionmanager.session.terminateOwnSession"
6053
- ];
6054
- const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6055
- filters: {
6056
- role: authenticatedRole.id,
6057
- action: { $in: requiredActions }
6058
- },
6059
- fields: ["action"],
6060
- limit: requiredActions.length
6061
- });
6062
- const existingActions = existingPermissions.map((p) => p.action);
6063
- const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6064
- if (missingActions.length === 0) {
6065
- await pluginStore.set({
6066
- key: "contentApiPermissionsVersion",
6067
- value: CONTENT_API_PERMISSIONS_VERSION
6068
- });
6069
- log.debug("Content-API permissions already configured");
6070
- return true;
6071
- }
6072
- for (const action of missingActions) {
6073
- await strapi2.documents(PERMISSION_UID).create({
6074
- data: { action, role: authenticatedRole.id }
6075
- });
6076
- log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6908
+ log.warn("Could not auto-configure permissions:", err?.name || "Error");
6909
+ log.warn(
6910
+ "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6911
+ );
6912
+ return false;
6913
+ }
6914
+ }
6915
+ async function ensureContentApiPermissionsLocked(strapi2, log, pluginStore) {
6916
+ const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6917
+ if (storedVersion === void 0 || storedVersion === null) {
6918
+ const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6919
+ if (legacyFlag === true) {
6920
+ await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6077
6921
  }
6922
+ }
6923
+ const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6924
+ if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6925
+ log.debug("Content-API permissions already at current version (skipping auto-setup)");
6926
+ return true;
6927
+ }
6928
+ const ROLE_UID = "plugin::users-permissions.role";
6929
+ const PERMISSION_UID = "plugin::users-permissions.permission";
6930
+ const roles = await strapi2.documents(ROLE_UID).findMany({
6931
+ filters: { type: "authenticated" },
6932
+ fields: ["id"],
6933
+ limit: 1
6934
+ });
6935
+ const authenticatedRole = roles?.[0];
6936
+ if (!authenticatedRole) {
6937
+ log.info(
6938
+ "Authenticated role does not exist yet; permission setup runs again on the first Session Manager API request"
6939
+ );
6940
+ return false;
6941
+ }
6942
+ const requiredActions = [
6943
+ "plugin::magic-sessionmanager.session.logout",
6944
+ "plugin::magic-sessionmanager.session.logoutAll",
6945
+ "plugin::magic-sessionmanager.session.logoutOthers",
6946
+ "plugin::magic-sessionmanager.session.getOwnSessions",
6947
+ "plugin::magic-sessionmanager.session.getUserSessions",
6948
+ "plugin::magic-sessionmanager.session.getCurrentSession",
6949
+ "plugin::magic-sessionmanager.session.terminateOwnSession"
6950
+ ];
6951
+ const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6952
+ filters: {
6953
+ role: authenticatedRole.id,
6954
+ action: { $in: requiredActions }
6955
+ },
6956
+ fields: ["id", "documentId", "action"],
6957
+ sort: { id: "asc" },
6958
+ limit: requiredActions.length * 10
6959
+ });
6960
+ await removeDuplicatePermissions(strapi2, log, PERMISSION_UID, existingPermissions);
6961
+ const existingActions = existingPermissions.map((p) => p.action);
6962
+ const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6963
+ if (missingActions.length === 0) {
6078
6964
  await pluginStore.set({
6079
6965
  key: "contentApiPermissionsVersion",
6080
6966
  value: CONTENT_API_PERMISSIONS_VERSION
6081
6967
  });
6082
- log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6968
+ log.debug("Content-API permissions already configured");
6083
6969
  return true;
6084
- } catch (err) {
6085
- log.warn("Could not auto-configure permissions:", err?.name || "Error");
6086
- log.warn(
6087
- "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6088
- );
6089
- return false;
6090
6970
  }
6971
+ for (const action of missingActions) {
6972
+ await strapi2.documents(PERMISSION_UID).create({
6973
+ data: { action, role: authenticatedRole.id }
6974
+ });
6975
+ log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6976
+ }
6977
+ await pluginStore.set({
6978
+ key: "contentApiPermissionsVersion",
6979
+ value: CONTENT_API_PERMISSIONS_VERSION
6980
+ });
6981
+ log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6982
+ return true;
6983
+ }
6984
+ async function removeDuplicatePermissions(strapi2, log, permissionUid, permissions) {
6985
+ const seen = /* @__PURE__ */ new Set();
6986
+ let removed = 0;
6987
+ for (const permission of permissions || []) {
6988
+ if (!seen.has(permission.action)) {
6989
+ seen.add(permission.action);
6990
+ continue;
6991
+ }
6992
+ if (!permission.documentId) continue;
6993
+ try {
6994
+ await strapi2.documents(permissionUid).delete({ documentId: permission.documentId });
6995
+ removed++;
6996
+ } catch (err) {
6997
+ log.debug("[PERMISSION] Could not remove a duplicate permission:", err?.name || "Error");
6998
+ }
6999
+ }
7000
+ if (removed > 0) {
7001
+ log.warn(`[PERMISSION] Removed ${removed} duplicate Content-API permission row(s)`);
7002
+ }
7003
+ return removed;
6091
7004
  }
6092
7005
  function mountDeferredContentApiPermissionRetry({
6093
7006
  strapi: strapi2,
@@ -6130,44 +7043,10 @@ var require_bootstrap = __commonJS({
6130
7043
  }
6131
7044
  async function ensureSessionLookupIndexes(strapi2, log) {
6132
7045
  try {
6133
- const knex = strapi2.db.connection;
6134
- const tableName = "magic_sessions";
6135
- const definitions = [
6136
- { column: "token_hash", name: "idx_magic_sessions_token_hash" },
6137
- { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
6138
- ];
6139
- if (!await knex.schema.hasTable(tableName)) return;
6140
- for (const definition of definitions) {
6141
- const dialect = strapi2.db.dialect.client;
6142
- let hasIndex = false;
6143
- if (dialect === "postgres") {
6144
- const result = await knex.raw(
6145
- "SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
6146
- [tableName, definition.name]
6147
- );
6148
- hasIndex = result.rows.length > 0;
6149
- } else if (dialect === "mysql" || dialect === "mysql2") {
6150
- const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
6151
- tableName,
6152
- definition.name
6153
- ]);
6154
- hasIndex = result[0].length > 0;
6155
- } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
6156
- const result = await knex.raw(
6157
- "SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
6158
- [definition.name]
6159
- );
6160
- hasIndex = result.length > 0;
6161
- }
6162
- if (hasIndex) {
6163
- log.debug(`[INDEX] ${definition.name} already exists`);
6164
- continue;
6165
- }
6166
- await knex.schema.alterTable(tableName, (table) => {
6167
- table.index([definition.column, "is_active"], definition.name);
6168
- });
6169
- log.info(`[INDEX] Created ${definition.name}`);
6170
- }
7046
+ await getCoordinator(strapi2).withLock(
7047
+ "schema:session-indexes",
7048
+ () => createSessionLookupIndexes(strapi2, log)
7049
+ );
6171
7050
  } catch (err) {
6172
7051
  log.debug(
6173
7052
  "[INDEX] Could not create session lookup indexes (will retry on next startup):",
@@ -6175,6 +7054,54 @@ var require_bootstrap = __commonJS({
6175
7054
  );
6176
7055
  }
6177
7056
  }
7057
+ async function createSessionLookupIndexes(strapi2, log) {
7058
+ const knex = strapi2.db.connection;
7059
+ const tableName = "magic_sessions";
7060
+ const definitions = [
7061
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7062
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
7063
+ ];
7064
+ if (!await knex.schema.hasTable(tableName)) return;
7065
+ const dialect = strapi2.db.dialect.client;
7066
+ for (const definition of definitions) {
7067
+ if (dialect === "postgres" || dialect === "sqlite" || dialect === "better-sqlite3") {
7068
+ const exists = dialect === "postgres" ? (await knex.raw("SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
7069
+ tableName,
7070
+ definition.name
7071
+ ])).rows.length > 0 : (await knex.raw("SELECT name FROM sqlite_master WHERE type='index' AND name = ?", [
7072
+ definition.name
7073
+ ])).length > 0;
7074
+ if (exists) {
7075
+ log.debug(`[INDEX] ${definition.name} already exists`);
7076
+ continue;
7077
+ }
7078
+ await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7079
+ definition.name,
7080
+ tableName,
7081
+ definition.column,
7082
+ "is_active"
7083
+ ]);
7084
+ log.info(`[INDEX] Created ${definition.name}`);
7085
+ continue;
7086
+ }
7087
+ let hasIndex = false;
7088
+ if (dialect === "mysql" || dialect === "mysql2") {
7089
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
7090
+ tableName,
7091
+ definition.name
7092
+ ]);
7093
+ hasIndex = result[0].length > 0;
7094
+ }
7095
+ if (hasIndex) {
7096
+ log.debug(`[INDEX] ${definition.name} already exists`);
7097
+ continue;
7098
+ }
7099
+ await knex.schema.alterTable(tableName, (table) => {
7100
+ table.index([definition.column, "is_active"], definition.name);
7101
+ });
7102
+ log.info(`[INDEX] Created ${definition.name}`);
7103
+ }
7104
+ }
6178
7105
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
6179
7106
  var MAX_CONSECUTIVE_ERRORS = 10;
6180
7107
  var ERROR_RESET_INTERVAL = 60 * 1e3;
@@ -6357,8 +7284,8 @@ var require_bootstrap = __commonJS({
6357
7284
  strapi2.log.info(
6358
7285
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days`
6359
7286
  );
6360
- await strapi2.documents(SESSION_UID).update({
6361
- documentId: thisSession.documentId,
7287
+ await strapi2.db.query(SESSION_UID).updateMany({
7288
+ where: { documentId: thisSession.documentId, isActive: true },
6362
7289
  data: {
6363
7290
  isActive: false,
6364
7291
  terminatedManually: false,
@@ -6376,8 +7303,8 @@ var require_bootstrap = __commonJS({
6376
7303
  strapi2.log.info(
6377
7304
  `[magic-sessionmanager] [JWT-IDLE] Session too idle to reactivate (${Math.round(idleFor / 1e3)}s > ${inactivityTimeout / 1e3}s)`
6378
7305
  );
6379
- await strapi2.documents(SESSION_UID).update({
6380
- documentId: thisSession.documentId,
7306
+ await strapi2.db.query(SESSION_UID).updateMany({
7307
+ where: { documentId: thisSession.documentId, isActive: true },
6381
7308
  data: {
6382
7309
  isActive: false,
6383
7310
  terminatedManually: false,
@@ -6392,10 +7319,22 @@ var require_bootstrap = __commonJS({
6392
7319
  resetErrorCounter();
6393
7320
  return decoded;
6394
7321
  }
6395
- await strapi2.documents(SESSION_UID).update({
6396
- documentId: thisSession.documentId,
7322
+ const reactivated = await strapi2.db.query(SESSION_UID).updateMany({
7323
+ where: {
7324
+ documentId: thisSession.documentId,
7325
+ isActive: false,
7326
+ terminationReason: { $null: true },
7327
+ $or: [{ terminatedManually: false }, { terminatedManually: { $null: true } }]
7328
+ },
6397
7329
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
6398
7330
  });
7331
+ if (Number(reactivated?.count) !== 1) {
7332
+ strapi2.log.info(
7333
+ "[magic-sessionmanager] [JWT-REJECTED] Session was terminated concurrently"
7334
+ );
7335
+ setSessionRejectionReason(tokenHashValue, "manual");
7336
+ return null;
7337
+ }
6399
7338
  strapi2.log.info("[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated");
6400
7339
  resetErrorCounter();
6401
7340
  return decoded;
@@ -6461,6 +7400,8 @@ var require_bootstrap = __commonJS({
6461
7400
  }
6462
7401
  module.exports.__private = {
6463
7402
  registerSessionAwareAuthStrategy,
7403
+ mountFailedLoginLockout,
7404
+ ensureSessionLookupIndexes,
6464
7405
  mountPreLoginGeoGuard,
6465
7406
  mountLoginInterceptor,
6466
7407
  mountRefreshTokenInterceptor,
@@ -6532,7 +7473,16 @@ var require_config = __commonJS({
6532
7473
  enableWebhooks: false,
6533
7474
  discordWebhookUrl: "",
6534
7475
  slackWebhookUrl: "",
6535
- trustedProxies: null
7476
+ trustedProxies: null,
7477
+ // Cross-process state for pm2 cluster / several replicas. `enabled:
7478
+ // false` keeps every counter, lease and cache per process (the pre-4.10
7479
+ // behaviour). `counterStore` may supply an object with async
7480
+ // hit/peek/block/clear methods (for example backed by Redis) for the
7481
+ // lockout and rate-limit counters; see README "Running several instances".
7482
+ coordination: {
7483
+ enabled: true,
7484
+ counterStore: null
7485
+ }
6536
7486
  },
6537
7487
  validator: (config) => {
6538
7488
  if (config.lastSeenRateLimit !== void 0 && typeof config.lastSeenRateLimit !== "number") {
@@ -6562,6 +7512,24 @@ var require_config = __commonJS({
6562
7512
  if (config.geoLookupFailureMode !== void 0 && !["auto", "allow", "block"].includes(config.geoLookupFailureMode)) {
6563
7513
  throw new Error("geoLookupFailureMode must be one of: auto, allow, block");
6564
7514
  }
7515
+ if (config.coordination !== void 0 && config.coordination !== null) {
7516
+ const coordination = config.coordination;
7517
+ if (typeof coordination !== "object" || Array.isArray(coordination)) {
7518
+ throw new Error("coordination must be an object");
7519
+ }
7520
+ if (coordination.enabled !== void 0 && typeof coordination.enabled !== "boolean") {
7521
+ throw new Error("coordination.enabled must be a boolean");
7522
+ }
7523
+ const store = coordination.counterStore;
7524
+ if (store !== void 0 && store !== null) {
7525
+ const required = ["hit", "peek", "block", "clear"];
7526
+ if (typeof store !== "object" || required.some((method) => typeof store[method] !== "function")) {
7527
+ throw new Error(
7528
+ "coordination.counterStore must implement async hit, peek, block and clear methods"
7529
+ );
7530
+ }
7531
+ }
7532
+ }
6565
7533
  }
6566
7534
  };
6567
7535
  }
@@ -6939,52 +7907,6 @@ var require_admin = __commonJS({
6939
7907
  description: "Get aggregate end-user counts only (admin)"
6940
7908
  }
6941
7909
  },
6942
- // ============================ LICENSE ============================
6943
- {
6944
- method: "GET",
6945
- path: "/license/status",
6946
- handler: "license.getStatus",
6947
- config: {
6948
- policies: adminPolicy(),
6949
- description: "Get license status (admin)"
6950
- }
6951
- },
6952
- {
6953
- method: "POST",
6954
- path: "/license/auto-create",
6955
- handler: "license.autoCreate",
6956
- config: {
6957
- policies: adminPolicy(),
6958
- description: "Auto-create license for current admin (admin)"
6959
- }
6960
- },
6961
- {
6962
- method: "POST",
6963
- path: "/license/create",
6964
- handler: "license.createAndActivate",
6965
- config: {
6966
- policies: adminPolicy(),
6967
- description: "Create and activate a new license (admin)"
6968
- }
6969
- },
6970
- {
6971
- method: "POST",
6972
- path: "/license/ping",
6973
- handler: "license.ping",
6974
- config: {
6975
- policies: adminPolicy(),
6976
- description: "Ping the license server (admin)"
6977
- }
6978
- },
6979
- {
6980
- method: "POST",
6981
- path: "/license/store-key",
6982
- handler: "license.storeKey",
6983
- config: {
6984
- policies: adminPolicy(),
6985
- description: "Store a license key (admin)"
6986
- }
6987
- },
6988
7910
  // ============================ GEOLOCATION ============================
6989
7911
  {
6990
7912
  method: "GET",
@@ -7415,6 +8337,7 @@ var require_session = __commonJS({
7415
8337
  var { parseNativeSessionKey } = require_native_session_view();
7416
8338
  var { runWithCallerRevocation } = require_block_revocation_scope();
7417
8339
  var { sendServerError } = require_http_errors();
8340
+ var { getCoordinator } = require_coordination();
7418
8341
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7419
8342
  var USER_UID = "plugin::users-permissions.user";
7420
8343
  var OWN_SESSIONS_LIMIT = 200;
@@ -8299,19 +9222,25 @@ var require_session = __commonJS({
8299
9222
  if (!userDocumentId) {
8300
9223
  return ctx.notFound("User not found");
8301
9224
  }
8302
- const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
8303
- if (!user) {
9225
+ const mode = hasRequestedState ? "explicit" : "toggle";
9226
+ const applyBlockedState = async () => {
9227
+ const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
9228
+ if (!user) return null;
9229
+ const nextBlocked = hasRequestedState ? requestedBlocked : !user.blocked;
9230
+ await runWithCallerRevocation(
9231
+ userDocumentId,
9232
+ () => strapi.documents(USER_UID).update({
9233
+ documentId: userDocumentId,
9234
+ data: { blocked: nextBlocked }
9235
+ })
9236
+ );
9237
+ return { blocked: nextBlocked };
9238
+ };
9239
+ const applied = mode === "toggle" ? await getCoordinator(strapi).withLock(`user-block:${userDocumentId}`, applyBlockedState) : await applyBlockedState();
9240
+ if (!applied) {
8304
9241
  return ctx.notFound("User not found");
8305
9242
  }
8306
- const mode = hasRequestedState ? "explicit" : "toggle";
8307
- const newBlockedStatus = hasRequestedState ? requestedBlocked : !user.blocked;
8308
- await runWithCallerRevocation(
8309
- userDocumentId,
8310
- () => strapi.documents(USER_UID).update({
8311
- documentId: userDocumentId,
8312
- data: { blocked: newBlockedStatus }
8313
- })
8314
- );
9243
+ const newBlockedStatus = applied.blocked;
8315
9244
  if (newBlockedStatus) {
8316
9245
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8317
9246
  await sessionService.terminateSession({ userId: userDocumentId, reason: "blocked" });
@@ -8331,182 +9260,6 @@ var require_session = __commonJS({
8331
9260
  }
8332
9261
  });
8333
9262
 
8334
- // server/src/controllers/license.js
8335
- var require_license = __commonJS({
8336
- "server/src/controllers/license.js"(exports, module) {
8337
- "use strict";
8338
- var { sendServerError } = require_http_errors();
8339
- var PROVIDER_UNREACHABLE_MESSAGE = "License server unreachable. The plugin keeps working without a key.";
8340
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
8341
- module.exports = ({ strapi: strapi2 }) => ({
8342
- async getStatus(ctx) {
8343
- try {
8344
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8345
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
8346
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
8347
- if (!licenseKey) {
8348
- return ctx.send({
8349
- success: true,
8350
- valid: true,
8351
- demo: false,
8352
- hasKey: false,
8353
- data: {
8354
- features: {
8355
- premium: true,
8356
- advanced: true,
8357
- enterprise: true,
8358
- custom: true
8359
- }
8360
- },
8361
- message: "Plugin is active. License key activation is optional."
8362
- });
8363
- }
8364
- const license = await licenseGuard.getLicenseByKey(licenseKey);
8365
- return ctx.send({
8366
- success: true,
8367
- valid: true,
8368
- demo: false,
8369
- hasKey: true,
8370
- data: {
8371
- licenseKey,
8372
- email: license?.email || null,
8373
- firstName: license?.firstName || null,
8374
- lastName: license?.lastName || null,
8375
- isActive: license?.isActive ?? true,
8376
- isExpired: license?.isExpired ?? false,
8377
- isOnline: license?.isOnline ?? false,
8378
- expiresAt: license?.expiresAt || null,
8379
- lastPingAt: license?.lastPingAt || null,
8380
- deviceName: license?.deviceName || null,
8381
- deviceId: license?.deviceId || null,
8382
- ipAddress: license?.ipAddress || null,
8383
- features: {
8384
- premium: true,
8385
- advanced: true,
8386
- enterprise: true,
8387
- custom: true
8388
- },
8389
- maxDevices: license?.maxDevices || 1,
8390
- currentDevices: license?.currentDevices || 0
8391
- }
8392
- });
8393
- } catch (error) {
8394
- strapi2.log.error(
8395
- "[magic-sessionmanager] Error getting license status:",
8396
- error?.name || "Error"
8397
- );
8398
- return sendServerError(ctx, 500, "Error getting license status");
8399
- }
8400
- },
8401
- async autoCreate(ctx) {
8402
- try {
8403
- const adminUser = ctx.state.user;
8404
- if (!adminUser) {
8405
- return ctx.unauthorized("No admin user logged in");
8406
- }
8407
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8408
- const license = await licenseGuard.createLicense({
8409
- email: adminUser.email,
8410
- firstName: adminUser.firstname || "Admin",
8411
- lastName: adminUser.lastname || "User"
8412
- });
8413
- if (!license) {
8414
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
8415
- }
8416
- await licenseGuard.storeLicenseKey(license.licenseKey);
8417
- return ctx.send({
8418
- success: true,
8419
- message: "License automatically created and stored",
8420
- data: license
8421
- });
8422
- } catch (error) {
8423
- strapi2.log.error(
8424
- "[magic-sessionmanager] Error auto-creating license:",
8425
- error?.name || "Error"
8426
- );
8427
- return sendServerError(ctx, 500, "Error creating license");
8428
- }
8429
- },
8430
- async createAndActivate(ctx) {
8431
- try {
8432
- const { email, firstName, lastName } = ctx.request.body || {};
8433
- if (![email, firstName, lastName].every((value) => typeof value === "string" && value.trim())) {
8434
- return ctx.badRequest("Email, firstName, and lastName are required");
8435
- }
8436
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8437
- const license = await licenseGuard.createLicense({ email, firstName, lastName });
8438
- if (!license) {
8439
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
8440
- }
8441
- await licenseGuard.storeLicenseKey(license.licenseKey);
8442
- return ctx.send({
8443
- success: true,
8444
- message: "License created and stored successfully",
8445
- data: license
8446
- });
8447
- } catch (error) {
8448
- strapi2.log.error("[magic-sessionmanager] Error creating license:", error?.name || "Error");
8449
- return sendServerError(ctx, 500, "Error creating license");
8450
- }
8451
- },
8452
- async ping(ctx) {
8453
- try {
8454
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
8455
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
8456
- if (!licenseKey) {
8457
- return ctx.badRequest("No license key found");
8458
- }
8459
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8460
- const verification = await licenseGuard.verifyLicense(licenseKey);
8461
- return ctx.send({
8462
- success: true,
8463
- message: verification.valid ? "License refreshed successfully" : "License key could not be verified, but the plugin keeps working.",
8464
- data: verification.data
8465
- });
8466
- } catch (error) {
8467
- strapi2.log.error("[magic-sessionmanager] Error refreshing license:", error?.name || "Error");
8468
- return sendServerError(ctx, 500, "Error refreshing license");
8469
- }
8470
- },
8471
- async storeKey(ctx) {
8472
- try {
8473
- const { licenseKey, email } = ctx.request.body || {};
8474
- if (typeof licenseKey !== "string" || !licenseKey.trim()) {
8475
- return ctx.badRequest("License key is required");
8476
- }
8477
- if (email !== void 0 && email !== null && email !== "") {
8478
- if (typeof email !== "string" || !EMAIL_PATTERN.test(email.trim())) {
8479
- return ctx.badRequest("Email must be a valid email address");
8480
- }
8481
- }
8482
- const trimmedKey = licenseKey.trim();
8483
- const trimmedEmail = typeof email === "string" && email.trim() ? email.trim().toLowerCase() : null;
8484
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8485
- const verification = await licenseGuard.verifyLicense(trimmedKey);
8486
- if (!verification.valid && !verification.networkError) {
8487
- strapi2.log.warn("[magic-sessionmanager] Rejected an invalid license key");
8488
- return ctx.badRequest("Invalid or expired license key");
8489
- }
8490
- const license = verification.valid ? await licenseGuard.getLicenseByKey(trimmedKey) : null;
8491
- if (license?.email && trimmedEmail && license.email.toLowerCase() !== trimmedEmail) {
8492
- strapi2.log.warn("[magic-sessionmanager] Rejected a license holder email mismatch");
8493
- return ctx.badRequest("Email address does not match this license key");
8494
- }
8495
- await licenseGuard.storeLicenseKey(trimmedKey);
8496
- return ctx.send({
8497
- success: true,
8498
- message: verification.networkError ? "License key stored. The license server was unreachable, but the plugin keeps working." : "License key stored successfully",
8499
- data: verification.data || { licenseKey: trimmedKey, email: trimmedEmail }
8500
- });
8501
- } catch (error) {
8502
- strapi2.log.error("[magic-sessionmanager] Error storing license key:", error?.name || "Error");
8503
- return sendServerError(ctx, 500, "Error validating license key");
8504
- }
8505
- }
8506
- });
8507
- }
8508
- });
8509
-
8510
9263
  // scripts/geoip-updater.cjs
8511
9264
  var require_geoip_updater = __commonJS({
8512
9265
  "scripts/geoip-updater.cjs"(exports, module) {
@@ -8824,10 +9577,13 @@ var require_settings = __commonJS({
8824
9577
  "server/src/controllers/settings.js"(exports, module) {
8825
9578
  "use strict";
8826
9579
  var {
8827
- invalidateSettingsCache,
9580
+ getSettingsRevision,
8828
9581
  normalizeGeoIpProvider,
8829
- normalizeGeoLookupFailureMode
9582
+ normalizeGeoLookupFailureMode,
9583
+ notifySettingsChanged
8830
9584
  } = require_settings_loader();
9585
+ var { withPluginStoreKey } = require_plugin_store();
9586
+ var { LockTimeoutError } = require_coordination();
8831
9587
  var { resolveDatabaseTarget } = require_geoip_updater();
8832
9588
  var { sendServerError, sendValidationError } = require_http_errors();
8833
9589
  var path = __require("node:path");
@@ -9215,6 +9971,26 @@ var require_settings = __commonJS({
9215
9971
  }
9216
9972
  return { settings, errors };
9217
9973
  }
9974
+ async function readRevision() {
9975
+ try {
9976
+ return await getSettingsRevision(strapi);
9977
+ } catch {
9978
+ return null;
9979
+ }
9980
+ }
9981
+ function sendSettingsConflict(ctx, currentRevision) {
9982
+ ctx.status = 409;
9983
+ ctx.body = {
9984
+ data: null,
9985
+ error: {
9986
+ status: 409,
9987
+ name: "ConflictError",
9988
+ message: "Settings were changed by another administrator. Reload and try again.",
9989
+ details: { revision: currentRevision }
9990
+ }
9991
+ };
9992
+ return ctx.body;
9993
+ }
9218
9994
  module.exports = {
9219
9995
  /**
9220
9996
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -9231,8 +10007,10 @@ var require_settings = __commonJS({
9231
10007
  });
9232
10008
  const storedSettings = await pluginStore.get({ key: "settings" });
9233
10009
  const settings = mergeSettingsWithDefaults(storedSettings);
10010
+ const revision = await readRevision();
9234
10011
  ctx.send({
9235
10012
  settings,
10013
+ ...revision === null ? {} : { revision },
9236
10014
  success: true
9237
10015
  });
9238
10016
  } catch (error) {
@@ -9256,42 +10034,60 @@ var require_settings = __commonJS({
9256
10034
  * @returns {Promise<void>}
9257
10035
  */
9258
10036
  async updateSettings(ctx) {
9259
- let pluginStore;
9260
- let current;
9261
10037
  try {
9262
10038
  const { body } = ctx.request;
9263
10039
  if (!body || typeof body !== "object" || Array.isArray(body)) {
9264
10040
  return ctx.badRequest("Settings data must be an object");
9265
10041
  }
9266
- pluginStore = strapi.store({
9267
- type: "plugin",
9268
- name: "magic-sessionmanager"
9269
- });
9270
- const stored = await pluginStore.get({ key: "settings" });
9271
- const storedObject = stored && typeof stored === "object" ? stored : {};
9272
- current = {
9273
- ...mergeSettingsWithDefaults(storedObject),
9274
- geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
9275
- };
9276
- const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
9277
- if (errors.length > 0) {
9278
- return sendValidationError(ctx, "Invalid settings", errors);
10042
+ const hasBaseRevision = Object.prototype.hasOwnProperty.call(body, "revision");
10043
+ if (hasBaseRevision && !(Number.isInteger(body.revision) && body.revision >= 0)) {
10044
+ return sendValidationError(ctx, "Invalid settings", [
10045
+ { path: ["revision"], message: "revision must be a non-negative integer" }
10046
+ ]);
9279
10047
  }
9280
- await pluginStore.set({
9281
- key: "settings",
9282
- value: sanitizedSettings
10048
+ const outcome = await withPluginStoreKey(strapi, "settings", async (pluginStore) => {
10049
+ if (hasBaseRevision) {
10050
+ const currentRevision = await readRevision();
10051
+ if (currentRevision !== null && currentRevision !== body.revision) {
10052
+ return { conflict: true, currentRevision };
10053
+ }
10054
+ }
10055
+ const stored = await pluginStore.get({ key: "settings" });
10056
+ const storedObject = stored && typeof stored === "object" ? stored : {};
10057
+ const current = {
10058
+ ...mergeSettingsWithDefaults(storedObject),
10059
+ geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
10060
+ };
10061
+ const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
10062
+ if (errors.length > 0) return { errors };
10063
+ await pluginStore.set({
10064
+ key: "settings",
10065
+ value: sanitizedSettings
10066
+ });
10067
+ const revision = await notifySettingsChanged(strapi);
10068
+ return { settings: sanitizedSettings, revision };
9283
10069
  });
9284
- invalidateSettingsCache();
10070
+ if (outcome.conflict) {
10071
+ return sendSettingsConflict(ctx, outcome.currentRevision);
10072
+ }
10073
+ if (outcome.errors) {
10074
+ return sendValidationError(ctx, "Invalid settings", outcome.errors);
10075
+ }
9285
10076
  strapi.log.info("[magic-sessionmanager/settings] Settings updated successfully");
9286
10077
  ctx.send({
9287
10078
  settings: {
9288
- ...sanitizedSettings,
9289
- geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
10079
+ ...outcome.settings,
10080
+ geoIpDatabasePath: getSafeGeoIpFilename(outcome.settings.geoIpDatabasePath)
9290
10081
  },
10082
+ ...outcome.revision === null || outcome.revision === void 0 ? {} : { revision: outcome.revision },
9291
10083
  success: true,
9292
10084
  message: "Settings saved successfully!"
9293
10085
  });
9294
10086
  } catch (error) {
10087
+ if (error instanceof LockTimeoutError) {
10088
+ strapi.log.warn("[magic-sessionmanager/settings] Settings are being saved elsewhere");
10089
+ return sendServerError(ctx, 503, "Settings are being saved by another request");
10090
+ }
9295
10091
  strapi.log.error(
9296
10092
  "[magic-sessionmanager/settings] Error updating settings:",
9297
10093
  error?.name || "Error"
@@ -9326,6 +10122,8 @@ var require_geoip = __commonJS({
9326
10122
  normalizeGeoIpDatabasePath
9327
10123
  } = require_settings_loader();
9328
10124
  var { sendServerError } = require_http_errors();
10125
+ var { setPluginStoreValue } = require_plugin_store();
10126
+ var { getHostFingerprint } = require_coordination();
9329
10127
  var CREDENTIALS_KEY = "geoipCredentials";
9330
10128
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
9331
10129
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -9348,11 +10146,7 @@ var require_geoip = __commonJS({
9348
10146
  };
9349
10147
  }
9350
10148
  async function setStoredCredentials(strapi2, credentials) {
9351
- const store = getGeoIpStore(strapi2);
9352
- await store.set({
9353
- key: CREDENTIALS_KEY,
9354
- value: credentials
9355
- });
10149
+ await setPluginStoreValue(strapi2, CREDENTIALS_KEY, credentials);
9356
10150
  }
9357
10151
  function getCredentialSource(storedCredentials) {
9358
10152
  if (process.env.MAXMIND_ACCOUNT_ID && process.env.MAXMIND_LICENSE_KEY) {
@@ -9419,7 +10213,12 @@ var require_geoip = __commonJS({
9419
10213
  metadata,
9420
10214
  hasCredentials: credentialSource !== "missing",
9421
10215
  credentialSource,
9422
- accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || ""
10216
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
10217
+ // The MMDB file lives on the local disk of the instance that
10218
+ // answered. In multi-instance deployments each instance reports
10219
+ // its own file; `instance` is a non-reversible host fingerprint.
10220
+ scope: "instance",
10221
+ instance: getHostFingerprint()
9423
10222
  }
9424
10223
  });
9425
10224
  } catch (error) {
@@ -9518,12 +10317,10 @@ var require_controllers = __commonJS({
9518
10317
  "server/src/controllers/index.js"(exports, module) {
9519
10318
  "use strict";
9520
10319
  var session = require_session();
9521
- var license = require_license();
9522
10320
  var settings = require_settings();
9523
10321
  var geoip = require_geoip();
9524
10322
  module.exports = {
9525
10323
  session,
9526
- license,
9527
10324
  settings,
9528
10325
  geoip
9529
10326
  };
@@ -9650,6 +10447,7 @@ var require_session2 = __commonJS({
9650
10447
  if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9651
10448
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9652
10449
  if (!revoked) {
10450
+ if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9653
10451
  throw new Error(
9654
10452
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9655
10453
  );
@@ -9680,7 +10478,10 @@ var require_session2 = __commonJS({
9680
10478
  }
9681
10479
  if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
9682
10480
  const revoked = await nativeManager.revokeSessionById(userId, parsed.nativeSessionId);
9683
- if (!revoked) throw new Error("Native session revocation was not confirmed.");
10481
+ if (!revoked) {
10482
+ if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
10483
+ throw new Error("Native session revocation was not confirmed.");
10484
+ }
9684
10485
  return true;
9685
10486
  }
9686
10487
  async function listNativeSessionsForUser(nativeManager, user, linkedIds = /* @__PURE__ */ new Set()) {
@@ -9817,6 +10618,7 @@ var require_session2 = __commonJS({
9817
10618
  if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9818
10619
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9819
10620
  if (!revoked) {
10621
+ if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9820
10622
  throw new Error(
9821
10623
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9822
10624
  );
@@ -10421,8 +11223,13 @@ var require_session2 = __commonJS({
10421
11223
  if (ts < cutoff) this._lastTouchCache.delete(k);
10422
11224
  }
10423
11225
  }
10424
- await strapi2.documents(SESSION_UID).update({
10425
- documentId: sessionDocId,
11226
+ const staleBefore = new Date(now.getTime() - rateLimit);
11227
+ await strapi2.db.query(SESSION_UID).updateMany({
11228
+ where: {
11229
+ documentId: sessionDocId,
11230
+ isActive: true,
11231
+ $or: [{ lastActive: { $lt: staleBefore } }, { lastActive: { $null: true } }]
11232
+ },
10426
11233
  data: { lastActive: now }
10427
11234
  });
10428
11235
  log.debug("[TOUCH] End-user session lastActive updated");
@@ -10512,9 +11319,24 @@ var require_session2 = __commonJS({
10512
11319
  let deactivatedCount = 0;
10513
11320
  for (const session of sessionsToDeactivate) {
10514
11321
  try {
10515
- if (nativeManager) await revokeNativeSessionForSidecar(nativeManager, session);
10516
- await strapi2.documents(SESSION_UID).update({
11322
+ const idleWhere = {
10517
11323
  documentId: session.documentId,
11324
+ isActive: true,
11325
+ $or: [
11326
+ { lastActive: { $lt: cutoffTime } },
11327
+ { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
11328
+ ]
11329
+ };
11330
+ if (nativeManager) {
11331
+ const stillIdle = await strapi2.documents(SESSION_UID).findFirst({
11332
+ filters: idleWhere,
11333
+ fields: ["documentId"]
11334
+ });
11335
+ if (!stillIdle) continue;
11336
+ await revokeNativeSessionForSidecar(nativeManager, session);
11337
+ }
11338
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
11339
+ where: idleWhere,
10518
11340
  data: {
10519
11341
  isActive: false,
10520
11342
  terminatedManually: false,
@@ -10522,7 +11344,7 @@ var require_session2 = __commonJS({
10522
11344
  logoutTime: now
10523
11345
  }
10524
11346
  });
10525
- deactivatedCount++;
11347
+ if (Number(result?.count) === 1) deactivatedCount++;
10526
11348
  } catch (err) {
10527
11349
  log.debug("[CLEANUP] Failed to deactivate an end-user session:", err?.name || "Error");
10528
11350
  }
@@ -10709,364 +11531,6 @@ var require_session2 = __commonJS({
10709
11531
  }
10710
11532
  });
10711
11533
 
10712
- // package.json
10713
- var require_package = __commonJS({
10714
- "package.json"(exports, module) {
10715
- module.exports = {
10716
- version: "4.9.1",
10717
- keywords: [
10718
- "strapi",
10719
- "plugin",
10720
- "strapi-plugin",
10721
- "strapi-v5",
10722
- "sessions",
10723
- "user-tracking",
10724
- "login-logout",
10725
- "activity-monitoring"
10726
- ],
10727
- type: "commonjs",
10728
- bin: {
10729
- "strapi-magic-sessionmanager-geoip": "./scripts/update-geoip-db.mjs"
10730
- },
10731
- exports: {
10732
- "./package.json": "./package.json",
10733
- "./strapi-admin": {
10734
- source: "./admin/src/index.js",
10735
- import: "./dist/admin/index.mjs",
10736
- require: "./dist/admin/index.js",
10737
- default: "./dist/admin/index.js"
10738
- },
10739
- "./strapi-server": {
10740
- source: "./server/src/index.js",
10741
- import: "./dist/server/index.mjs",
10742
- require: "./dist/server/index.js",
10743
- default: "./dist/server/index.js"
10744
- }
10745
- },
10746
- files: [
10747
- "dist",
10748
- "strapi-admin.js",
10749
- "strapi-server.js",
10750
- "scripts/geoip-updater.cjs",
10751
- "scripts/update-geoip-db.mjs",
10752
- "README.md",
10753
- "LICENSE",
10754
- "CHANGELOG.md",
10755
- "pics"
10756
- ],
10757
- engines: {
10758
- node: "^22.22.2 || >=24.15.0",
10759
- npm: ">=6.0.0"
10760
- },
10761
- scripts: {
10762
- clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`,
10763
- test: "node --test tests/*.test.js tests/*.test.mjs",
10764
- "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
10765
- "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
10766
- lint: "eslint .",
10767
- "lint:fix": "eslint . --fix",
10768
- format: "prettier --write .",
10769
- "format:check": "prettier --check .",
10770
- build: "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
10771
- watch: "strapi-plugin watch",
10772
- "watch:link": "strapi-plugin watch:link",
10773
- "geoip:update": "node scripts/update-geoip-db.mjs",
10774
- verify: "strapi-plugin verify",
10775
- "verify:runtime": "node scripts/verify-server-bundle.mjs",
10776
- prepublishOnly: "npm test && npm run build && npm run verify && npm run verify:runtime"
10777
- },
10778
- dependencies: {
10779
- "@maxmind/geoip2-node": "^7.1.0",
10780
- "sanitize-html": "^2.18.0"
10781
- },
10782
- devDependencies: {
10783
- "@eslint/js": "^10.0.1",
10784
- "@semantic-release/changelog": "^7.0.0",
10785
- "@semantic-release/commit-analyzer": "^13.0.1",
10786
- "@semantic-release/git": "^11.0.1",
10787
- "@semantic-release/github": "^12.0.10",
10788
- "@semantic-release/npm": "^13.2.0",
10789
- "@semantic-release/release-notes-generator": "^14.1.1",
10790
- "@strapi/design-system": "^2.2.4",
10791
- "@strapi/icons": "^2.2.4",
10792
- "@strapi/sdk-plugin": "^6.1.1",
10793
- "@strapi/strapi": "5.61.0",
10794
- esbuild: "^0.28.2",
10795
- eslint: "^10.14.0",
10796
- "eslint-config-prettier": "^10.1.8",
10797
- "eslint-plugin-react-hooks": "^7.1.1",
10798
- globals: "^17.14.0",
10799
- prettier: "^3.9.10",
10800
- react: "^18.3.1",
10801
- "react-dom": "^18.3.1",
10802
- "react-intl": "^6.8.9",
10803
- "react-router-dom": "^6.30.6",
10804
- "semantic-release": "^25.0.9",
10805
- "styled-components": "^6.6.0"
10806
- },
10807
- peerDependencies: {
10808
- "@strapi/design-system": "^2.0.0",
10809
- "@strapi/icons": "^2.0.0",
10810
- "@strapi/strapi": "^5.0.0",
10811
- "@strapi/utils": "^5.0.0",
10812
- react: "^18.3.1",
10813
- "react-dom": "^18.3.1",
10814
- "react-intl": "^6.0.0",
10815
- "react-router-dom": "^6.0.0",
10816
- "styled-components": "^6.0.0"
10817
- },
10818
- publishConfig: {
10819
- access: "public"
10820
- },
10821
- strapi: {
10822
- kind: "plugin",
10823
- name: "magic-sessionmanager",
10824
- displayName: "Magic Sessionmanager",
10825
- description: "Advanced session management for Strapi v5 - Track user login/logout, session history, and online status"
10826
- },
10827
- name: "strapi-plugin-magic-sessionmanager",
10828
- description: "Advanced Session Management for Strapi v5 - Track user sessions with IP geolocation, security scoring, and real-time monitoring",
10829
- license: "MIT",
10830
- author: "Schero D.",
10831
- repository: {
10832
- type: "git",
10833
- url: "https://github.com/Schero94/Magic-Sessionmanager.git"
10834
- },
10835
- bugs: {
10836
- url: "https://github.com/Schero94/Magic-Sessionmanager/issues"
10837
- },
10838
- homepage: "https://github.com/Schero94/Magic-Sessionmanager#readme",
10839
- private: false
10840
- };
10841
- }
10842
- });
10843
-
10844
- // server/src/services/license-guard.js
10845
- var require_license_guard = __commonJS({
10846
- "server/src/services/license-guard.js"(exports, module) {
10847
- "use strict";
10848
- var crypto = __require("crypto");
10849
- var os = __require("os");
10850
- var pluginPkg = require_package();
10851
- var { createLogger } = require_logger();
10852
- var DEFAULT_LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
10853
- var envTimeout = Number(process.env.MAGIC_LICENSE_TIMEOUT_MS);
10854
- var DEFAULT_FETCH_TIMEOUT_MS = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 12e3;
10855
- var FETCH_RETRIES = 1;
10856
- var FETCH_RETRY_BACKOFF_MS = 750;
10857
- async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
10858
- let lastError;
10859
- for (let attempt = 0; attempt <= FETCH_RETRIES; attempt += 1) {
10860
- const controller = new AbortController();
10861
- const timer = setTimeout(() => controller.abort(), timeoutMs);
10862
- try {
10863
- return await fetch(url, { ...options, signal: controller.signal });
10864
- } catch (err) {
10865
- lastError = err;
10866
- if (attempt < FETCH_RETRIES) {
10867
- await new Promise((r) => setTimeout(r, FETCH_RETRY_BACKOFF_MS));
10868
- continue;
10869
- }
10870
- throw err;
10871
- } finally {
10872
- clearTimeout(timer);
10873
- }
10874
- }
10875
- throw lastError;
10876
- }
10877
- module.exports = ({ strapi: strapi2 }) => {
10878
- const log = createLogger(strapi2);
10879
- return {
10880
- getLicenseServerUrl() {
10881
- return process.env.MAGIC_LICENSE_SERVER_URL || DEFAULT_LICENSE_SERVER_URL;
10882
- },
10883
- async generateDeviceId() {
10884
- try {
10885
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
10886
- const stored = await pluginStore.get({ key: "deviceId" });
10887
- if (stored && typeof stored === "string" && stored.length >= 16) {
10888
- return stored;
10889
- }
10890
- let identifier;
10891
- try {
10892
- const networkInterfaces = os.networkInterfaces();
10893
- const macAddresses = [];
10894
- Object.values(networkInterfaces).forEach((interfaces) => {
10895
- interfaces?.forEach((iface) => {
10896
- if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
10897
- macAddresses.push(iface.mac);
10898
- }
10899
- });
10900
- });
10901
- identifier = `${macAddresses.join("-")}-${os.hostname()}`;
10902
- } catch {
10903
- identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
10904
- }
10905
- const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
10906
- await pluginStore.set({ key: "deviceId", value: deviceId });
10907
- return deviceId;
10908
- } catch {
10909
- return crypto.randomBytes(16).toString("hex");
10910
- }
10911
- },
10912
- getDeviceName() {
10913
- try {
10914
- return os.hostname() || "Unknown Device";
10915
- } catch {
10916
- return "Unknown Device";
10917
- }
10918
- },
10919
- getIpAddress() {
10920
- try {
10921
- const networkInterfaces = os.networkInterfaces();
10922
- for (const name of Object.keys(networkInterfaces)) {
10923
- const interfaces = networkInterfaces[name];
10924
- if (!interfaces) continue;
10925
- for (const iface of interfaces) {
10926
- if (iface.family === "IPv4" && !iface.internal) {
10927
- return iface.address;
10928
- }
10929
- }
10930
- }
10931
- return "127.0.0.1";
10932
- } catch {
10933
- return "127.0.0.1";
10934
- }
10935
- },
10936
- getUserAgent() {
10937
- const pluginVersion = pluginPkg.version || "1.0.0";
10938
- const strapiVersion = strapi2.config.get("info.strapi") || "5.0.0";
10939
- return `MagicSessionManager/${pluginVersion} Strapi/${strapiVersion} Node/${process.version} ${os.platform()}/${os.release()}`;
10940
- },
10941
- async createLicense({ email, firstName, lastName }) {
10942
- try {
10943
- const response = await fetchWithTimeout(
10944
- `${this.getLicenseServerUrl()}/api/licenses/create`,
10945
- {
10946
- method: "POST",
10947
- headers: { "Content-Type": "application/json" },
10948
- body: JSON.stringify({
10949
- email,
10950
- firstName,
10951
- lastName,
10952
- deviceName: this.getDeviceName(),
10953
- deviceId: await this.generateDeviceId(),
10954
- ipAddress: this.getIpAddress(),
10955
- userAgent: this.getUserAgent(),
10956
- pluginName: "magic-sessionmanager",
10957
- productName: "Magic Session Manager"
10958
- })
10959
- }
10960
- );
10961
- const data = await response.json();
10962
- if (data.success) {
10963
- log.info("[SUCCESS] License created");
10964
- return data.data;
10965
- }
10966
- log.warn("[WARNING] License creation rejected by server");
10967
- return null;
10968
- } catch (error) {
10969
- log.warn("[WARNING] Error creating license:", error?.name || "Error");
10970
- return null;
10971
- }
10972
- },
10973
- async verifyLicense(licenseKey) {
10974
- try {
10975
- const response = await fetchWithTimeout(
10976
- `${this.getLicenseServerUrl()}/api/licenses/verify`,
10977
- {
10978
- method: "POST",
10979
- headers: { "Content-Type": "application/json" },
10980
- body: JSON.stringify({
10981
- licenseKey,
10982
- pluginName: "magic-sessionmanager",
10983
- productName: "Magic Session Manager"
10984
- })
10985
- }
10986
- );
10987
- const data = await response.json();
10988
- if (data.success && data.data) {
10989
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
10990
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
10991
- return { valid: true, data: data.data };
10992
- }
10993
- return { valid: false, data: null };
10994
- } catch (error) {
10995
- log.warn(
10996
- `[WARNING] License server unreachable during optional activation (${error?.name || "Error"}). This does not block the plugin.`
10997
- );
10998
- return { valid: false, data: null, networkError: true };
10999
- }
11000
- },
11001
- async getLicenseByKey(licenseKey) {
11002
- try {
11003
- const encodedKey = encodeURIComponent(licenseKey);
11004
- const response = await fetchWithTimeout(
11005
- `${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`,
11006
- {
11007
- method: "GET",
11008
- headers: { "Content-Type": "application/json" }
11009
- }
11010
- );
11011
- const data = await response.json();
11012
- if (data.success && data.data) return data.data;
11013
- return null;
11014
- } catch (error) {
11015
- log.warn("[WARNING] Could not fetch license by key:", error?.name || "Error");
11016
- return null;
11017
- }
11018
- },
11019
- async pingLicense() {
11020
- return null;
11021
- },
11022
- async storeLicenseKey(licenseKey) {
11023
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
11024
- await pluginStore.set({ key: "licenseKey", value: licenseKey });
11025
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
11026
- log.info("[SUCCESS] License key stored");
11027
- return true;
11028
- },
11029
- startPinging() {
11030
- return null;
11031
- },
11032
- async initialize() {
11033
- return { valid: true, demo: false, data: null };
11034
- },
11035
- cleanup() {
11036
- },
11037
- async hasFeature() {
11038
- return true;
11039
- },
11040
- async getMaxSessions() {
11041
- return -1;
11042
- },
11043
- async getLicenseTierInfo() {
11044
- try {
11045
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
11046
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
11047
- const hasKey = !!licenseKey;
11048
- return {
11049
- tier: hasKey ? "pro" : "free",
11050
- hasKey,
11051
- features: {
11052
- premium: true,
11053
- advanced: true,
11054
- enterprise: true
11055
- }
11056
- };
11057
- } catch {
11058
- return {
11059
- tier: "free",
11060
- hasKey: false,
11061
- features: { premium: true, advanced: true, enterprise: true }
11062
- };
11063
- }
11064
- }
11065
- };
11066
- };
11067
- }
11068
- });
11069
-
11070
11534
  // server/src/services/geolocation.js
11071
11535
  var require_geolocation = __commonJS({
11072
11536
  "server/src/services/geolocation.js"(exports, module) {
@@ -11075,6 +11539,7 @@ var require_geolocation = __commonJS({
11075
11539
  var net = __require("node:net");
11076
11540
  var path = __require("node:path");
11077
11541
  var { getPluginSettings } = require_settings_loader();
11542
+ var { getCoordinator, hashedKey } = require_coordination();
11078
11543
  var { resolveDatabaseTarget } = require_geoip_updater();
11079
11544
  var GEO_API_TIMEOUT_MS = 4e3;
11080
11545
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -11083,6 +11548,7 @@ var require_geolocation = __commonJS({
11083
11548
  var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
11084
11549
  var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
11085
11550
  var IPAPI_MAX_QUEUE_SIZE = 50;
11551
+ var SHARED_BACKOFF_KEY = "geo:ipapi:backoff";
11086
11552
  var DEFAULT_CITY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
11087
11553
  var DEFAULT_COUNTRY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-Country.mmdb");
11088
11554
  var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
@@ -11159,6 +11625,50 @@ var require_geolocation = __commonJS({
11159
11625
  expiresAt: Date.now() + ttlMs
11160
11626
  });
11161
11627
  }
11628
+ async function getSharedIpapiResult(strapiInstance, lookupIp) {
11629
+ try {
11630
+ const data = await getCoordinator(strapiInstance).cacheGet(hashedKey("geo:ipapi", lookupIp));
11631
+ return data && typeof data === "object" ? { ...data, ip: lookupIp } : null;
11632
+ } catch {
11633
+ return null;
11634
+ }
11635
+ }
11636
+ async function shareIpapiResult(strapiInstance, lookupIp, data, ttlMs) {
11637
+ if (!lookupIp || !data || ttlMs <= 0) return;
11638
+ try {
11639
+ const { ip: _ip, ...withoutIp } = data;
11640
+ await getCoordinator(strapiInstance).cacheSet(
11641
+ hashedKey("geo:ipapi", lookupIp),
11642
+ withoutIp,
11643
+ ttlMs
11644
+ );
11645
+ } catch {
11646
+ }
11647
+ }
11648
+ async function cacheIpapiResultEverywhere(strapiInstance, lookupIp, data, ttlMs) {
11649
+ cacheIpapiResult(lookupIp, data, ttlMs);
11650
+ await shareIpapiResult(strapiInstance, lookupIp, data, ttlMs);
11651
+ }
11652
+ async function syncSharedIpapiBackoff(strapiInstance) {
11653
+ try {
11654
+ const until = Number(await getCoordinator(strapiInstance).cacheGet(SHARED_BACKOFF_KEY));
11655
+ if (Number.isFinite(until) && until > ipapiRateLimitedUntil) ipapiRateLimitedUntil = until;
11656
+ } catch {
11657
+ }
11658
+ return getIpapiRateLimitRemainingMs();
11659
+ }
11660
+ async function shareIpapiBackoff(strapiInstance) {
11661
+ const remaining = getIpapiRateLimitRemainingMs();
11662
+ if (remaining <= 0) return;
11663
+ try {
11664
+ await getCoordinator(strapiInstance).cacheSet(
11665
+ SHARED_BACKOFF_KEY,
11666
+ ipapiRateLimitedUntil,
11667
+ remaining
11668
+ );
11669
+ } catch {
11670
+ }
11671
+ }
11162
11672
  function getRetryAfterMs(response) {
11163
11673
  const retryAfter = response?.headers?.get?.("retry-after");
11164
11674
  if (!retryAfter) return null;
@@ -11465,7 +11975,12 @@ var require_geolocation = __commonJS({
11465
11975
  }
11466
11976
  const cached = getCachedIpapiResult(lookupIp);
11467
11977
  if (cached) return cached;
11468
- const rateLimitRemainingMs = getIpapiRateLimitRemainingMs();
11978
+ const shared = await getSharedIpapiResult(strapi2, lookupIp);
11979
+ if (shared) {
11980
+ cacheIpapiResult(lookupIp, shared, IPAPI_FAILURE_CACHE_TTL_MS);
11981
+ return cloneGeoData(shared);
11982
+ }
11983
+ const rateLimitRemainingMs = await syncSharedIpapiBackoff(strapi2);
11469
11984
  if (rateLimitRemainingMs > 0) {
11470
11985
  logIpapiRateLimit(
11471
11986
  strapi2,
@@ -11490,7 +12005,7 @@ var require_geolocation = __commonJS({
11490
12005
  "ipapi",
11491
12006
  "Remote GeoIP provider concurrency limit reached"
11492
12007
  );
11493
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12008
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11494
12009
  return fallback;
11495
12010
  }
11496
12011
  const queuedRateLimitRemainingMs = getIpapiRateLimitRemainingMs();
@@ -11519,6 +12034,7 @@ var require_geolocation = __commonJS({
11519
12034
  const reason = response.status === 429 ? "rate_limited" : "error";
11520
12035
  if (response.status === 429) {
11521
12036
  const backoffMs = markIpapiRateLimited(response);
12037
+ await shareIpapiBackoff(strapi2);
11522
12038
  logIpapiRateLimit(
11523
12039
  strapi2,
11524
12040
  `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11534,7 +12050,7 @@ var require_geolocation = __commonJS({
11534
12050
  "ipapi",
11535
12051
  `HTTP ${response.status}`
11536
12052
  );
11537
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12053
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11538
12054
  return fallback;
11539
12055
  }
11540
12056
  const data = await response.json();
@@ -11542,6 +12058,7 @@ var require_geolocation = __commonJS({
11542
12058
  const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
11543
12059
  if (reason === "rate_limited") {
11544
12060
  const backoffMs = markIpapiRateLimited();
12061
+ await shareIpapiBackoff(strapi2);
11545
12062
  logIpapiRateLimit(
11546
12063
  strapi2,
11547
12064
  `[magic-sessionmanager/geolocation] API reported rate limit; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11550,7 +12067,7 @@ var require_geolocation = __commonJS({
11550
12067
  strapi2.log.warn("[magic-sessionmanager/geolocation] Provider rejected the lookup");
11551
12068
  }
11552
12069
  const fallback = this.getFallbackData(lookupIp, reason, "ipapi", data.reason);
11553
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12070
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11554
12071
  return fallback;
11555
12072
  }
11556
12073
  const result = {
@@ -11587,7 +12104,7 @@ var require_geolocation = __commonJS({
11587
12104
  _source: "ipapi"
11588
12105
  };
11589
12106
  strapi2.log.debug("[magic-sessionmanager/geolocation] ipapi lookup completed");
11590
- cacheIpapiResult(lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
12107
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
11591
12108
  return result;
11592
12109
  } catch (error) {
11593
12110
  const status = error?.name === "AbortError" ? "error" : "error";
@@ -11596,7 +12113,7 @@ var require_geolocation = __commonJS({
11596
12113
  error?.name || "Error"
11597
12114
  );
11598
12115
  const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
11599
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12116
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11600
12117
  return fallback;
11601
12118
  } finally {
11602
12119
  clearTimeout(timer);
@@ -12166,12 +12683,10 @@ var require_services = __commonJS({
12166
12683
  "server/src/services/index.js"(exports, module) {
12167
12684
  "use strict";
12168
12685
  var session = require_session2();
12169
- var licenseGuard = require_license_guard();
12170
12686
  var geolocation = require_geolocation();
12171
12687
  var notifications = require_notifications();
12172
12688
  module.exports = {
12173
12689
  session,
12174
- "license-guard": licenseGuard,
12175
12690
  geolocation,
12176
12691
  notifications
12177
12692
  };
@@ -12183,12 +12698,7 @@ var require_rate_limit = __commonJS({
12183
12698
  "server/src/middlewares/rate-limit.js"(exports, module) {
12184
12699
  "use strict";
12185
12700
  var { getPluginSettings } = require_settings_loader();
12186
- var buckets = /* @__PURE__ */ new Map();
12187
- var prune = (now) => {
12188
- for (const [key, entry] of buckets) {
12189
- if (entry.expiresAt <= now) buckets.delete(key);
12190
- }
12191
- };
12701
+ var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
12192
12702
  var callerKey = (ctx) => {
12193
12703
  const userId = ctx.state?.user?.id;
12194
12704
  if (userId) return `u:${userId}`;
@@ -12208,15 +12718,7 @@ var require_rate_limit = __commonJS({
12208
12718
  const normalizedPath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") || "/" : rawPath;
12209
12719
  return `${method} path:${normalizedPath}`;
12210
12720
  };
12211
- var RESOLVED_TTL_MS = 3e4;
12212
- var resolvedCache = /* @__PURE__ */ new Map();
12213
12721
  async function resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) {
12214
- const now = Date.now();
12215
- const cacheKey = `${profile}:${routeMax}:${routeWindowMs}`;
12216
- const cachedEntry = resolvedCache.get(cacheKey);
12217
- if (cachedEntry && now - cachedEntry.at < RESOLVED_TTL_MS) {
12218
- return { max: cachedEntry.max, windowMs: cachedEntry.windowMs };
12219
- }
12220
12722
  let settings;
12221
12723
  try {
12222
12724
  settings = await getPluginSettings(strapi2);
@@ -12244,7 +12746,6 @@ var require_rate_limit = __commonJS({
12244
12746
  } else {
12245
12747
  resolved = { max: routeMax, windowMs: routeWindowMs };
12246
12748
  }
12247
- resolvedCache.set(cacheKey, { ...resolved, at: now });
12248
12749
  return resolved;
12249
12750
  }
12250
12751
  var rateLimit = (cfg = {}, { strapi: strapi2 }) => {
@@ -12253,17 +12754,12 @@ var require_rate_limit = __commonJS({
12253
12754
  const profile = cfg.profile === "read" || cfg.profile === "write" ? cfg.profile : null;
12254
12755
  return async (ctx, next) => {
12255
12756
  const { max, windowMs } = profile ? await resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) : { max: routeMax, windowMs: routeWindowMs };
12256
- const key = `${routeKey(ctx)}::${callerKey(ctx)}`;
12757
+ const key = hashedKey("rl", `${routeKey(ctx)}::${callerKey(ctx)}`);
12257
12758
  const now = Date.now();
12258
- if (buckets.size > 5e3) prune(now);
12259
- let entry = buckets.get(key);
12260
- if (!entry || entry.expiresAt <= now) {
12261
- entry = { count: 0, expiresAt: now + windowMs };
12262
- buckets.set(key, entry);
12263
- }
12264
- entry.count += 1;
12265
- if (entry.count > max) {
12266
- const retryAfterSec = Math.ceil((entry.expiresAt - now) / 1e3);
12759
+ const entry = await getCoordinator(strapi2).hit(key, windowMs);
12760
+ const expiresAt = entry.windowStart + windowMs;
12761
+ if (entry.hits > max) {
12762
+ const retryAfterSec = Math.max(1, Math.ceil((expiresAt - now) / 1e3));
12267
12763
  ctx.set("Retry-After", String(retryAfterSec));
12268
12764
  strapi2.log.warn("[magic-sessionmanager] Content API rate limit exceeded");
12269
12765
  ctx.status = 429;
@@ -12285,8 +12781,7 @@ var require_rate_limit = __commonJS({
12285
12781
  resolveLimits,
12286
12782
  routeKey,
12287
12783
  reset() {
12288
- buckets.clear();
12289
- resolvedCache.clear();
12784
+ __resetMemoryForTests();
12290
12785
  }
12291
12786
  };
12292
12787
  module.exports = rateLimit;