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
@@ -79,24 +79,746 @@ var require_logger = __commonJS({
79
79
  }
80
80
  });
81
81
 
82
+ // server/src/utils/coordination.js
83
+ var require_coordination = __commonJS({
84
+ "server/src/utils/coordination.js"(exports2, module2) {
85
+ "use strict";
86
+ var { AsyncLocalStorage } = require("node:async_hooks");
87
+ var crypto = require("node:crypto");
88
+ var os = require("node:os");
89
+ var heldLocks = new AsyncLocalStorage();
90
+ var TABLES = Object.freeze({
91
+ counters: "magic_sm_counters",
92
+ leases: "magic_sm_leases",
93
+ cache: "magic_sm_cache"
94
+ });
95
+ var PG_LOCK_NAMESPACE = 5067597;
96
+ var NEVER_EXPIRES = 8e15;
97
+ var MAX_KEY_LENGTH = 191;
98
+ var LEASE_SHRINK_MARGIN_MS = 6e4;
99
+ var COUNTER_COLUMNS = Object.freeze(["hits", "window_start", "blocked_until"]);
100
+ var instanceIdCache = null;
101
+ function getInstanceId() {
102
+ if (instanceIdCache) return instanceIdCache;
103
+ let host = "unknown";
104
+ try {
105
+ host = os.hostname() || "unknown";
106
+ } catch {
107
+ }
108
+ const hostHash = crypto.createHash("sha256").update(host).digest("hex").slice(0, 12);
109
+ instanceIdCache = `${hostHash}:${process.pid}:${crypto.randomBytes(4).toString("hex")}`;
110
+ return instanceIdCache;
111
+ }
112
+ function getHostFingerprint() {
113
+ return getInstanceId().split(":")[0];
114
+ }
115
+ function hashedKey(prefix, raw) {
116
+ const digest = crypto.createHash("sha256").update(String(raw)).digest("hex").slice(0, 48);
117
+ return `${prefix}:${digest}`;
118
+ }
119
+ function toNumber(value) {
120
+ if (value === null || value === void 0) return 0;
121
+ const n = Number(value);
122
+ return Number.isFinite(n) ? n : 0;
123
+ }
124
+ function assertKey(key) {
125
+ if (typeof key !== "string" || key.length === 0 || key.length > MAX_KEY_LENGTH) {
126
+ throw new TypeError("coordination key must be a non-empty string of at most 191 characters");
127
+ }
128
+ }
129
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
130
+ var LockTimeoutError = class extends Error {
131
+ constructor(name) {
132
+ super(`Timed out waiting for lock "${name}"`);
133
+ this.name = "LockTimeoutError";
134
+ }
135
+ };
136
+ function createMemoryBackend() {
137
+ const counters = /* @__PURE__ */ new Map();
138
+ const leases = /* @__PURE__ */ new Map();
139
+ const revisions = /* @__PURE__ */ new Map();
140
+ const lockTails = /* @__PURE__ */ new Map();
141
+ const pruneCounters = (now) => {
142
+ if (counters.size < 5e3) return;
143
+ for (const [k, v] of counters) {
144
+ if (v.expiresAt <= now && v.blockedUntil <= now) counters.delete(k);
145
+ }
146
+ };
147
+ return {
148
+ mode: "memory",
149
+ async hit(key, windowMs, now = Date.now()) {
150
+ pruneCounters(now);
151
+ let entry = counters.get(key);
152
+ if (!entry) {
153
+ entry = { hits: 0, windowStart: 0, blockedUntil: 0, expiresAt: 0 };
154
+ counters.set(key, entry);
155
+ }
156
+ if (entry.windowStart <= now - windowMs) {
157
+ entry.hits = 1;
158
+ entry.windowStart = now;
159
+ } else {
160
+ entry.hits += 1;
161
+ }
162
+ entry.expiresAt = Math.max(entry.expiresAt, now + windowMs);
163
+ return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
164
+ },
165
+ async peek(key) {
166
+ const entry = counters.get(key);
167
+ if (!entry) return null;
168
+ return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
169
+ },
170
+ async block(key, untilMs) {
171
+ const entry = counters.get(key) || {
172
+ hits: 0,
173
+ windowStart: 0,
174
+ blockedUntil: 0,
175
+ expiresAt: 0
176
+ };
177
+ if (entry.blockedUntil < untilMs) entry.blockedUntil = untilMs;
178
+ entry.expiresAt = Math.max(entry.expiresAt, untilMs);
179
+ counters.set(key, entry);
180
+ },
181
+ async clear(key) {
182
+ counters.delete(key);
183
+ },
184
+ async release(key) {
185
+ const entry = counters.get(key);
186
+ if (entry && entry.hits > 0) entry.hits -= 1;
187
+ },
188
+ async getRevision(name) {
189
+ return revisions.get(name) || 0;
190
+ },
191
+ async bumpRevision(name) {
192
+ const next = (revisions.get(name) || 0) + 1;
193
+ revisions.set(name, next);
194
+ return next;
195
+ },
196
+ async tryAcquireLease(name, ttlMs, owner, now = Date.now()) {
197
+ const lease = leases.get(name);
198
+ if (lease && lease.until > now && lease.owner !== owner && lease.until <= now + ttlMs + LEASE_SHRINK_MARGIN_MS) {
199
+ return false;
200
+ }
201
+ leases.set(name, { owner, until: now + ttlMs });
202
+ return true;
203
+ },
204
+ async releaseLease(name, owner) {
205
+ const lease = leases.get(name);
206
+ if (lease && lease.owner === owner) leases.delete(name);
207
+ },
208
+ async withLock(name, fn) {
209
+ const previous = lockTails.get(name) || Promise.resolve();
210
+ let release;
211
+ const current = new Promise((resolve) => {
212
+ release = resolve;
213
+ });
214
+ const tail = previous.then(() => current);
215
+ lockTails.set(name, tail);
216
+ await previous;
217
+ try {
218
+ return await fn();
219
+ } finally {
220
+ release();
221
+ if (lockTails.get(name) === tail) lockTails.delete(name);
222
+ }
223
+ },
224
+ // The shared cache is an L2 behind per-module L1 caches; in memory mode
225
+ // the L1 caches already cover the process, so this layer stays empty.
226
+ async cacheGet() {
227
+ return null;
228
+ },
229
+ async cacheSet() {
230
+ },
231
+ async prune(now = Date.now()) {
232
+ let removed = 0;
233
+ for (const [k, v] of counters) {
234
+ if (v.expiresAt <= now && v.blockedUntil <= now) {
235
+ counters.delete(k);
236
+ removed++;
237
+ }
238
+ }
239
+ return removed;
240
+ },
241
+ reset() {
242
+ counters.clear();
243
+ leases.clear();
244
+ revisions.clear();
245
+ lockTails.clear();
246
+ }
247
+ };
248
+ }
249
+ function normalizeDialect(client) {
250
+ const value = String(client || "").toLowerCase();
251
+ if (value === "postgres" || value === "pg" || value === "postgresql") return "postgres";
252
+ if (value === "mysql" || value === "mysql2" || value === "mariadb") return "mysql";
253
+ if (value === "sqlite" || value === "sqlite3" || value === "better-sqlite3") return "sqlite";
254
+ return "other";
255
+ }
256
+ async function ensureTables(knex) {
257
+ const definitions = [
258
+ [
259
+ TABLES.counters,
260
+ (table) => {
261
+ table.string("k", MAX_KEY_LENGTH).notNullable().primary();
262
+ table.integer("hits").notNullable().defaultTo(0);
263
+ table.bigInteger("window_start").notNullable().defaultTo(0);
264
+ table.bigInteger("blocked_until").notNullable().defaultTo(0);
265
+ table.bigInteger("expires_at").notNullable().defaultTo(0);
266
+ table.index(["expires_at"], "magic_sm_counters_expires_idx");
267
+ }
268
+ ],
269
+ [
270
+ TABLES.leases,
271
+ (table) => {
272
+ table.string("name", MAX_KEY_LENGTH).notNullable().primary();
273
+ table.string("owner", MAX_KEY_LENGTH).notNullable().defaultTo("");
274
+ table.bigInteger("lease_until").notNullable().defaultTo(0);
275
+ }
276
+ ],
277
+ [
278
+ TABLES.cache,
279
+ (table) => {
280
+ table.string("k", MAX_KEY_LENGTH).notNullable().primary();
281
+ table.text("v");
282
+ table.bigInteger("expires_at").notNullable().defaultTo(0);
283
+ table.index(["expires_at"], "magic_sm_cache_expires_idx");
284
+ }
285
+ ]
286
+ ];
287
+ for (const [name, build] of definitions) {
288
+ if (await knex.schema.hasTable(name)) continue;
289
+ try {
290
+ await knex.schema.createTable(name, build);
291
+ } catch (err) {
292
+ if (!await knex.schema.hasTable(name)) throw err;
293
+ }
294
+ }
295
+ }
296
+ function createDatabaseBackend({ knex, dialect }) {
297
+ const kind = normalizeDialect(dialect);
298
+ const readCounter = async (key) => {
299
+ const row = await knex(TABLES.counters).select("hits", "window_start", "blocked_until").where({ k: key }).first();
300
+ if (!row) return null;
301
+ return {
302
+ hits: toNumber(row.hits),
303
+ windowStart: toNumber(row.window_start),
304
+ blockedUntil: toNumber(row.blocked_until)
305
+ };
306
+ };
307
+ const ensureCounterRow = (key, expiresAt) => knex(TABLES.counters).insert({ k: key, hits: 0, window_start: 0, blocked_until: 0, expires_at: expiresAt }).onConflict("k").ignore();
308
+ const supportsReturning = kind === "postgres" || kind === "sqlite";
309
+ const toCounter = (row) => row ? {
310
+ hits: toNumber(row.hits),
311
+ windowStart: toNumber(row.window_start),
312
+ blockedUntil: toNumber(row.blocked_until)
313
+ } : null;
314
+ const updateCounterReturning = async (key, withReturning, withoutReturning) => {
315
+ if (supportsReturning) {
316
+ const rows = await withReturning(knex(TABLES.counters).where({ k: key }));
317
+ return Array.isArray(rows) && rows.length > 0 ? toCounter(rows[0]) : null;
318
+ }
319
+ return knex.transaction(async (trx) => {
320
+ if (toNumber(await withoutReturning(trx)) === 0) return null;
321
+ const row = await trx(TABLES.counters).select(...COUNTER_COLUMNS).where({ k: key }).forUpdate().first();
322
+ return toCounter(row);
323
+ });
324
+ };
325
+ const tryAcquireLease = async (name, ttlMs, owner, now = Date.now()) => {
326
+ await knex(TABLES.leases).insert({ name, owner: "", lease_until: 0 }).onConflict("name").ignore();
327
+ const changed = await knex(TABLES.leases).where({ name }).andWhere((qb) => {
328
+ qb.where("lease_until", "<=", now).orWhere("owner", owner).orWhere("lease_until", ">", now + ttlMs + LEASE_SHRINK_MARGIN_MS);
329
+ }).update({ owner, lease_until: now + ttlMs });
330
+ return toNumber(changed) === 1;
331
+ };
332
+ const releaseLease = async (name, owner) => {
333
+ await knex(TABLES.leases).where({ name, owner }).update({ lease_until: 0 });
334
+ };
335
+ return {
336
+ mode: "database",
337
+ dialect: kind,
338
+ /**
339
+ * Increments a fixed-window counter in one atomic UPDATE and returns the
340
+ * value written by THIS update. The CASE expressions only read
341
+ * `window_start`, which is assigned last, so the result is the same under
342
+ * MySQL's left-to-right SET evaluation and the all-old-values semantics
343
+ * of PostgreSQL and SQLite.
344
+ *
345
+ * Reading the row in a separate statement after the UPDATE would return
346
+ * the count after later concurrent increments as well, so under a burst
347
+ * most callers would see a number above the limit and be rejected
348
+ * (measured: 2 of 48 parallel requests allowed with a limit of 10).
349
+ * PostgreSQL and SQLite therefore use `UPDATE ... RETURNING` (knex
350
+ * `returning`, SQLite >= 3.35); other dialects run UPDATE and SELECT in
351
+ * one transaction, where the row lock taken by the UPDATE keeps other
352
+ * writers out until the read is done.
353
+ */
354
+ async hit(key, windowMs, now = Date.now()) {
355
+ const cutoff = now - windowMs;
356
+ const data = {
357
+ hits: knex.raw("CASE WHEN window_start <= ? THEN 1 ELSE hits + 1 END", [cutoff]),
358
+ expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
359
+ now + windowMs,
360
+ now + windowMs
361
+ ]),
362
+ window_start: knex.raw("CASE WHEN window_start <= ? THEN ? ELSE window_start END", [
363
+ cutoff,
364
+ now
365
+ ])
366
+ };
367
+ const update = () => updateCounterReturning(
368
+ key,
369
+ (qb) => qb.update(data, [...COUNTER_COLUMNS]),
370
+ (trx) => trx(TABLES.counters).where({ k: key }).update(data)
371
+ );
372
+ let row = await update();
373
+ if (!row) {
374
+ await ensureCounterRow(key, now + windowMs);
375
+ row = await update();
376
+ }
377
+ return row || await readCounter(key) || { hits: 1, windowStart: now, blockedUntil: 0 };
378
+ },
379
+ /**
380
+ * Gives back one attempt counted by `hit` (for example when the request
381
+ * ended with a server error and must not count as a failed login).
382
+ */
383
+ async release(key) {
384
+ await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
385
+ },
386
+ peek: readCounter,
387
+ async block(key, untilMs) {
388
+ await ensureCounterRow(key, untilMs);
389
+ await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
390
+ blocked_until: untilMs,
391
+ expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
392
+ untilMs,
393
+ untilMs
394
+ ])
395
+ });
396
+ },
397
+ async clear(key) {
398
+ await knex(TABLES.counters).where({ k: key }).del();
399
+ },
400
+ async getRevision(name) {
401
+ const row = await knex(TABLES.counters).select("hits").where({ k: `rev:${name}` }).first();
402
+ return row ? toNumber(row.hits) : 0;
403
+ },
404
+ async bumpRevision(name) {
405
+ const key = `rev:${name}`;
406
+ await ensureCounterRow(key, NEVER_EXPIRES);
407
+ const data = { hits: knex.raw("hits + 1"), expires_at: NEVER_EXPIRES };
408
+ const row = await updateCounterReturning(
409
+ key,
410
+ (qb) => qb.update(data, [...COUNTER_COLUMNS]),
411
+ (trx) => trx(TABLES.counters).where({ k: key }).update(data)
412
+ );
413
+ return row ? row.hits : this.getRevision(name);
414
+ },
415
+ tryAcquireLease,
416
+ releaseLease,
417
+ /**
418
+ * Runs `fn` while holding a cluster-wide named lock.
419
+ *
420
+ * PostgreSQL: a transaction-level advisory lock (`pg_advisory_xact_lock`)
421
+ * on a dedicated transaction; it is released when that transaction ends,
422
+ * also when the process dies. `fn` runs on other connections, so it must
423
+ * not depend on that transaction. Other dialects: a lease row, polled
424
+ * until it is free or `waitMs` elapses; the lease expires after `ttlMs`
425
+ * if the holder dies.
426
+ */
427
+ async withLock(name, fn, { waitMs = 15e3, ttlMs = 3e4, owner } = {}) {
428
+ if (kind === "postgres") {
429
+ const timeout = Math.max(1, Math.floor(waitMs));
430
+ return knex.transaction(async (trx) => {
431
+ try {
432
+ await trx.raw(`SET LOCAL lock_timeout = '${timeout}ms'`);
433
+ await trx.raw("SELECT pg_advisory_xact_lock(?, hashtext(?))", [
434
+ PG_LOCK_NAMESPACE,
435
+ name
436
+ ]);
437
+ } catch (err) {
438
+ if (err?.code === "55P03") throw new LockTimeoutError(name);
439
+ throw err;
440
+ }
441
+ return fn();
442
+ });
443
+ }
444
+ const leaseName = `lock:${name}`;
445
+ const deadline = Date.now() + waitMs;
446
+ let delay = 25;
447
+ while (!await tryAcquireLease(leaseName, ttlMs, owner)) {
448
+ if (Date.now() >= deadline) throw new LockTimeoutError(name);
449
+ await sleep(delay + Math.floor(Math.random() * delay));
450
+ delay = Math.min(delay * 2, 250);
451
+ }
452
+ try {
453
+ return await fn();
454
+ } finally {
455
+ await releaseLease(leaseName, owner).catch(() => {
456
+ });
457
+ }
458
+ },
459
+ async cacheGet(key, now = Date.now()) {
460
+ const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: key }).andWhere("expires_at", ">", now).first();
461
+ if (!row || row.v === null || row.v === void 0) return null;
462
+ try {
463
+ return JSON.parse(row.v);
464
+ } catch {
465
+ return null;
466
+ }
467
+ },
468
+ async cacheSet(key, value, ttlMs, now = Date.now()) {
469
+ const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
470
+ await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
471
+ },
472
+ async prune(now = Date.now()) {
473
+ const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
474
+ const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
475
+ return toNumber(counters) + toNumber(cache);
476
+ }
477
+ };
478
+ }
479
+ var sharedMemory = createMemoryBackend();
480
+ var coordinators = /* @__PURE__ */ new WeakMap();
481
+ function createCoordinator({
482
+ database = null,
483
+ counterStore = null,
484
+ log = null,
485
+ owner = getInstanceId()
486
+ } = {}) {
487
+ let db = database;
488
+ let lastFallbackLogAt = 0;
489
+ const reportFallback = (operation, err) => {
490
+ const now = Date.now();
491
+ if (now - lastFallbackLogAt < 6e4) return;
492
+ lastFallbackLogAt = now;
493
+ log?.warn?.(
494
+ `[COORDINATION] ${operation} failed on the shared store, using process-local state:`,
495
+ err?.name || "Error"
496
+ );
497
+ };
498
+ const run = async (operation, sharedCall, memoryCall) => {
499
+ if (!db) return memoryCall();
500
+ try {
501
+ return await sharedCall(db);
502
+ } catch (err) {
503
+ if (err instanceof LockTimeoutError) throw err;
504
+ reportFallback(operation, err);
505
+ return memoryCall();
506
+ }
507
+ };
508
+ const counterCall = async (operation, method, args) => {
509
+ if (counterStore && typeof counterStore[method] === "function") {
510
+ try {
511
+ return await counterStore[method](...args);
512
+ } catch (err) {
513
+ reportFallback(`${operation} (custom store)`, err);
514
+ }
515
+ }
516
+ return run(
517
+ operation,
518
+ (backend) => backend[method](...args),
519
+ () => sharedMemory[method](...args)
520
+ );
521
+ };
522
+ return {
523
+ owner,
524
+ get mode() {
525
+ if (counterStore) return db ? "custom+database" : "custom+memory";
526
+ return db ? "database" : "memory";
527
+ },
528
+ get dialect() {
529
+ return db?.dialect || null;
530
+ },
531
+ /** Switches the coordinator to the database backend. */
532
+ attachDatabase(backend) {
533
+ db = backend;
534
+ },
535
+ /** Switches the coordinator back to process-local state. */
536
+ detachDatabase() {
537
+ db = null;
538
+ },
539
+ /**
540
+ * Increments the fixed-window counter `key`.
541
+ * @returns {Promise<{hits: number, windowStart: number, blockedUntil: number}>}
542
+ */
543
+ hit(key, windowMs) {
544
+ assertKey(key);
545
+ return counterCall("counter increment", "hit", [key, windowMs]);
546
+ },
547
+ /** @returns {Promise<{hits: number, windowStart: number, blockedUntil: number}|null>} */
548
+ peek(key) {
549
+ assertKey(key);
550
+ return counterCall("counter read", "peek", [key]);
551
+ },
552
+ /** Raises the block deadline of `key` to `untilMs` (never lowers it). */
553
+ block(key, untilMs) {
554
+ assertKey(key);
555
+ return counterCall("counter block", "block", [key, untilMs]);
556
+ },
557
+ /** Removes counter `key`. */
558
+ clear(key) {
559
+ assertKey(key);
560
+ return counterCall("counter clear", "clear", [key]);
561
+ },
562
+ /**
563
+ * Gives back one hit of counter `key`. Optional for a custom
564
+ * `counterStore`: a store without `release` keeps the hit.
565
+ */
566
+ async release(key) {
567
+ assertKey(key);
568
+ if (counterStore && typeof counterStore.release !== "function") return;
569
+ return counterCall("counter release", "release", [key]);
570
+ },
571
+ getRevision(name) {
572
+ return run(
573
+ "revision read",
574
+ (backend) => backend.getRevision(name),
575
+ () => sharedMemory.getRevision(name)
576
+ );
577
+ },
578
+ bumpRevision(name) {
579
+ return run(
580
+ "revision bump",
581
+ (backend) => backend.bumpRevision(name),
582
+ () => sharedMemory.bumpRevision(name)
583
+ );
584
+ },
585
+ /**
586
+ * Takes the lease `name` for `ttlMs` unless another process holds an
587
+ * unexpired lease. Re-acquiring an own lease extends it.
588
+ * @returns {Promise<boolean>}
589
+ */
590
+ tryAcquireLease(name, ttlMs) {
591
+ return run(
592
+ "lease acquire",
593
+ (backend) => backend.tryAcquireLease(name, ttlMs, owner),
594
+ () => sharedMemory.tryAcquireLease(name, ttlMs, owner)
595
+ );
596
+ },
597
+ releaseLease(name) {
598
+ return run(
599
+ "lease release",
600
+ (backend) => backend.releaseLease(name, owner),
601
+ () => sharedMemory.releaseLease(name, owner)
602
+ );
603
+ },
604
+ /**
605
+ * Runs `fn` inside the cluster-wide critical section `name`. A process-
606
+ * local mutex is always taken first, so concurrent callers in one process
607
+ * do not compete for database connections.
608
+ *
609
+ * @template T
610
+ * @param {string} name
611
+ * @param {() => Promise<T>} fn
612
+ * @param {{waitMs?: number, ttlMs?: number}} [options]
613
+ * @returns {Promise<T>}
614
+ * @throws {LockTimeoutError} When the lock could not be taken in time
615
+ */
616
+ withLock(name, fn, options = {}) {
617
+ const held = heldLocks.getStore();
618
+ if (held && held.has(name)) return fn();
619
+ const inner = () => heldLocks.run(/* @__PURE__ */ new Set([...held || [], name]), fn);
620
+ return sharedMemory.withLock(`local:${name}`, async () => {
621
+ if (!db) return inner();
622
+ let entered = false;
623
+ try {
624
+ return await db.withLock(
625
+ name,
626
+ () => {
627
+ entered = true;
628
+ return inner();
629
+ },
630
+ { ...options, owner }
631
+ );
632
+ } catch (err) {
633
+ if (entered || err instanceof LockTimeoutError) throw err;
634
+ reportFallback("lock", err);
635
+ return inner();
636
+ }
637
+ });
638
+ },
639
+ cacheGet(key) {
640
+ assertKey(key);
641
+ return run(
642
+ "cache read",
643
+ (backend) => backend.cacheGet(key),
644
+ () => sharedMemory.cacheGet(key)
645
+ );
646
+ },
647
+ cacheSet(key, value, ttlMs) {
648
+ assertKey(key);
649
+ return run(
650
+ "cache write",
651
+ (backend) => backend.cacheSet(key, value, ttlMs),
652
+ () => sharedMemory.cacheSet(key, value, ttlMs)
653
+ );
654
+ },
655
+ prune() {
656
+ return run(
657
+ "prune",
658
+ (backend) => backend.prune(),
659
+ () => sharedMemory.prune()
660
+ );
661
+ }
662
+ };
663
+ }
664
+ function getCoordinator(strapi2) {
665
+ const key = strapi2 && typeof strapi2 === "object" ? strapi2 : sharedMemory;
666
+ let coordinator = coordinators.get(key);
667
+ if (!coordinator) {
668
+ const config2 = readCoordinationConfig(strapi2);
669
+ coordinator = createCoordinator({
670
+ counterStore: config2.counterStore,
671
+ log: strapi2?.log || null
672
+ });
673
+ coordinators.set(key, coordinator);
674
+ }
675
+ return coordinator;
676
+ }
677
+ function readCoordinationConfig(strapi2) {
678
+ let raw;
679
+ try {
680
+ raw = strapi2?.config?.get?.("plugin::magic-sessionmanager.coordination") || null;
681
+ } catch {
682
+ raw = null;
683
+ }
684
+ const config2 = raw && typeof raw === "object" ? raw : {};
685
+ const counterStore = config2.counterStore && typeof config2.counterStore === "object" ? config2.counterStore : null;
686
+ return { enabled: config2.enabled !== false, counterStore };
687
+ }
688
+ async function initCoordination(strapi2, log = strapi2?.log) {
689
+ const coordinator = getCoordinator(strapi2);
690
+ const config2 = readCoordinationConfig(strapi2);
691
+ if (!config2.enabled) {
692
+ log?.info?.("[COORDINATION] Disabled by config; using process-local state");
693
+ return coordinator;
694
+ }
695
+ const knex = strapi2?.db?.connection;
696
+ if (typeof knex !== "function" || !knex.schema) {
697
+ log?.warn?.("[COORDINATION] No database connection; using process-local state");
698
+ return coordinator;
699
+ }
700
+ try {
701
+ await ensureTables(knex);
702
+ coordinator.attachDatabase(
703
+ createDatabaseBackend({
704
+ knex,
705
+ dialect: strapi2.db?.dialect?.client || knex.client?.config?.client
706
+ })
707
+ );
708
+ log?.info?.(`[COORDINATION] Shared state enabled (${coordinator.mode})`);
709
+ } catch (err) {
710
+ log?.error?.(
711
+ "[COORDINATION] Could not prepare shared tables; using process-local state:",
712
+ err?.name || "Error"
713
+ );
714
+ }
715
+ return coordinator;
716
+ }
717
+ module2.exports = {
718
+ TABLES,
719
+ LockTimeoutError,
720
+ createCoordinator,
721
+ createDatabaseBackend,
722
+ createMemoryBackend,
723
+ ensureTables,
724
+ getCoordinator,
725
+ getHostFingerprint,
726
+ getInstanceId,
727
+ hashedKey,
728
+ initCoordination,
729
+ normalizeDialect,
730
+ __resetMemoryForTests() {
731
+ sharedMemory.reset();
732
+ }
733
+ };
734
+ }
735
+ });
736
+
737
+ // server/src/utils/plugin-store.js
738
+ var require_plugin_store = __commonJS({
739
+ "server/src/utils/plugin-store.js"(exports2, module2) {
740
+ "use strict";
741
+ var { getCoordinator } = require_coordination();
742
+ var PLUGIN_ID = "magic-sessionmanager";
743
+ var CORE_STORE_UID = "strapi::core-store";
744
+ function coreStoreKey(key) {
745
+ return `plugin_${PLUGIN_ID}_${key}`;
746
+ }
747
+ async function collapseDuplicateStoreRows(strapi2, key) {
748
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
749
+ if (!query || typeof query.findMany !== "function") return 0;
750
+ const rows = await query.findMany({
751
+ where: { key: coreStoreKey(key), environment: null, tag: null },
752
+ select: ["id"],
753
+ orderBy: { id: "desc" }
754
+ });
755
+ if (!Array.isArray(rows) || rows.length < 2) return 0;
756
+ const extraIds = rows.slice(1).map((row) => row.id);
757
+ const result = await query.deleteMany({ where: { id: { $in: extraIds } } });
758
+ return Number(result?.count) || 0;
759
+ }
760
+ async function withPluginStoreKey(strapi2, key, fn) {
761
+ const store = strapi2.store({ type: "plugin", name: PLUGIN_ID });
762
+ return getCoordinator(strapi2).withLock(`store:${key}`, async () => {
763
+ try {
764
+ const removed = await collapseDuplicateStoreRows(strapi2, key);
765
+ if (removed > 0) {
766
+ strapi2.log?.warn?.(
767
+ `[magic-sessionmanager] [STORE] Removed ${removed} duplicate store row(s) for "${key}"`
768
+ );
769
+ }
770
+ } catch (err) {
771
+ strapi2.log?.debug?.(
772
+ "[magic-sessionmanager] [STORE] Duplicate check failed:",
773
+ err?.name || "Error"
774
+ );
775
+ }
776
+ return fn(store);
777
+ });
778
+ }
779
+ async function setPluginStoreValue(strapi2, key, value) {
780
+ await withPluginStoreKey(strapi2, key, (store) => store.set({ key, value }));
781
+ }
782
+ var LEGACY_LICENSE_STORE_KEYS = Object.freeze(["licenseKey", "lastValidated", "deviceId"]);
783
+ async function removeLegacyLicenseData(strapi2) {
784
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
785
+ if (!query || typeof query.deleteMany !== "function") return 0;
786
+ const result = await query.deleteMany({
787
+ where: { key: { $in: LEGACY_LICENSE_STORE_KEYS.map(coreStoreKey) } }
788
+ });
789
+ return Number(result?.count) || 0;
790
+ }
791
+ module2.exports = {
792
+ LEGACY_LICENSE_STORE_KEYS,
793
+ PLUGIN_ID,
794
+ collapseDuplicateStoreRows,
795
+ coreStoreKey,
796
+ removeLegacyLicenseData,
797
+ setPluginStoreValue,
798
+ withPluginStoreKey
799
+ };
800
+ }
801
+ });
802
+
82
803
  // server/src/utils/content-api-permissions.js
83
804
  var require_content_api_permissions = __commonJS({
84
805
  "server/src/utils/content-api-permissions.js"(exports2, module2) {
85
806
  "use strict";
807
+ var { withPluginStoreKey } = require_plugin_store();
86
808
  var CONTENT_API_PERMISSIONS_VERSION = 2;
87
- var MAGIC_SESSIONMANAGER_STORE = "magic-sessionmanager";
88
809
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
89
810
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
90
811
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
91
812
  if (role?.type !== "authenticated") return false;
92
- const pluginStore = strapi2.store({ type: "plugin", name: MAGIC_SESSIONMANAGER_STORE });
93
- const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
94
- if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
95
- await pluginStore.set({
96
- key: CONTENT_API_PERMISSIONS_VERSION_KEY,
97
- value: CONTENT_API_PERMISSIONS_VERSION
813
+ return withPluginStoreKey(strapi2, CONTENT_API_PERMISSIONS_VERSION_KEY, async (pluginStore) => {
814
+ const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
815
+ if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
816
+ await pluginStore.set({
817
+ key: CONTENT_API_PERMISSIONS_VERSION_KEY,
818
+ value: CONTENT_API_PERMISSIONS_VERSION
819
+ });
820
+ return true;
98
821
  });
99
- return true;
100
822
  }
101
823
  function createContentApiPermissionsLifecycle(strapi2) {
102
824
  return {
@@ -376,7 +1098,11 @@ var require_encryption = __commonJS({
376
1098
  if (!token) return null;
377
1099
  return crypto.createHash("sha256").update(token).digest("hex");
378
1100
  }
1101
+ function getEncryptionKeyCheck() {
1102
+ return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
1103
+ }
379
1104
  module2.exports = {
1105
+ getEncryptionKeyCheck,
380
1106
  encryptToken,
381
1107
  decryptToken,
382
1108
  generateSessionId,
@@ -435,13 +1161,18 @@ var require_resolve_user = __commonJS({
435
1161
  var require_settings_loader = __commonJS({
436
1162
  "server/src/utils/settings-loader.js"(exports2, module2) {
437
1163
  "use strict";
1164
+ var { getCoordinator } = require_coordination();
438
1165
  var PLUGIN_ID = "magic-sessionmanager";
439
1166
  var SETTINGS_KEY = "settings";
440
1167
  var CACHE_TTL_MS = 30 * 1e3;
1168
+ var REVISION_CHECK_MS = 2 * 1e3;
1169
+ var SETTINGS_REVISION = "settings";
441
1170
  var GEO_IP_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
442
1171
  var GEO_LOOKUP_FAILURE_MODES = /* @__PURE__ */ new Set(["auto", "allow", "block"]);
443
1172
  var cached = null;
444
1173
  var cachedAt = 0;
1174
+ var cachedRevision = null;
1175
+ var revisionCheckedAt = 0;
445
1176
  function toIntInRange(value, fallback, min, max) {
446
1177
  const n = Number.parseInt(value, 10);
447
1178
  if (!Number.isFinite(n)) return fallback;
@@ -555,8 +1286,23 @@ var require_settings_loader = __commonJS({
555
1286
  }
556
1287
  async function getPluginSettings(strapi2) {
557
1288
  const now = Date.now();
1289
+ const coordinator = getCoordinator(strapi2);
558
1290
  if (cached && now - cachedAt < CACHE_TTL_MS) {
559
- return cached;
1291
+ if (now - revisionCheckedAt < REVISION_CHECK_MS) return cached;
1292
+ revisionCheckedAt = now;
1293
+ let revision2;
1294
+ try {
1295
+ revision2 = await coordinator.getRevision(SETTINGS_REVISION);
1296
+ } catch {
1297
+ return cached;
1298
+ }
1299
+ if (revision2 === cachedRevision) return cached;
1300
+ }
1301
+ let revision;
1302
+ try {
1303
+ revision = await coordinator.getRevision(SETTINGS_REVISION);
1304
+ } catch {
1305
+ revision = null;
560
1306
  }
561
1307
  const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
562
1308
  let storedSettings;
@@ -573,6 +1319,8 @@ var require_settings_loader = __commonJS({
573
1319
  const merged = { ...staticConfig, ...storedSettings };
574
1320
  cached = merged;
575
1321
  cachedAt = now;
1322
+ cachedRevision = revision;
1323
+ revisionCheckedAt = now;
576
1324
  return merged;
577
1325
  }
578
1326
  function getPluginSettingsSync(strapi2) {
@@ -582,11 +1330,30 @@ var require_settings_loader = __commonJS({
582
1330
  function invalidateSettingsCache() {
583
1331
  cached = null;
584
1332
  cachedAt = 0;
1333
+ cachedRevision = null;
1334
+ revisionCheckedAt = 0;
1335
+ }
1336
+ async function getSettingsRevision(strapi2) {
1337
+ return getCoordinator(strapi2).getRevision(SETTINGS_REVISION);
1338
+ }
1339
+ async function notifySettingsChanged(strapi2) {
1340
+ invalidateSettingsCache();
1341
+ try {
1342
+ return await getCoordinator(strapi2).bumpRevision(SETTINGS_REVISION);
1343
+ } catch (err) {
1344
+ strapi2?.log?.warn?.(
1345
+ `[${PLUGIN_ID}] settings-loader: could not publish the settings revision:`,
1346
+ err?.name || "Error"
1347
+ );
1348
+ return null;
1349
+ }
585
1350
  }
586
1351
  module2.exports = {
587
1352
  getPluginSettings,
588
1353
  getPluginSettingsSync,
589
1354
  invalidateSettingsCache,
1355
+ notifySettingsChanged,
1356
+ getSettingsRevision,
590
1357
  normalizeStoredSettings,
591
1358
  normalizeRetentionDays,
592
1359
  getSessionCreationGraceMs,
@@ -5127,7 +5894,7 @@ var require_bootstrap = __commonJS({
5127
5894
  "server/src/bootstrap.js"(exports2, module2) {
5128
5895
  "use strict";
5129
5896
  var getClientIp = require_getClientIp();
5130
- var { encryptToken, hashToken } = require_encryption();
5897
+ var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
5131
5898
  var { createLogger } = require_logger();
5132
5899
  var { resolveUserDocumentId } = require_resolve_user();
5133
5900
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -5137,6 +5904,13 @@ var require_bootstrap = __commonJS({
5137
5904
  var { REVOCATION_UID } = require_session_revocation();
5138
5905
  var { getNativeSessionManager } = require_native_session_manager();
5139
5906
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
5907
+ var {
5908
+ getCoordinator,
5909
+ hashedKey,
5910
+ initCoordination,
5911
+ LockTimeoutError
5912
+ } = require_coordination();
5913
+ var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
5140
5914
  var {
5141
5915
  classifyJwtIssuingRequest,
5142
5916
  isFailedLoginTrackedPath,
@@ -5150,6 +5924,12 @@ var require_bootstrap = __commonJS({
5150
5924
  stripAuthTokensFromResponse
5151
5925
  } = require_refresh_token();
5152
5926
  var SESSION_UID = "plugin::magic-sessionmanager.session";
5927
+ var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
5928
+ var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5929
+ var JOB_LEASES = Object.freeze({
5930
+ idleCleanup: "job:idle-cleanup",
5931
+ retention: "job:retention"
5932
+ });
5153
5933
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
5154
5934
  var deferredContentApiPermissionSetup = /* @__PURE__ */ new WeakMap();
5155
5935
  async function getRequestSettings(strapi2, ctx) {
@@ -5164,6 +5944,16 @@ var require_bootstrap = __commonJS({
5164
5944
  }
5165
5945
  return settings;
5166
5946
  }
5947
+ async function removeLegacyLicenseRows(strapi2, log) {
5948
+ try {
5949
+ const removed = await removeLegacyLicenseData(strapi2);
5950
+ if (removed > 0) {
5951
+ log.info(`[CLEANUP] Removed ${removed} stored value(s) of the former license feature`);
5952
+ }
5953
+ } catch (err) {
5954
+ log.warn("[CLEANUP] Could not remove former license data:", err?.name || "Error");
5955
+ }
5956
+ }
5167
5957
  module2.exports = async ({ strapi: strapi2 }) => {
5168
5958
  const log = createLogger(strapi2);
5169
5959
  log.info("[START] Bootstrap starting...");
@@ -5174,21 +5964,36 @@ var require_bootstrap = __commonJS({
5174
5964
  throw e;
5175
5965
  }
5176
5966
  try {
5967
+ const coordinator = await initCoordination(strapi2, log);
5968
+ await checkEncryptionKeyConsistency(strapi2, log);
5177
5969
  await ensureSessionLookupIndexes(strapi2, log);
5178
5970
  await registerSessionAwareAuthStrategy(strapi2);
5179
- const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
5180
- await licenseGuardService.initialize();
5181
- log.info("[SUCCESS] Session Manager active - all features are available without a license key");
5971
+ await removeLegacyLicenseRows(strapi2, log);
5182
5972
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
5183
5973
  if (!strapi2.sessionManagerIntervals) {
5184
5974
  strapi2.sessionManagerIntervals = {};
5185
5975
  }
5976
+ const runIdleCleanupIfLeader = async (intervalMs, useDbDirect) => {
5977
+ const leaseMs = Math.max(60 * 1e3, intervalMs - 30 * 1e3);
5978
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.idleCleanup, leaseMs)) {
5979
+ log.debug("[CLEANUP] Another instance holds the cleanup lease; skipping this run");
5980
+ return;
5981
+ }
5982
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
5983
+ await service.cleanupInactiveSessions({ useDbDirect });
5984
+ try {
5985
+ await coordinator.prune();
5986
+ } catch (err) {
5987
+ log.debug("[CLEANUP] Shared counter pruning failed:", err?.name || "Error");
5988
+ }
5989
+ };
5186
5990
  log.info("Running initial session cleanup...");
5187
5991
  try {
5188
5992
  const settings = await getPluginSettings(strapi2);
5189
- await sessionService.cleanupInactiveSessions({
5190
- useDbDirect: settings.cleanupUseDbDirect === true
5191
- });
5993
+ await runIdleCleanupIfLeader(
5994
+ Math.max(5 * 60 * 1e3, settings.cleanupInterval || 30 * 60 * 1e3),
5995
+ settings.cleanupUseDbDirect === true
5996
+ );
5192
5997
  } catch (cleanupErr) {
5193
5998
  log.warn("Initial cleanup failed:", cleanupErr?.name || "Error");
5194
5999
  }
@@ -5203,8 +6008,7 @@ var require_bootstrap = __commonJS({
5203
6008
  }
5204
6009
  const handle = setTimeout(async () => {
5205
6010
  try {
5206
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5207
- await service.cleanupInactiveSessions({ useDbDirect });
6011
+ await runIdleCleanupIfLeader(intervalMs, useDbDirect);
5208
6012
  } catch (err) {
5209
6013
  log.error("Periodic cleanup error:", err?.name || "Error");
5210
6014
  }
@@ -5213,7 +6017,6 @@ var require_bootstrap = __commonJS({
5213
6017
  strapi2.sessionManagerIntervals.cleanupTimeout = handle;
5214
6018
  };
5215
6019
  await scheduleIdleCleanup();
5216
- const RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5217
6020
  const scheduleRetention = async () => {
5218
6021
  let useDbDirect = false;
5219
6022
  try {
@@ -5223,8 +6026,7 @@ var require_bootstrap = __commonJS({
5223
6026
  }
5224
6027
  const handle = setTimeout(async () => {
5225
6028
  try {
5226
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5227
- await service.deleteOldSessions({ useDbDirect });
6029
+ await runRetentionIfLeader(useDbDirect);
5228
6030
  } catch (err) {
5229
6031
  log.error("Retention cleanup error:", err?.name || "Error");
5230
6032
  }
@@ -5232,8 +6034,23 @@ var require_bootstrap = __commonJS({
5232
6034
  }, RETENTION_INTERVAL_MS);
5233
6035
  strapi2.sessionManagerIntervals.retentionTimeout = handle;
5234
6036
  };
6037
+ const runRetentionIfLeader = async (useDbDirect) => {
6038
+ const leaseMs = RETENTION_INTERVAL_MS - 60 * 60 * 1e3;
6039
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.retention, leaseMs)) {
6040
+ log.debug("[RETENTION] Another instance holds the retention lease; skipping this run");
6041
+ return;
6042
+ }
6043
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
6044
+ await service.deleteOldSessions({ useDbDirect });
6045
+ };
5235
6046
  strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
5236
- () => {
6047
+ async () => {
6048
+ try {
6049
+ const settings = await getPluginSettings(strapi2);
6050
+ await runRetentionIfLeader(settings.cleanupUseDbDirect === true);
6051
+ } catch (err) {
6052
+ log.error("Retention cleanup error:", err?.name || "Error");
6053
+ }
5237
6054
  scheduleRetention();
5238
6055
  },
5239
6056
  5 * 60 * 1e3
@@ -5263,6 +6080,24 @@ var require_bootstrap = __commonJS({
5263
6080
  log.error("[ERROR] Bootstrap error:", err?.name || "Error");
5264
6081
  }
5265
6082
  };
6083
+ async function checkEncryptionKeyConsistency(strapi2, log) {
6084
+ const coordinator = getCoordinator(strapi2);
6085
+ if (!coordinator.dialect) return;
6086
+ try {
6087
+ const current = getEncryptionKeyCheck();
6088
+ const stored = await coordinator.cacheGet("instance:encryption-key-check");
6089
+ if (stored && stored !== current) {
6090
+ log.error(
6091
+ "[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."
6092
+ );
6093
+ }
6094
+ if (stored !== current) {
6095
+ await coordinator.cacheSet("instance:encryption-key-check", current, Infinity);
6096
+ }
6097
+ } catch (err) {
6098
+ log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
6099
+ }
6100
+ }
5266
6101
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
5267
6102
  strapi2.server.use(async (ctx, next) => {
5268
6103
  if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
@@ -5472,31 +6307,9 @@ var require_bootstrap = __commonJS({
5472
6307
  }
5473
6308
  }
5474
6309
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
5475
- const WINDOW_MS = 15 * 60 * 1e3;
5476
- const failed = /* @__PURE__ */ new Map();
5477
- const prune = (now) => {
5478
- if (failed.size < 5e3) return;
5479
- for (const [k, v] of failed) {
5480
- if (v.blockedUntil < now && now - v.firstFailAt > WINDOW_MS) failed.delete(k);
5481
- }
5482
- };
5483
- const recordFailure = (ip, max) => {
5484
- const now = Date.now();
5485
- prune(now);
5486
- const entry = failed.get(ip) || { count: 0, firstFailAt: now, blockedUntil: 0 };
5487
- if (now - entry.firstFailAt > WINDOW_MS) {
5488
- entry.count = 0;
5489
- entry.firstFailAt = now;
5490
- entry.blockedUntil = 0;
5491
- }
5492
- entry.count += 1;
5493
- if (entry.count >= max) {
5494
- entry.blockedUntil = now + WINDOW_MS;
5495
- }
5496
- failed.set(ip, entry);
5497
- return entry;
5498
- };
5499
- const clearFailures = (ip) => failed.delete(ip);
6310
+ const WINDOW_MS = FAILED_LOGIN_WINDOW_MS;
6311
+ const coordinator = getCoordinator(strapi2);
6312
+ const keyFor = (ip) => hashedKey("lf", ip);
5500
6313
  strapi2.server.use(async (ctx, next) => {
5501
6314
  if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
5502
6315
  const settings = await getRequestSettings(strapi2, ctx);
@@ -5504,10 +6317,15 @@ var require_bootstrap = __commonJS({
5504
6317
  if (maxFailed <= 0) return next();
5505
6318
  const ip = getClientIp(ctx);
5506
6319
  if (!ip || ip === "unknown") return next();
6320
+ const key = keyFor(ip);
5507
6321
  const now = Date.now();
5508
- const existing = failed.get(ip);
5509
- if (existing && existing.blockedUntil > now) {
5510
- const retrySec = Math.ceil((existing.blockedUntil - now) / 1e3);
6322
+ let existing = null;
6323
+ try {
6324
+ existing = await coordinator.peek(key);
6325
+ } catch (err) {
6326
+ log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
6327
+ }
6328
+ const rejectLocked = (retrySec) => {
5511
6329
  ctx.set("Retry-After", String(retrySec));
5512
6330
  log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
5513
6331
  ctx.status = 429;
@@ -5519,20 +6337,80 @@ var require_bootstrap = __commonJS({
5519
6337
  details: { retryAfter: retrySec }
5520
6338
  }
5521
6339
  };
6340
+ };
6341
+ if (existing && existing.blockedUntil > now) {
6342
+ rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
5522
6343
  return;
5523
6344
  }
5524
- await next();
5525
- if (ctx.status === 200 && ctx.body && ctx.body.jwt) {
5526
- clearFailures(ip);
5527
- } else if (ctx.status >= 400 && ctx.status < 500 && ctx.status !== 429) {
5528
- const entry = recordFailure(ip, maxFailed);
5529
- if (entry.blockedUntil > now) {
5530
- log.warn(`[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`);
6345
+ let reserved = null;
6346
+ try {
6347
+ reserved = await coordinator.hit(key, WINDOW_MS);
6348
+ } catch (err) {
6349
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
6350
+ }
6351
+ if (reserved && reserved.hits > maxFailed) {
6352
+ try {
6353
+ await coordinator.release(key);
6354
+ } catch (err) {
6355
+ log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
6356
+ }
6357
+ ctx.set("Retry-After", "1");
6358
+ ctx.status = 429;
6359
+ ctx.body = {
6360
+ error: {
6361
+ status: 429,
6362
+ name: "TooManyRequestsError",
6363
+ message: "Too many login attempts at once. Please try again.",
6364
+ details: { retryAfter: 1 }
6365
+ }
6366
+ };
6367
+ return;
6368
+ }
6369
+ let thrown = null;
6370
+ try {
6371
+ await next();
6372
+ } catch (err) {
6373
+ thrown = err;
6374
+ }
6375
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
6376
+ try {
6377
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) {
6378
+ await coordinator.clear(key);
6379
+ } else if (status >= 400 && status < 500 && status !== 429) {
6380
+ if (reserved && reserved.hits >= maxFailed) {
6381
+ await coordinator.block(key, Date.now() + WINDOW_MS);
6382
+ log.warn(
6383
+ `[LOCKOUT] Client locked for 15min after ${reserved.hits} failed login attempts`
6384
+ );
6385
+ }
6386
+ } else if (reserved) {
6387
+ await coordinator.release(key);
5531
6388
  }
6389
+ } catch (err) {
6390
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
5532
6391
  }
6392
+ if (thrown) throw thrown;
5533
6393
  });
5534
6394
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
5535
6395
  }
6396
+ function statusOfThrownError(err) {
6397
+ const status = Number(err?.status ?? err?.statusCode);
6398
+ if (Number.isInteger(status) && status >= 400 && status < 600) return status;
6399
+ const byName = {
6400
+ UnauthorizedError: 401,
6401
+ ForbiddenError: 403,
6402
+ NotFoundError: 404,
6403
+ PayloadTooLargeError: 413,
6404
+ RateLimitError: 429,
6405
+ NotImplementedError: 501,
6406
+ ApplicationError: 400,
6407
+ ValidationError: 400,
6408
+ YupValidationError: 400,
6409
+ PaginationError: 400,
6410
+ PolicyError: 403
6411
+ };
6412
+ return byName[err?.name] || 500;
6413
+ }
5536
6414
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
5537
6415
  strapi2.server.use(async (ctx, next) => {
5538
6416
  const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
@@ -6011,77 +6889,112 @@ var require_bootstrap = __commonJS({
6011
6889
  }
6012
6890
  async function ensureContentApiPermissions(strapi2, log) {
6013
6891
  try {
6014
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
6015
- const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6016
- if (storedVersion === void 0) {
6017
- const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6018
- if (legacyFlag === true) {
6019
- await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6020
- }
6021
- }
6022
- const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6023
- if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6024
- log.debug("Content-API permissions already at current version (skipping auto-setup)");
6025
- return true;
6026
- }
6027
- const ROLE_UID = "plugin::users-permissions.role";
6028
- const PERMISSION_UID = "plugin::users-permissions.permission";
6029
- const roles = await strapi2.documents(ROLE_UID).findMany({
6030
- filters: { type: "authenticated" },
6031
- fields: ["id"],
6032
- limit: 1
6033
- });
6034
- const authenticatedRole = roles?.[0];
6035
- if (!authenticatedRole) {
6036
- log.warn("Authenticated role not found - skipping permission setup");
6892
+ return await withPluginStoreKey(
6893
+ strapi2,
6894
+ "contentApiPermissionsVersion",
6895
+ (pluginStore) => ensureContentApiPermissionsLocked(strapi2, log, pluginStore)
6896
+ );
6897
+ } catch (err) {
6898
+ if (err instanceof LockTimeoutError) {
6899
+ log.warn("Content-API permission setup is busy on another instance; will retry");
6037
6900
  return false;
6038
6901
  }
6039
- const requiredActions = [
6040
- "plugin::magic-sessionmanager.session.logout",
6041
- "plugin::magic-sessionmanager.session.logoutAll",
6042
- "plugin::magic-sessionmanager.session.logoutOthers",
6043
- "plugin::magic-sessionmanager.session.getOwnSessions",
6044
- "plugin::magic-sessionmanager.session.getUserSessions",
6045
- "plugin::magic-sessionmanager.session.getCurrentSession",
6046
- "plugin::magic-sessionmanager.session.terminateOwnSession"
6047
- ];
6048
- const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6049
- filters: {
6050
- role: authenticatedRole.id,
6051
- action: { $in: requiredActions }
6052
- },
6053
- fields: ["action"],
6054
- limit: requiredActions.length
6055
- });
6056
- const existingActions = existingPermissions.map((p) => p.action);
6057
- const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6058
- if (missingActions.length === 0) {
6059
- await pluginStore.set({
6060
- key: "contentApiPermissionsVersion",
6061
- value: CONTENT_API_PERMISSIONS_VERSION
6062
- });
6063
- log.debug("Content-API permissions already configured");
6064
- return true;
6065
- }
6066
- for (const action of missingActions) {
6067
- await strapi2.documents(PERMISSION_UID).create({
6068
- data: { action, role: authenticatedRole.id }
6069
- });
6070
- log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6902
+ log.warn("Could not auto-configure permissions:", err?.name || "Error");
6903
+ log.warn(
6904
+ "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6905
+ );
6906
+ return false;
6907
+ }
6908
+ }
6909
+ async function ensureContentApiPermissionsLocked(strapi2, log, pluginStore) {
6910
+ const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6911
+ if (storedVersion === void 0 || storedVersion === null) {
6912
+ const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6913
+ if (legacyFlag === true) {
6914
+ await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6071
6915
  }
6916
+ }
6917
+ const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6918
+ if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6919
+ log.debug("Content-API permissions already at current version (skipping auto-setup)");
6920
+ return true;
6921
+ }
6922
+ const ROLE_UID = "plugin::users-permissions.role";
6923
+ const PERMISSION_UID = "plugin::users-permissions.permission";
6924
+ const roles = await strapi2.documents(ROLE_UID).findMany({
6925
+ filters: { type: "authenticated" },
6926
+ fields: ["id"],
6927
+ limit: 1
6928
+ });
6929
+ const authenticatedRole = roles?.[0];
6930
+ if (!authenticatedRole) {
6931
+ log.info(
6932
+ "Authenticated role does not exist yet; permission setup runs again on the first Session Manager API request"
6933
+ );
6934
+ return false;
6935
+ }
6936
+ const requiredActions = [
6937
+ "plugin::magic-sessionmanager.session.logout",
6938
+ "plugin::magic-sessionmanager.session.logoutAll",
6939
+ "plugin::magic-sessionmanager.session.logoutOthers",
6940
+ "plugin::magic-sessionmanager.session.getOwnSessions",
6941
+ "plugin::magic-sessionmanager.session.getUserSessions",
6942
+ "plugin::magic-sessionmanager.session.getCurrentSession",
6943
+ "plugin::magic-sessionmanager.session.terminateOwnSession"
6944
+ ];
6945
+ const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6946
+ filters: {
6947
+ role: authenticatedRole.id,
6948
+ action: { $in: requiredActions }
6949
+ },
6950
+ fields: ["id", "documentId", "action"],
6951
+ sort: { id: "asc" },
6952
+ limit: requiredActions.length * 10
6953
+ });
6954
+ await removeDuplicatePermissions(strapi2, log, PERMISSION_UID, existingPermissions);
6955
+ const existingActions = existingPermissions.map((p) => p.action);
6956
+ const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6957
+ if (missingActions.length === 0) {
6072
6958
  await pluginStore.set({
6073
6959
  key: "contentApiPermissionsVersion",
6074
6960
  value: CONTENT_API_PERMISSIONS_VERSION
6075
6961
  });
6076
- log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6962
+ log.debug("Content-API permissions already configured");
6077
6963
  return true;
6078
- } catch (err) {
6079
- log.warn("Could not auto-configure permissions:", err?.name || "Error");
6080
- log.warn(
6081
- "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6082
- );
6083
- return false;
6084
6964
  }
6965
+ for (const action of missingActions) {
6966
+ await strapi2.documents(PERMISSION_UID).create({
6967
+ data: { action, role: authenticatedRole.id }
6968
+ });
6969
+ log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6970
+ }
6971
+ await pluginStore.set({
6972
+ key: "contentApiPermissionsVersion",
6973
+ value: CONTENT_API_PERMISSIONS_VERSION
6974
+ });
6975
+ log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6976
+ return true;
6977
+ }
6978
+ async function removeDuplicatePermissions(strapi2, log, permissionUid, permissions) {
6979
+ const seen = /* @__PURE__ */ new Set();
6980
+ let removed = 0;
6981
+ for (const permission of permissions || []) {
6982
+ if (!seen.has(permission.action)) {
6983
+ seen.add(permission.action);
6984
+ continue;
6985
+ }
6986
+ if (!permission.documentId) continue;
6987
+ try {
6988
+ await strapi2.documents(permissionUid).delete({ documentId: permission.documentId });
6989
+ removed++;
6990
+ } catch (err) {
6991
+ log.debug("[PERMISSION] Could not remove a duplicate permission:", err?.name || "Error");
6992
+ }
6993
+ }
6994
+ if (removed > 0) {
6995
+ log.warn(`[PERMISSION] Removed ${removed} duplicate Content-API permission row(s)`);
6996
+ }
6997
+ return removed;
6085
6998
  }
6086
6999
  function mountDeferredContentApiPermissionRetry({
6087
7000
  strapi: strapi2,
@@ -6124,44 +7037,10 @@ var require_bootstrap = __commonJS({
6124
7037
  }
6125
7038
  async function ensureSessionLookupIndexes(strapi2, log) {
6126
7039
  try {
6127
- const knex = strapi2.db.connection;
6128
- const tableName = "magic_sessions";
6129
- const definitions = [
6130
- { column: "token_hash", name: "idx_magic_sessions_token_hash" },
6131
- { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
6132
- ];
6133
- if (!await knex.schema.hasTable(tableName)) return;
6134
- for (const definition of definitions) {
6135
- const dialect = strapi2.db.dialect.client;
6136
- let hasIndex = false;
6137
- if (dialect === "postgres") {
6138
- const result = await knex.raw(
6139
- "SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
6140
- [tableName, definition.name]
6141
- );
6142
- hasIndex = result.rows.length > 0;
6143
- } else if (dialect === "mysql" || dialect === "mysql2") {
6144
- const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
6145
- tableName,
6146
- definition.name
6147
- ]);
6148
- hasIndex = result[0].length > 0;
6149
- } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
6150
- const result = await knex.raw(
6151
- "SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
6152
- [definition.name]
6153
- );
6154
- hasIndex = result.length > 0;
6155
- }
6156
- if (hasIndex) {
6157
- log.debug(`[INDEX] ${definition.name} already exists`);
6158
- continue;
6159
- }
6160
- await knex.schema.alterTable(tableName, (table) => {
6161
- table.index([definition.column, "is_active"], definition.name);
6162
- });
6163
- log.info(`[INDEX] Created ${definition.name}`);
6164
- }
7040
+ await getCoordinator(strapi2).withLock(
7041
+ "schema:session-indexes",
7042
+ () => createSessionLookupIndexes(strapi2, log)
7043
+ );
6165
7044
  } catch (err) {
6166
7045
  log.debug(
6167
7046
  "[INDEX] Could not create session lookup indexes (will retry on next startup):",
@@ -6169,6 +7048,54 @@ var require_bootstrap = __commonJS({
6169
7048
  );
6170
7049
  }
6171
7050
  }
7051
+ async function createSessionLookupIndexes(strapi2, log) {
7052
+ const knex = strapi2.db.connection;
7053
+ const tableName = "magic_sessions";
7054
+ const definitions = [
7055
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7056
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
7057
+ ];
7058
+ if (!await knex.schema.hasTable(tableName)) return;
7059
+ const dialect = strapi2.db.dialect.client;
7060
+ for (const definition of definitions) {
7061
+ if (dialect === "postgres" || dialect === "sqlite" || dialect === "better-sqlite3") {
7062
+ const exists = dialect === "postgres" ? (await knex.raw("SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
7063
+ tableName,
7064
+ definition.name
7065
+ ])).rows.length > 0 : (await knex.raw("SELECT name FROM sqlite_master WHERE type='index' AND name = ?", [
7066
+ definition.name
7067
+ ])).length > 0;
7068
+ if (exists) {
7069
+ log.debug(`[INDEX] ${definition.name} already exists`);
7070
+ continue;
7071
+ }
7072
+ await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7073
+ definition.name,
7074
+ tableName,
7075
+ definition.column,
7076
+ "is_active"
7077
+ ]);
7078
+ log.info(`[INDEX] Created ${definition.name}`);
7079
+ continue;
7080
+ }
7081
+ let hasIndex = false;
7082
+ if (dialect === "mysql" || dialect === "mysql2") {
7083
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
7084
+ tableName,
7085
+ definition.name
7086
+ ]);
7087
+ hasIndex = result[0].length > 0;
7088
+ }
7089
+ if (hasIndex) {
7090
+ log.debug(`[INDEX] ${definition.name} already exists`);
7091
+ continue;
7092
+ }
7093
+ await knex.schema.alterTable(tableName, (table) => {
7094
+ table.index([definition.column, "is_active"], definition.name);
7095
+ });
7096
+ log.info(`[INDEX] Created ${definition.name}`);
7097
+ }
7098
+ }
6172
7099
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
6173
7100
  var MAX_CONSECUTIVE_ERRORS = 10;
6174
7101
  var ERROR_RESET_INTERVAL = 60 * 1e3;
@@ -6351,8 +7278,8 @@ var require_bootstrap = __commonJS({
6351
7278
  strapi2.log.info(
6352
7279
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days`
6353
7280
  );
6354
- await strapi2.documents(SESSION_UID).update({
6355
- documentId: thisSession.documentId,
7281
+ await strapi2.db.query(SESSION_UID).updateMany({
7282
+ where: { documentId: thisSession.documentId, isActive: true },
6356
7283
  data: {
6357
7284
  isActive: false,
6358
7285
  terminatedManually: false,
@@ -6370,8 +7297,8 @@ var require_bootstrap = __commonJS({
6370
7297
  strapi2.log.info(
6371
7298
  `[magic-sessionmanager] [JWT-IDLE] Session too idle to reactivate (${Math.round(idleFor / 1e3)}s > ${inactivityTimeout / 1e3}s)`
6372
7299
  );
6373
- await strapi2.documents(SESSION_UID).update({
6374
- documentId: thisSession.documentId,
7300
+ await strapi2.db.query(SESSION_UID).updateMany({
7301
+ where: { documentId: thisSession.documentId, isActive: true },
6375
7302
  data: {
6376
7303
  isActive: false,
6377
7304
  terminatedManually: false,
@@ -6386,10 +7313,22 @@ var require_bootstrap = __commonJS({
6386
7313
  resetErrorCounter();
6387
7314
  return decoded;
6388
7315
  }
6389
- await strapi2.documents(SESSION_UID).update({
6390
- documentId: thisSession.documentId,
7316
+ const reactivated = await strapi2.db.query(SESSION_UID).updateMany({
7317
+ where: {
7318
+ documentId: thisSession.documentId,
7319
+ isActive: false,
7320
+ terminationReason: { $null: true },
7321
+ $or: [{ terminatedManually: false }, { terminatedManually: { $null: true } }]
7322
+ },
6391
7323
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
6392
7324
  });
7325
+ if (Number(reactivated?.count) !== 1) {
7326
+ strapi2.log.info(
7327
+ "[magic-sessionmanager] [JWT-REJECTED] Session was terminated concurrently"
7328
+ );
7329
+ setSessionRejectionReason(tokenHashValue, "manual");
7330
+ return null;
7331
+ }
6393
7332
  strapi2.log.info("[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated");
6394
7333
  resetErrorCounter();
6395
7334
  return decoded;
@@ -6455,6 +7394,8 @@ var require_bootstrap = __commonJS({
6455
7394
  }
6456
7395
  module2.exports.__private = {
6457
7396
  registerSessionAwareAuthStrategy,
7397
+ mountFailedLoginLockout,
7398
+ ensureSessionLookupIndexes,
6458
7399
  mountPreLoginGeoGuard,
6459
7400
  mountLoginInterceptor,
6460
7401
  mountRefreshTokenInterceptor,
@@ -6526,7 +7467,16 @@ var require_config = __commonJS({
6526
7467
  enableWebhooks: false,
6527
7468
  discordWebhookUrl: "",
6528
7469
  slackWebhookUrl: "",
6529
- trustedProxies: null
7470
+ trustedProxies: null,
7471
+ // Cross-process state for pm2 cluster / several replicas. `enabled:
7472
+ // false` keeps every counter, lease and cache per process (the pre-4.10
7473
+ // behaviour). `counterStore` may supply an object with async
7474
+ // hit/peek/block/clear methods (for example backed by Redis) for the
7475
+ // lockout and rate-limit counters; see README "Running several instances".
7476
+ coordination: {
7477
+ enabled: true,
7478
+ counterStore: null
7479
+ }
6530
7480
  },
6531
7481
  validator: (config2) => {
6532
7482
  if (config2.lastSeenRateLimit !== void 0 && typeof config2.lastSeenRateLimit !== "number") {
@@ -6556,6 +7506,24 @@ var require_config = __commonJS({
6556
7506
  if (config2.geoLookupFailureMode !== void 0 && !["auto", "allow", "block"].includes(config2.geoLookupFailureMode)) {
6557
7507
  throw new Error("geoLookupFailureMode must be one of: auto, allow, block");
6558
7508
  }
7509
+ if (config2.coordination !== void 0 && config2.coordination !== null) {
7510
+ const coordination = config2.coordination;
7511
+ if (typeof coordination !== "object" || Array.isArray(coordination)) {
7512
+ throw new Error("coordination must be an object");
7513
+ }
7514
+ if (coordination.enabled !== void 0 && typeof coordination.enabled !== "boolean") {
7515
+ throw new Error("coordination.enabled must be a boolean");
7516
+ }
7517
+ const store = coordination.counterStore;
7518
+ if (store !== void 0 && store !== null) {
7519
+ const required = ["hit", "peek", "block", "clear"];
7520
+ if (typeof store !== "object" || required.some((method) => typeof store[method] !== "function")) {
7521
+ throw new Error(
7522
+ "coordination.counterStore must implement async hit, peek, block and clear methods"
7523
+ );
7524
+ }
7525
+ }
7526
+ }
6559
7527
  }
6560
7528
  };
6561
7529
  }
@@ -6933,52 +7901,6 @@ var require_admin = __commonJS({
6933
7901
  description: "Get aggregate end-user counts only (admin)"
6934
7902
  }
6935
7903
  },
6936
- // ============================ LICENSE ============================
6937
- {
6938
- method: "GET",
6939
- path: "/license/status",
6940
- handler: "license.getStatus",
6941
- config: {
6942
- policies: adminPolicy(),
6943
- description: "Get license status (admin)"
6944
- }
6945
- },
6946
- {
6947
- method: "POST",
6948
- path: "/license/auto-create",
6949
- handler: "license.autoCreate",
6950
- config: {
6951
- policies: adminPolicy(),
6952
- description: "Auto-create license for current admin (admin)"
6953
- }
6954
- },
6955
- {
6956
- method: "POST",
6957
- path: "/license/create",
6958
- handler: "license.createAndActivate",
6959
- config: {
6960
- policies: adminPolicy(),
6961
- description: "Create and activate a new license (admin)"
6962
- }
6963
- },
6964
- {
6965
- method: "POST",
6966
- path: "/license/ping",
6967
- handler: "license.ping",
6968
- config: {
6969
- policies: adminPolicy(),
6970
- description: "Ping the license server (admin)"
6971
- }
6972
- },
6973
- {
6974
- method: "POST",
6975
- path: "/license/store-key",
6976
- handler: "license.storeKey",
6977
- config: {
6978
- policies: adminPolicy(),
6979
- description: "Store a license key (admin)"
6980
- }
6981
- },
6982
7904
  // ============================ GEOLOCATION ============================
6983
7905
  {
6984
7906
  method: "GET",
@@ -7409,6 +8331,7 @@ var require_session = __commonJS({
7409
8331
  var { parseNativeSessionKey } = require_native_session_view();
7410
8332
  var { runWithCallerRevocation } = require_block_revocation_scope();
7411
8333
  var { sendServerError } = require_http_errors();
8334
+ var { getCoordinator } = require_coordination();
7412
8335
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7413
8336
  var USER_UID = "plugin::users-permissions.user";
7414
8337
  var OWN_SESSIONS_LIMIT = 200;
@@ -8293,19 +9216,25 @@ var require_session = __commonJS({
8293
9216
  if (!userDocumentId) {
8294
9217
  return ctx.notFound("User not found");
8295
9218
  }
8296
- const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
8297
- if (!user) {
9219
+ const mode = hasRequestedState ? "explicit" : "toggle";
9220
+ const applyBlockedState = async () => {
9221
+ const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
9222
+ if (!user) return null;
9223
+ const nextBlocked = hasRequestedState ? requestedBlocked : !user.blocked;
9224
+ await runWithCallerRevocation(
9225
+ userDocumentId,
9226
+ () => strapi.documents(USER_UID).update({
9227
+ documentId: userDocumentId,
9228
+ data: { blocked: nextBlocked }
9229
+ })
9230
+ );
9231
+ return { blocked: nextBlocked };
9232
+ };
9233
+ const applied = mode === "toggle" ? await getCoordinator(strapi).withLock(`user-block:${userDocumentId}`, applyBlockedState) : await applyBlockedState();
9234
+ if (!applied) {
8298
9235
  return ctx.notFound("User not found");
8299
9236
  }
8300
- const mode = hasRequestedState ? "explicit" : "toggle";
8301
- const newBlockedStatus = hasRequestedState ? requestedBlocked : !user.blocked;
8302
- await runWithCallerRevocation(
8303
- userDocumentId,
8304
- () => strapi.documents(USER_UID).update({
8305
- documentId: userDocumentId,
8306
- data: { blocked: newBlockedStatus }
8307
- })
8308
- );
9237
+ const newBlockedStatus = applied.blocked;
8309
9238
  if (newBlockedStatus) {
8310
9239
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8311
9240
  await sessionService.terminateSession({ userId: userDocumentId, reason: "blocked" });
@@ -8325,182 +9254,6 @@ var require_session = __commonJS({
8325
9254
  }
8326
9255
  });
8327
9256
 
8328
- // server/src/controllers/license.js
8329
- var require_license = __commonJS({
8330
- "server/src/controllers/license.js"(exports2, module2) {
8331
- "use strict";
8332
- var { sendServerError } = require_http_errors();
8333
- var PROVIDER_UNREACHABLE_MESSAGE = "License server unreachable. The plugin keeps working without a key.";
8334
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
8335
- module2.exports = ({ strapi: strapi2 }) => ({
8336
- async getStatus(ctx) {
8337
- try {
8338
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8339
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
8340
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
8341
- if (!licenseKey) {
8342
- return ctx.send({
8343
- success: true,
8344
- valid: true,
8345
- demo: false,
8346
- hasKey: false,
8347
- data: {
8348
- features: {
8349
- premium: true,
8350
- advanced: true,
8351
- enterprise: true,
8352
- custom: true
8353
- }
8354
- },
8355
- message: "Plugin is active. License key activation is optional."
8356
- });
8357
- }
8358
- const license = await licenseGuard.getLicenseByKey(licenseKey);
8359
- return ctx.send({
8360
- success: true,
8361
- valid: true,
8362
- demo: false,
8363
- hasKey: true,
8364
- data: {
8365
- licenseKey,
8366
- email: license?.email || null,
8367
- firstName: license?.firstName || null,
8368
- lastName: license?.lastName || null,
8369
- isActive: license?.isActive ?? true,
8370
- isExpired: license?.isExpired ?? false,
8371
- isOnline: license?.isOnline ?? false,
8372
- expiresAt: license?.expiresAt || null,
8373
- lastPingAt: license?.lastPingAt || null,
8374
- deviceName: license?.deviceName || null,
8375
- deviceId: license?.deviceId || null,
8376
- ipAddress: license?.ipAddress || null,
8377
- features: {
8378
- premium: true,
8379
- advanced: true,
8380
- enterprise: true,
8381
- custom: true
8382
- },
8383
- maxDevices: license?.maxDevices || 1,
8384
- currentDevices: license?.currentDevices || 0
8385
- }
8386
- });
8387
- } catch (error) {
8388
- strapi2.log.error(
8389
- "[magic-sessionmanager] Error getting license status:",
8390
- error?.name || "Error"
8391
- );
8392
- return sendServerError(ctx, 500, "Error getting license status");
8393
- }
8394
- },
8395
- async autoCreate(ctx) {
8396
- try {
8397
- const adminUser = ctx.state.user;
8398
- if (!adminUser) {
8399
- return ctx.unauthorized("No admin user logged in");
8400
- }
8401
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8402
- const license = await licenseGuard.createLicense({
8403
- email: adminUser.email,
8404
- firstName: adminUser.firstname || "Admin",
8405
- lastName: adminUser.lastname || "User"
8406
- });
8407
- if (!license) {
8408
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
8409
- }
8410
- await licenseGuard.storeLicenseKey(license.licenseKey);
8411
- return ctx.send({
8412
- success: true,
8413
- message: "License automatically created and stored",
8414
- data: license
8415
- });
8416
- } catch (error) {
8417
- strapi2.log.error(
8418
- "[magic-sessionmanager] Error auto-creating license:",
8419
- error?.name || "Error"
8420
- );
8421
- return sendServerError(ctx, 500, "Error creating license");
8422
- }
8423
- },
8424
- async createAndActivate(ctx) {
8425
- try {
8426
- const { email, firstName, lastName } = ctx.request.body || {};
8427
- if (![email, firstName, lastName].every((value) => typeof value === "string" && value.trim())) {
8428
- return ctx.badRequest("Email, firstName, and lastName are required");
8429
- }
8430
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8431
- const license = await licenseGuard.createLicense({ email, firstName, lastName });
8432
- if (!license) {
8433
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
8434
- }
8435
- await licenseGuard.storeLicenseKey(license.licenseKey);
8436
- return ctx.send({
8437
- success: true,
8438
- message: "License created and stored successfully",
8439
- data: license
8440
- });
8441
- } catch (error) {
8442
- strapi2.log.error("[magic-sessionmanager] Error creating license:", error?.name || "Error");
8443
- return sendServerError(ctx, 500, "Error creating license");
8444
- }
8445
- },
8446
- async ping(ctx) {
8447
- try {
8448
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
8449
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
8450
- if (!licenseKey) {
8451
- return ctx.badRequest("No license key found");
8452
- }
8453
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8454
- const verification = await licenseGuard.verifyLicense(licenseKey);
8455
- return ctx.send({
8456
- success: true,
8457
- message: verification.valid ? "License refreshed successfully" : "License key could not be verified, but the plugin keeps working.",
8458
- data: verification.data
8459
- });
8460
- } catch (error) {
8461
- strapi2.log.error("[magic-sessionmanager] Error refreshing license:", error?.name || "Error");
8462
- return sendServerError(ctx, 500, "Error refreshing license");
8463
- }
8464
- },
8465
- async storeKey(ctx) {
8466
- try {
8467
- const { licenseKey, email } = ctx.request.body || {};
8468
- if (typeof licenseKey !== "string" || !licenseKey.trim()) {
8469
- return ctx.badRequest("License key is required");
8470
- }
8471
- if (email !== void 0 && email !== null && email !== "") {
8472
- if (typeof email !== "string" || !EMAIL_PATTERN.test(email.trim())) {
8473
- return ctx.badRequest("Email must be a valid email address");
8474
- }
8475
- }
8476
- const trimmedKey = licenseKey.trim();
8477
- const trimmedEmail = typeof email === "string" && email.trim() ? email.trim().toLowerCase() : null;
8478
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8479
- const verification = await licenseGuard.verifyLicense(trimmedKey);
8480
- if (!verification.valid && !verification.networkError) {
8481
- strapi2.log.warn("[magic-sessionmanager] Rejected an invalid license key");
8482
- return ctx.badRequest("Invalid or expired license key");
8483
- }
8484
- const license = verification.valid ? await licenseGuard.getLicenseByKey(trimmedKey) : null;
8485
- if (license?.email && trimmedEmail && license.email.toLowerCase() !== trimmedEmail) {
8486
- strapi2.log.warn("[magic-sessionmanager] Rejected a license holder email mismatch");
8487
- return ctx.badRequest("Email address does not match this license key");
8488
- }
8489
- await licenseGuard.storeLicenseKey(trimmedKey);
8490
- return ctx.send({
8491
- success: true,
8492
- message: verification.networkError ? "License key stored. The license server was unreachable, but the plugin keeps working." : "License key stored successfully",
8493
- data: verification.data || { licenseKey: trimmedKey, email: trimmedEmail }
8494
- });
8495
- } catch (error) {
8496
- strapi2.log.error("[magic-sessionmanager] Error storing license key:", error?.name || "Error");
8497
- return sendServerError(ctx, 500, "Error validating license key");
8498
- }
8499
- }
8500
- });
8501
- }
8502
- });
8503
-
8504
9257
  // scripts/geoip-updater.cjs
8505
9258
  var require_geoip_updater = __commonJS({
8506
9259
  "scripts/geoip-updater.cjs"(exports2, module2) {
@@ -8818,10 +9571,13 @@ var require_settings = __commonJS({
8818
9571
  "server/src/controllers/settings.js"(exports2, module2) {
8819
9572
  "use strict";
8820
9573
  var {
8821
- invalidateSettingsCache,
9574
+ getSettingsRevision,
8822
9575
  normalizeGeoIpProvider,
8823
- normalizeGeoLookupFailureMode
9576
+ normalizeGeoLookupFailureMode,
9577
+ notifySettingsChanged
8824
9578
  } = require_settings_loader();
9579
+ var { withPluginStoreKey } = require_plugin_store();
9580
+ var { LockTimeoutError } = require_coordination();
8825
9581
  var { resolveDatabaseTarget } = require_geoip_updater();
8826
9582
  var { sendServerError, sendValidationError } = require_http_errors();
8827
9583
  var path = require("node:path");
@@ -9209,6 +9965,26 @@ var require_settings = __commonJS({
9209
9965
  }
9210
9966
  return { settings, errors };
9211
9967
  }
9968
+ async function readRevision() {
9969
+ try {
9970
+ return await getSettingsRevision(strapi);
9971
+ } catch {
9972
+ return null;
9973
+ }
9974
+ }
9975
+ function sendSettingsConflict(ctx, currentRevision) {
9976
+ ctx.status = 409;
9977
+ ctx.body = {
9978
+ data: null,
9979
+ error: {
9980
+ status: 409,
9981
+ name: "ConflictError",
9982
+ message: "Settings were changed by another administrator. Reload and try again.",
9983
+ details: { revision: currentRevision }
9984
+ }
9985
+ };
9986
+ return ctx.body;
9987
+ }
9212
9988
  module2.exports = {
9213
9989
  /**
9214
9990
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -9225,8 +10001,10 @@ var require_settings = __commonJS({
9225
10001
  });
9226
10002
  const storedSettings = await pluginStore.get({ key: "settings" });
9227
10003
  const settings = mergeSettingsWithDefaults(storedSettings);
10004
+ const revision = await readRevision();
9228
10005
  ctx.send({
9229
10006
  settings,
10007
+ ...revision === null ? {} : { revision },
9230
10008
  success: true
9231
10009
  });
9232
10010
  } catch (error) {
@@ -9250,42 +10028,60 @@ var require_settings = __commonJS({
9250
10028
  * @returns {Promise<void>}
9251
10029
  */
9252
10030
  async updateSettings(ctx) {
9253
- let pluginStore;
9254
- let current;
9255
10031
  try {
9256
10032
  const { body } = ctx.request;
9257
10033
  if (!body || typeof body !== "object" || Array.isArray(body)) {
9258
10034
  return ctx.badRequest("Settings data must be an object");
9259
10035
  }
9260
- pluginStore = strapi.store({
9261
- type: "plugin",
9262
- name: "magic-sessionmanager"
9263
- });
9264
- const stored = await pluginStore.get({ key: "settings" });
9265
- const storedObject = stored && typeof stored === "object" ? stored : {};
9266
- current = {
9267
- ...mergeSettingsWithDefaults(storedObject),
9268
- geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
9269
- };
9270
- const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
9271
- if (errors.length > 0) {
9272
- return sendValidationError(ctx, "Invalid settings", errors);
10036
+ const hasBaseRevision = Object.prototype.hasOwnProperty.call(body, "revision");
10037
+ if (hasBaseRevision && !(Number.isInteger(body.revision) && body.revision >= 0)) {
10038
+ return sendValidationError(ctx, "Invalid settings", [
10039
+ { path: ["revision"], message: "revision must be a non-negative integer" }
10040
+ ]);
9273
10041
  }
9274
- await pluginStore.set({
9275
- key: "settings",
9276
- value: sanitizedSettings
10042
+ const outcome = await withPluginStoreKey(strapi, "settings", async (pluginStore) => {
10043
+ if (hasBaseRevision) {
10044
+ const currentRevision = await readRevision();
10045
+ if (currentRevision !== null && currentRevision !== body.revision) {
10046
+ return { conflict: true, currentRevision };
10047
+ }
10048
+ }
10049
+ const stored = await pluginStore.get({ key: "settings" });
10050
+ const storedObject = stored && typeof stored === "object" ? stored : {};
10051
+ const current = {
10052
+ ...mergeSettingsWithDefaults(storedObject),
10053
+ geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
10054
+ };
10055
+ const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
10056
+ if (errors.length > 0) return { errors };
10057
+ await pluginStore.set({
10058
+ key: "settings",
10059
+ value: sanitizedSettings
10060
+ });
10061
+ const revision = await notifySettingsChanged(strapi);
10062
+ return { settings: sanitizedSettings, revision };
9277
10063
  });
9278
- invalidateSettingsCache();
10064
+ if (outcome.conflict) {
10065
+ return sendSettingsConflict(ctx, outcome.currentRevision);
10066
+ }
10067
+ if (outcome.errors) {
10068
+ return sendValidationError(ctx, "Invalid settings", outcome.errors);
10069
+ }
9279
10070
  strapi.log.info("[magic-sessionmanager/settings] Settings updated successfully");
9280
10071
  ctx.send({
9281
10072
  settings: {
9282
- ...sanitizedSettings,
9283
- geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
10073
+ ...outcome.settings,
10074
+ geoIpDatabasePath: getSafeGeoIpFilename(outcome.settings.geoIpDatabasePath)
9284
10075
  },
10076
+ ...outcome.revision === null || outcome.revision === void 0 ? {} : { revision: outcome.revision },
9285
10077
  success: true,
9286
10078
  message: "Settings saved successfully!"
9287
10079
  });
9288
10080
  } catch (error) {
10081
+ if (error instanceof LockTimeoutError) {
10082
+ strapi.log.warn("[magic-sessionmanager/settings] Settings are being saved elsewhere");
10083
+ return sendServerError(ctx, 503, "Settings are being saved by another request");
10084
+ }
9289
10085
  strapi.log.error(
9290
10086
  "[magic-sessionmanager/settings] Error updating settings:",
9291
10087
  error?.name || "Error"
@@ -9320,6 +10116,8 @@ var require_geoip = __commonJS({
9320
10116
  normalizeGeoIpDatabasePath
9321
10117
  } = require_settings_loader();
9322
10118
  var { sendServerError } = require_http_errors();
10119
+ var { setPluginStoreValue } = require_plugin_store();
10120
+ var { getHostFingerprint } = require_coordination();
9323
10121
  var CREDENTIALS_KEY = "geoipCredentials";
9324
10122
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
9325
10123
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -9342,11 +10140,7 @@ var require_geoip = __commonJS({
9342
10140
  };
9343
10141
  }
9344
10142
  async function setStoredCredentials(strapi2, credentials) {
9345
- const store = getGeoIpStore(strapi2);
9346
- await store.set({
9347
- key: CREDENTIALS_KEY,
9348
- value: credentials
9349
- });
10143
+ await setPluginStoreValue(strapi2, CREDENTIALS_KEY, credentials);
9350
10144
  }
9351
10145
  function getCredentialSource(storedCredentials) {
9352
10146
  if (process.env.MAXMIND_ACCOUNT_ID && process.env.MAXMIND_LICENSE_KEY) {
@@ -9413,7 +10207,12 @@ var require_geoip = __commonJS({
9413
10207
  metadata,
9414
10208
  hasCredentials: credentialSource !== "missing",
9415
10209
  credentialSource,
9416
- accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || ""
10210
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
10211
+ // The MMDB file lives on the local disk of the instance that
10212
+ // answered. In multi-instance deployments each instance reports
10213
+ // its own file; `instance` is a non-reversible host fingerprint.
10214
+ scope: "instance",
10215
+ instance: getHostFingerprint()
9417
10216
  }
9418
10217
  });
9419
10218
  } catch (error) {
@@ -9512,12 +10311,10 @@ var require_controllers = __commonJS({
9512
10311
  "server/src/controllers/index.js"(exports2, module2) {
9513
10312
  "use strict";
9514
10313
  var session = require_session();
9515
- var license = require_license();
9516
10314
  var settings = require_settings();
9517
10315
  var geoip = require_geoip();
9518
10316
  module2.exports = {
9519
10317
  session,
9520
- license,
9521
10318
  settings,
9522
10319
  geoip
9523
10320
  };
@@ -9644,6 +10441,7 @@ var require_session2 = __commonJS({
9644
10441
  if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9645
10442
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9646
10443
  if (!revoked) {
10444
+ if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9647
10445
  throw new Error(
9648
10446
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9649
10447
  );
@@ -9674,7 +10472,10 @@ var require_session2 = __commonJS({
9674
10472
  }
9675
10473
  if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
9676
10474
  const revoked = await nativeManager.revokeSessionById(userId, parsed.nativeSessionId);
9677
- if (!revoked) throw new Error("Native session revocation was not confirmed.");
10475
+ if (!revoked) {
10476
+ if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
10477
+ throw new Error("Native session revocation was not confirmed.");
10478
+ }
9678
10479
  return true;
9679
10480
  }
9680
10481
  async function listNativeSessionsForUser(nativeManager, user, linkedIds = /* @__PURE__ */ new Set()) {
@@ -9811,6 +10612,7 @@ var require_session2 = __commonJS({
9811
10612
  if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9812
10613
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9813
10614
  if (!revoked) {
10615
+ if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9814
10616
  throw new Error(
9815
10617
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9816
10618
  );
@@ -10415,8 +11217,13 @@ var require_session2 = __commonJS({
10415
11217
  if (ts < cutoff) this._lastTouchCache.delete(k);
10416
11218
  }
10417
11219
  }
10418
- await strapi2.documents(SESSION_UID).update({
10419
- documentId: sessionDocId,
11220
+ const staleBefore = new Date(now.getTime() - rateLimit);
11221
+ await strapi2.db.query(SESSION_UID).updateMany({
11222
+ where: {
11223
+ documentId: sessionDocId,
11224
+ isActive: true,
11225
+ $or: [{ lastActive: { $lt: staleBefore } }, { lastActive: { $null: true } }]
11226
+ },
10420
11227
  data: { lastActive: now }
10421
11228
  });
10422
11229
  log.debug("[TOUCH] End-user session lastActive updated");
@@ -10506,9 +11313,24 @@ var require_session2 = __commonJS({
10506
11313
  let deactivatedCount = 0;
10507
11314
  for (const session of sessionsToDeactivate) {
10508
11315
  try {
10509
- if (nativeManager) await revokeNativeSessionForSidecar(nativeManager, session);
10510
- await strapi2.documents(SESSION_UID).update({
11316
+ const idleWhere = {
10511
11317
  documentId: session.documentId,
11318
+ isActive: true,
11319
+ $or: [
11320
+ { lastActive: { $lt: cutoffTime } },
11321
+ { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
11322
+ ]
11323
+ };
11324
+ if (nativeManager) {
11325
+ const stillIdle = await strapi2.documents(SESSION_UID).findFirst({
11326
+ filters: idleWhere,
11327
+ fields: ["documentId"]
11328
+ });
11329
+ if (!stillIdle) continue;
11330
+ await revokeNativeSessionForSidecar(nativeManager, session);
11331
+ }
11332
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
11333
+ where: idleWhere,
10512
11334
  data: {
10513
11335
  isActive: false,
10514
11336
  terminatedManually: false,
@@ -10516,7 +11338,7 @@ var require_session2 = __commonJS({
10516
11338
  logoutTime: now
10517
11339
  }
10518
11340
  });
10519
- deactivatedCount++;
11341
+ if (Number(result?.count) === 1) deactivatedCount++;
10520
11342
  } catch (err) {
10521
11343
  log.debug("[CLEANUP] Failed to deactivate an end-user session:", err?.name || "Error");
10522
11344
  }
@@ -10703,364 +11525,6 @@ var require_session2 = __commonJS({
10703
11525
  }
10704
11526
  });
10705
11527
 
10706
- // package.json
10707
- var require_package = __commonJS({
10708
- "package.json"(exports2, module2) {
10709
- module2.exports = {
10710
- version: "4.9.1",
10711
- keywords: [
10712
- "strapi",
10713
- "plugin",
10714
- "strapi-plugin",
10715
- "strapi-v5",
10716
- "sessions",
10717
- "user-tracking",
10718
- "login-logout",
10719
- "activity-monitoring"
10720
- ],
10721
- type: "commonjs",
10722
- bin: {
10723
- "strapi-magic-sessionmanager-geoip": "./scripts/update-geoip-db.mjs"
10724
- },
10725
- exports: {
10726
- "./package.json": "./package.json",
10727
- "./strapi-admin": {
10728
- source: "./admin/src/index.js",
10729
- import: "./dist/admin/index.mjs",
10730
- require: "./dist/admin/index.js",
10731
- default: "./dist/admin/index.js"
10732
- },
10733
- "./strapi-server": {
10734
- source: "./server/src/index.js",
10735
- import: "./dist/server/index.mjs",
10736
- require: "./dist/server/index.js",
10737
- default: "./dist/server/index.js"
10738
- }
10739
- },
10740
- files: [
10741
- "dist",
10742
- "strapi-admin.js",
10743
- "strapi-server.js",
10744
- "scripts/geoip-updater.cjs",
10745
- "scripts/update-geoip-db.mjs",
10746
- "README.md",
10747
- "LICENSE",
10748
- "CHANGELOG.md",
10749
- "pics"
10750
- ],
10751
- engines: {
10752
- node: "^22.22.2 || >=24.15.0",
10753
- npm: ">=6.0.0"
10754
- },
10755
- scripts: {
10756
- clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`,
10757
- test: "node --test tests/*.test.js tests/*.test.mjs",
10758
- "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
10759
- "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
10760
- lint: "eslint .",
10761
- "lint:fix": "eslint . --fix",
10762
- format: "prettier --write .",
10763
- "format:check": "prettier --check .",
10764
- build: "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
10765
- watch: "strapi-plugin watch",
10766
- "watch:link": "strapi-plugin watch:link",
10767
- "geoip:update": "node scripts/update-geoip-db.mjs",
10768
- verify: "strapi-plugin verify",
10769
- "verify:runtime": "node scripts/verify-server-bundle.mjs",
10770
- prepublishOnly: "npm test && npm run build && npm run verify && npm run verify:runtime"
10771
- },
10772
- dependencies: {
10773
- "@maxmind/geoip2-node": "^7.1.0",
10774
- "sanitize-html": "^2.18.0"
10775
- },
10776
- devDependencies: {
10777
- "@eslint/js": "^10.0.1",
10778
- "@semantic-release/changelog": "^7.0.0",
10779
- "@semantic-release/commit-analyzer": "^13.0.1",
10780
- "@semantic-release/git": "^11.0.1",
10781
- "@semantic-release/github": "^12.0.10",
10782
- "@semantic-release/npm": "^13.2.0",
10783
- "@semantic-release/release-notes-generator": "^14.1.1",
10784
- "@strapi/design-system": "^2.2.4",
10785
- "@strapi/icons": "^2.2.4",
10786
- "@strapi/sdk-plugin": "^6.1.1",
10787
- "@strapi/strapi": "5.61.0",
10788
- esbuild: "^0.28.2",
10789
- eslint: "^10.14.0",
10790
- "eslint-config-prettier": "^10.1.8",
10791
- "eslint-plugin-react-hooks": "^7.1.1",
10792
- globals: "^17.14.0",
10793
- prettier: "^3.9.10",
10794
- react: "^18.3.1",
10795
- "react-dom": "^18.3.1",
10796
- "react-intl": "^6.8.9",
10797
- "react-router-dom": "^6.30.6",
10798
- "semantic-release": "^25.0.9",
10799
- "styled-components": "^6.6.0"
10800
- },
10801
- peerDependencies: {
10802
- "@strapi/design-system": "^2.0.0",
10803
- "@strapi/icons": "^2.0.0",
10804
- "@strapi/strapi": "^5.0.0",
10805
- "@strapi/utils": "^5.0.0",
10806
- react: "^18.3.1",
10807
- "react-dom": "^18.3.1",
10808
- "react-intl": "^6.0.0",
10809
- "react-router-dom": "^6.0.0",
10810
- "styled-components": "^6.0.0"
10811
- },
10812
- publishConfig: {
10813
- access: "public"
10814
- },
10815
- strapi: {
10816
- kind: "plugin",
10817
- name: "magic-sessionmanager",
10818
- displayName: "Magic Sessionmanager",
10819
- description: "Advanced session management for Strapi v5 - Track user login/logout, session history, and online status"
10820
- },
10821
- name: "strapi-plugin-magic-sessionmanager",
10822
- description: "Advanced Session Management for Strapi v5 - Track user sessions with IP geolocation, security scoring, and real-time monitoring",
10823
- license: "MIT",
10824
- author: "Schero D.",
10825
- repository: {
10826
- type: "git",
10827
- url: "https://github.com/Schero94/Magic-Sessionmanager.git"
10828
- },
10829
- bugs: {
10830
- url: "https://github.com/Schero94/Magic-Sessionmanager/issues"
10831
- },
10832
- homepage: "https://github.com/Schero94/Magic-Sessionmanager#readme",
10833
- private: false
10834
- };
10835
- }
10836
- });
10837
-
10838
- // server/src/services/license-guard.js
10839
- var require_license_guard = __commonJS({
10840
- "server/src/services/license-guard.js"(exports2, module2) {
10841
- "use strict";
10842
- var crypto = require("crypto");
10843
- var os = require("os");
10844
- var pluginPkg = require_package();
10845
- var { createLogger } = require_logger();
10846
- var DEFAULT_LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
10847
- var envTimeout = Number(process.env.MAGIC_LICENSE_TIMEOUT_MS);
10848
- var DEFAULT_FETCH_TIMEOUT_MS = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 12e3;
10849
- var FETCH_RETRIES = 1;
10850
- var FETCH_RETRY_BACKOFF_MS = 750;
10851
- async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
10852
- let lastError;
10853
- for (let attempt = 0; attempt <= FETCH_RETRIES; attempt += 1) {
10854
- const controller = new AbortController();
10855
- const timer = setTimeout(() => controller.abort(), timeoutMs);
10856
- try {
10857
- return await fetch(url, { ...options, signal: controller.signal });
10858
- } catch (err) {
10859
- lastError = err;
10860
- if (attempt < FETCH_RETRIES) {
10861
- await new Promise((r) => setTimeout(r, FETCH_RETRY_BACKOFF_MS));
10862
- continue;
10863
- }
10864
- throw err;
10865
- } finally {
10866
- clearTimeout(timer);
10867
- }
10868
- }
10869
- throw lastError;
10870
- }
10871
- module2.exports = ({ strapi: strapi2 }) => {
10872
- const log = createLogger(strapi2);
10873
- return {
10874
- getLicenseServerUrl() {
10875
- return process.env.MAGIC_LICENSE_SERVER_URL || DEFAULT_LICENSE_SERVER_URL;
10876
- },
10877
- async generateDeviceId() {
10878
- try {
10879
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
10880
- const stored = await pluginStore.get({ key: "deviceId" });
10881
- if (stored && typeof stored === "string" && stored.length >= 16) {
10882
- return stored;
10883
- }
10884
- let identifier;
10885
- try {
10886
- const networkInterfaces = os.networkInterfaces();
10887
- const macAddresses = [];
10888
- Object.values(networkInterfaces).forEach((interfaces) => {
10889
- interfaces?.forEach((iface) => {
10890
- if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
10891
- macAddresses.push(iface.mac);
10892
- }
10893
- });
10894
- });
10895
- identifier = `${macAddresses.join("-")}-${os.hostname()}`;
10896
- } catch {
10897
- identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
10898
- }
10899
- const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
10900
- await pluginStore.set({ key: "deviceId", value: deviceId });
10901
- return deviceId;
10902
- } catch {
10903
- return crypto.randomBytes(16).toString("hex");
10904
- }
10905
- },
10906
- getDeviceName() {
10907
- try {
10908
- return os.hostname() || "Unknown Device";
10909
- } catch {
10910
- return "Unknown Device";
10911
- }
10912
- },
10913
- getIpAddress() {
10914
- try {
10915
- const networkInterfaces = os.networkInterfaces();
10916
- for (const name of Object.keys(networkInterfaces)) {
10917
- const interfaces = networkInterfaces[name];
10918
- if (!interfaces) continue;
10919
- for (const iface of interfaces) {
10920
- if (iface.family === "IPv4" && !iface.internal) {
10921
- return iface.address;
10922
- }
10923
- }
10924
- }
10925
- return "127.0.0.1";
10926
- } catch {
10927
- return "127.0.0.1";
10928
- }
10929
- },
10930
- getUserAgent() {
10931
- const pluginVersion = pluginPkg.version || "1.0.0";
10932
- const strapiVersion = strapi2.config.get("info.strapi") || "5.0.0";
10933
- return `MagicSessionManager/${pluginVersion} Strapi/${strapiVersion} Node/${process.version} ${os.platform()}/${os.release()}`;
10934
- },
10935
- async createLicense({ email, firstName, lastName }) {
10936
- try {
10937
- const response = await fetchWithTimeout(
10938
- `${this.getLicenseServerUrl()}/api/licenses/create`,
10939
- {
10940
- method: "POST",
10941
- headers: { "Content-Type": "application/json" },
10942
- body: JSON.stringify({
10943
- email,
10944
- firstName,
10945
- lastName,
10946
- deviceName: this.getDeviceName(),
10947
- deviceId: await this.generateDeviceId(),
10948
- ipAddress: this.getIpAddress(),
10949
- userAgent: this.getUserAgent(),
10950
- pluginName: "magic-sessionmanager",
10951
- productName: "Magic Session Manager"
10952
- })
10953
- }
10954
- );
10955
- const data = await response.json();
10956
- if (data.success) {
10957
- log.info("[SUCCESS] License created");
10958
- return data.data;
10959
- }
10960
- log.warn("[WARNING] License creation rejected by server");
10961
- return null;
10962
- } catch (error) {
10963
- log.warn("[WARNING] Error creating license:", error?.name || "Error");
10964
- return null;
10965
- }
10966
- },
10967
- async verifyLicense(licenseKey) {
10968
- try {
10969
- const response = await fetchWithTimeout(
10970
- `${this.getLicenseServerUrl()}/api/licenses/verify`,
10971
- {
10972
- method: "POST",
10973
- headers: { "Content-Type": "application/json" },
10974
- body: JSON.stringify({
10975
- licenseKey,
10976
- pluginName: "magic-sessionmanager",
10977
- productName: "Magic Session Manager"
10978
- })
10979
- }
10980
- );
10981
- const data = await response.json();
10982
- if (data.success && data.data) {
10983
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
10984
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
10985
- return { valid: true, data: data.data };
10986
- }
10987
- return { valid: false, data: null };
10988
- } catch (error) {
10989
- log.warn(
10990
- `[WARNING] License server unreachable during optional activation (${error?.name || "Error"}). This does not block the plugin.`
10991
- );
10992
- return { valid: false, data: null, networkError: true };
10993
- }
10994
- },
10995
- async getLicenseByKey(licenseKey) {
10996
- try {
10997
- const encodedKey = encodeURIComponent(licenseKey);
10998
- const response = await fetchWithTimeout(
10999
- `${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`,
11000
- {
11001
- method: "GET",
11002
- headers: { "Content-Type": "application/json" }
11003
- }
11004
- );
11005
- const data = await response.json();
11006
- if (data.success && data.data) return data.data;
11007
- return null;
11008
- } catch (error) {
11009
- log.warn("[WARNING] Could not fetch license by key:", error?.name || "Error");
11010
- return null;
11011
- }
11012
- },
11013
- async pingLicense() {
11014
- return null;
11015
- },
11016
- async storeLicenseKey(licenseKey) {
11017
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
11018
- await pluginStore.set({ key: "licenseKey", value: licenseKey });
11019
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
11020
- log.info("[SUCCESS] License key stored");
11021
- return true;
11022
- },
11023
- startPinging() {
11024
- return null;
11025
- },
11026
- async initialize() {
11027
- return { valid: true, demo: false, data: null };
11028
- },
11029
- cleanup() {
11030
- },
11031
- async hasFeature() {
11032
- return true;
11033
- },
11034
- async getMaxSessions() {
11035
- return -1;
11036
- },
11037
- async getLicenseTierInfo() {
11038
- try {
11039
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
11040
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
11041
- const hasKey = !!licenseKey;
11042
- return {
11043
- tier: hasKey ? "pro" : "free",
11044
- hasKey,
11045
- features: {
11046
- premium: true,
11047
- advanced: true,
11048
- enterprise: true
11049
- }
11050
- };
11051
- } catch {
11052
- return {
11053
- tier: "free",
11054
- hasKey: false,
11055
- features: { premium: true, advanced: true, enterprise: true }
11056
- };
11057
- }
11058
- }
11059
- };
11060
- };
11061
- }
11062
- });
11063
-
11064
11528
  // server/src/services/geolocation.js
11065
11529
  var require_geolocation = __commonJS({
11066
11530
  "server/src/services/geolocation.js"(exports2, module2) {
@@ -11069,6 +11533,7 @@ var require_geolocation = __commonJS({
11069
11533
  var net = require("node:net");
11070
11534
  var path = require("node:path");
11071
11535
  var { getPluginSettings } = require_settings_loader();
11536
+ var { getCoordinator, hashedKey } = require_coordination();
11072
11537
  var { resolveDatabaseTarget } = require_geoip_updater();
11073
11538
  var GEO_API_TIMEOUT_MS = 4e3;
11074
11539
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -11077,6 +11542,7 @@ var require_geolocation = __commonJS({
11077
11542
  var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
11078
11543
  var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
11079
11544
  var IPAPI_MAX_QUEUE_SIZE = 50;
11545
+ var SHARED_BACKOFF_KEY = "geo:ipapi:backoff";
11080
11546
  var DEFAULT_CITY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
11081
11547
  var DEFAULT_COUNTRY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-Country.mmdb");
11082
11548
  var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
@@ -11153,6 +11619,50 @@ var require_geolocation = __commonJS({
11153
11619
  expiresAt: Date.now() + ttlMs
11154
11620
  });
11155
11621
  }
11622
+ async function getSharedIpapiResult(strapiInstance, lookupIp) {
11623
+ try {
11624
+ const data = await getCoordinator(strapiInstance).cacheGet(hashedKey("geo:ipapi", lookupIp));
11625
+ return data && typeof data === "object" ? { ...data, ip: lookupIp } : null;
11626
+ } catch {
11627
+ return null;
11628
+ }
11629
+ }
11630
+ async function shareIpapiResult(strapiInstance, lookupIp, data, ttlMs) {
11631
+ if (!lookupIp || !data || ttlMs <= 0) return;
11632
+ try {
11633
+ const { ip: _ip, ...withoutIp } = data;
11634
+ await getCoordinator(strapiInstance).cacheSet(
11635
+ hashedKey("geo:ipapi", lookupIp),
11636
+ withoutIp,
11637
+ ttlMs
11638
+ );
11639
+ } catch {
11640
+ }
11641
+ }
11642
+ async function cacheIpapiResultEverywhere(strapiInstance, lookupIp, data, ttlMs) {
11643
+ cacheIpapiResult(lookupIp, data, ttlMs);
11644
+ await shareIpapiResult(strapiInstance, lookupIp, data, ttlMs);
11645
+ }
11646
+ async function syncSharedIpapiBackoff(strapiInstance) {
11647
+ try {
11648
+ const until = Number(await getCoordinator(strapiInstance).cacheGet(SHARED_BACKOFF_KEY));
11649
+ if (Number.isFinite(until) && until > ipapiRateLimitedUntil) ipapiRateLimitedUntil = until;
11650
+ } catch {
11651
+ }
11652
+ return getIpapiRateLimitRemainingMs();
11653
+ }
11654
+ async function shareIpapiBackoff(strapiInstance) {
11655
+ const remaining = getIpapiRateLimitRemainingMs();
11656
+ if (remaining <= 0) return;
11657
+ try {
11658
+ await getCoordinator(strapiInstance).cacheSet(
11659
+ SHARED_BACKOFF_KEY,
11660
+ ipapiRateLimitedUntil,
11661
+ remaining
11662
+ );
11663
+ } catch {
11664
+ }
11665
+ }
11156
11666
  function getRetryAfterMs(response) {
11157
11667
  const retryAfter = response?.headers?.get?.("retry-after");
11158
11668
  if (!retryAfter) return null;
@@ -11459,7 +11969,12 @@ var require_geolocation = __commonJS({
11459
11969
  }
11460
11970
  const cached = getCachedIpapiResult(lookupIp);
11461
11971
  if (cached) return cached;
11462
- const rateLimitRemainingMs = getIpapiRateLimitRemainingMs();
11972
+ const shared = await getSharedIpapiResult(strapi2, lookupIp);
11973
+ if (shared) {
11974
+ cacheIpapiResult(lookupIp, shared, IPAPI_FAILURE_CACHE_TTL_MS);
11975
+ return cloneGeoData(shared);
11976
+ }
11977
+ const rateLimitRemainingMs = await syncSharedIpapiBackoff(strapi2);
11463
11978
  if (rateLimitRemainingMs > 0) {
11464
11979
  logIpapiRateLimit(
11465
11980
  strapi2,
@@ -11484,7 +11999,7 @@ var require_geolocation = __commonJS({
11484
11999
  "ipapi",
11485
12000
  "Remote GeoIP provider concurrency limit reached"
11486
12001
  );
11487
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12002
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11488
12003
  return fallback;
11489
12004
  }
11490
12005
  const queuedRateLimitRemainingMs = getIpapiRateLimitRemainingMs();
@@ -11513,6 +12028,7 @@ var require_geolocation = __commonJS({
11513
12028
  const reason = response.status === 429 ? "rate_limited" : "error";
11514
12029
  if (response.status === 429) {
11515
12030
  const backoffMs = markIpapiRateLimited(response);
12031
+ await shareIpapiBackoff(strapi2);
11516
12032
  logIpapiRateLimit(
11517
12033
  strapi2,
11518
12034
  `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11528,7 +12044,7 @@ var require_geolocation = __commonJS({
11528
12044
  "ipapi",
11529
12045
  `HTTP ${response.status}`
11530
12046
  );
11531
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12047
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11532
12048
  return fallback;
11533
12049
  }
11534
12050
  const data = await response.json();
@@ -11536,6 +12052,7 @@ var require_geolocation = __commonJS({
11536
12052
  const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
11537
12053
  if (reason === "rate_limited") {
11538
12054
  const backoffMs = markIpapiRateLimited();
12055
+ await shareIpapiBackoff(strapi2);
11539
12056
  logIpapiRateLimit(
11540
12057
  strapi2,
11541
12058
  `[magic-sessionmanager/geolocation] API reported rate limit; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11544,7 +12061,7 @@ var require_geolocation = __commonJS({
11544
12061
  strapi2.log.warn("[magic-sessionmanager/geolocation] Provider rejected the lookup");
11545
12062
  }
11546
12063
  const fallback = this.getFallbackData(lookupIp, reason, "ipapi", data.reason);
11547
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12064
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11548
12065
  return fallback;
11549
12066
  }
11550
12067
  const result = {
@@ -11581,7 +12098,7 @@ var require_geolocation = __commonJS({
11581
12098
  _source: "ipapi"
11582
12099
  };
11583
12100
  strapi2.log.debug("[magic-sessionmanager/geolocation] ipapi lookup completed");
11584
- cacheIpapiResult(lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
12101
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
11585
12102
  return result;
11586
12103
  } catch (error) {
11587
12104
  const status = error?.name === "AbortError" ? "error" : "error";
@@ -11590,7 +12107,7 @@ var require_geolocation = __commonJS({
11590
12107
  error?.name || "Error"
11591
12108
  );
11592
12109
  const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
11593
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12110
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11594
12111
  return fallback;
11595
12112
  } finally {
11596
12113
  clearTimeout(timer);
@@ -12160,12 +12677,10 @@ var require_services = __commonJS({
12160
12677
  "server/src/services/index.js"(exports2, module2) {
12161
12678
  "use strict";
12162
12679
  var session = require_session2();
12163
- var licenseGuard = require_license_guard();
12164
12680
  var geolocation = require_geolocation();
12165
12681
  var notifications = require_notifications();
12166
12682
  module2.exports = {
12167
12683
  session,
12168
- "license-guard": licenseGuard,
12169
12684
  geolocation,
12170
12685
  notifications
12171
12686
  };
@@ -12177,12 +12692,7 @@ var require_rate_limit = __commonJS({
12177
12692
  "server/src/middlewares/rate-limit.js"(exports2, module2) {
12178
12693
  "use strict";
12179
12694
  var { getPluginSettings } = require_settings_loader();
12180
- var buckets = /* @__PURE__ */ new Map();
12181
- var prune = (now) => {
12182
- for (const [key, entry] of buckets) {
12183
- if (entry.expiresAt <= now) buckets.delete(key);
12184
- }
12185
- };
12695
+ var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
12186
12696
  var callerKey = (ctx) => {
12187
12697
  const userId = ctx.state?.user?.id;
12188
12698
  if (userId) return `u:${userId}`;
@@ -12202,15 +12712,7 @@ var require_rate_limit = __commonJS({
12202
12712
  const normalizedPath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") || "/" : rawPath;
12203
12713
  return `${method} path:${normalizedPath}`;
12204
12714
  };
12205
- var RESOLVED_TTL_MS = 3e4;
12206
- var resolvedCache = /* @__PURE__ */ new Map();
12207
12715
  async function resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) {
12208
- const now = Date.now();
12209
- const cacheKey = `${profile}:${routeMax}:${routeWindowMs}`;
12210
- const cachedEntry = resolvedCache.get(cacheKey);
12211
- if (cachedEntry && now - cachedEntry.at < RESOLVED_TTL_MS) {
12212
- return { max: cachedEntry.max, windowMs: cachedEntry.windowMs };
12213
- }
12214
12716
  let settings;
12215
12717
  try {
12216
12718
  settings = await getPluginSettings(strapi2);
@@ -12238,7 +12740,6 @@ var require_rate_limit = __commonJS({
12238
12740
  } else {
12239
12741
  resolved = { max: routeMax, windowMs: routeWindowMs };
12240
12742
  }
12241
- resolvedCache.set(cacheKey, { ...resolved, at: now });
12242
12743
  return resolved;
12243
12744
  }
12244
12745
  var rateLimit = (cfg = {}, { strapi: strapi2 }) => {
@@ -12247,17 +12748,12 @@ var require_rate_limit = __commonJS({
12247
12748
  const profile = cfg.profile === "read" || cfg.profile === "write" ? cfg.profile : null;
12248
12749
  return async (ctx, next) => {
12249
12750
  const { max, windowMs } = profile ? await resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) : { max: routeMax, windowMs: routeWindowMs };
12250
- const key = `${routeKey(ctx)}::${callerKey(ctx)}`;
12751
+ const key = hashedKey("rl", `${routeKey(ctx)}::${callerKey(ctx)}`);
12251
12752
  const now = Date.now();
12252
- if (buckets.size > 5e3) prune(now);
12253
- let entry = buckets.get(key);
12254
- if (!entry || entry.expiresAt <= now) {
12255
- entry = { count: 0, expiresAt: now + windowMs };
12256
- buckets.set(key, entry);
12257
- }
12258
- entry.count += 1;
12259
- if (entry.count > max) {
12260
- const retryAfterSec = Math.ceil((entry.expiresAt - now) / 1e3);
12753
+ const entry = await getCoordinator(strapi2).hit(key, windowMs);
12754
+ const expiresAt = entry.windowStart + windowMs;
12755
+ if (entry.hits > max) {
12756
+ const retryAfterSec = Math.max(1, Math.ceil((expiresAt - now) / 1e3));
12261
12757
  ctx.set("Retry-After", String(retryAfterSec));
12262
12758
  strapi2.log.warn("[magic-sessionmanager] Content API rate limit exceeded");
12263
12759
  ctx.status = 429;
@@ -12279,8 +12775,7 @@ var require_rate_limit = __commonJS({
12279
12775
  resolveLimits,
12280
12776
  routeKey,
12281
12777
  reset() {
12282
- buckets.clear();
12283
- resolvedCache.clear();
12778
+ __resetMemoryForTests();
12284
12779
  }
12285
12780
  };
12286
12781
  module2.exports = rateLimit;