strapi-plugin-magic-sessionmanager 4.9.0 → 4.10.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 (29) hide show
  1. package/CHANGELOG.md +54 -4
  2. package/README.md +195 -41
  3. package/dist/admin/{Analytics-B6d-39Qh.js → Analytics-CdmRsigN.js} +1 -1
  4. package/dist/admin/{Analytics-DxOWXHn8.mjs → Analytics-PRqsLMEx.mjs} +1 -1
  5. package/dist/admin/{App-ZsSGj7n8.mjs → App-BSeYF7KA.mjs} +2 -2
  6. package/dist/admin/{App-mRFV50K6.js → App-DUMCbuCr.js} +2 -2
  7. package/dist/admin/{License-DXt2oi6u.js → License-BeD7Du6r.js} +1 -1
  8. package/dist/admin/{License-BE6UQ_V3.mjs → License-D5W_l35e.mjs} +1 -1
  9. package/dist/admin/{OnlineUsersWidget-_tJ6aeWl.mjs → OnlineUsersWidget-B5pXzqM9.mjs} +2 -1
  10. package/dist/admin/{OnlineUsersWidget-CFvM3Vbp.js → OnlineUsersWidget-CDZ19_PT.js} +2 -1
  11. package/dist/admin/{Settings-dtW7cjTX.mjs → Settings-B-GRuWjT.mjs} +13 -3
  12. package/dist/admin/{Settings-BUc12TP5.js → Settings-CrLzRXrA.js} +13 -3
  13. package/dist/admin/{de-j0oZH9Pz.mjs → de-DwUCBY1b.mjs} +1 -0
  14. package/dist/admin/{de-BFKoGEVT.js → de-Dzo1tVoJ.js} +1 -0
  15. package/dist/admin/{en-s7Ksdkcg.js → en-CL5llI55.js} +1 -0
  16. package/dist/admin/{en-UY4Tb5tE.mjs → en-Dd0wXfgR.mjs} +1 -0
  17. package/dist/admin/{es-07OGMe_5.js → es-CiNDwv_f.js} +1 -0
  18. package/dist/admin/{es-DGBcZwQy.mjs → es-Cl5IwDA4.mjs} +1 -0
  19. package/dist/admin/{fr-ETj_2UBY.js → fr-DBOQ-UDm.js} +1 -0
  20. package/dist/admin/{fr-B6-DWhGO.mjs → fr-DhADj8Zs.mjs} +1 -0
  21. package/dist/admin/{index-C_SyRULc.mjs → index-CHACmZsg.mjs} +42 -32
  22. package/dist/admin/{index-D4kEnXSp.js → index-CaLVyCio.js} +26 -16
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-YMRLm9gx.mjs → pt-CT6VpDMM.mjs} +1 -0
  26. package/dist/admin/{pt-C7PwrQtV.js → pt-m73K1nJ0.js} +1 -0
  27. package/dist/server/index.js +1329 -268
  28. package/dist/server/index.mjs +1329 -268
  29. package/package.json +4 -1
@@ -85,24 +85,735 @@ var require_logger = __commonJS({
85
85
  }
86
86
  });
87
87
 
88
+ // server/src/utils/coordination.js
89
+ var require_coordination = __commonJS({
90
+ "server/src/utils/coordination.js"(exports, module) {
91
+ "use strict";
92
+ var { AsyncLocalStorage } = __require("node:async_hooks");
93
+ var crypto = __require("node:crypto");
94
+ var os = __require("node:os");
95
+ var heldLocks = new AsyncLocalStorage();
96
+ var TABLES = Object.freeze({
97
+ counters: "magic_sm_counters",
98
+ leases: "magic_sm_leases",
99
+ cache: "magic_sm_cache"
100
+ });
101
+ var PG_LOCK_NAMESPACE = 5067597;
102
+ var NEVER_EXPIRES = 8e15;
103
+ var MAX_KEY_LENGTH = 191;
104
+ var LEASE_SHRINK_MARGIN_MS = 6e4;
105
+ var COUNTER_COLUMNS = Object.freeze(["hits", "window_start", "blocked_until"]);
106
+ var instanceIdCache = null;
107
+ function getInstanceId() {
108
+ if (instanceIdCache) return instanceIdCache;
109
+ let host = "unknown";
110
+ try {
111
+ host = os.hostname() || "unknown";
112
+ } catch {
113
+ }
114
+ const hostHash = crypto.createHash("sha256").update(host).digest("hex").slice(0, 12);
115
+ instanceIdCache = `${hostHash}:${process.pid}:${crypto.randomBytes(4).toString("hex")}`;
116
+ return instanceIdCache;
117
+ }
118
+ function getHostFingerprint() {
119
+ return getInstanceId().split(":")[0];
120
+ }
121
+ function hashedKey(prefix, raw) {
122
+ const digest = crypto.createHash("sha256").update(String(raw)).digest("hex").slice(0, 48);
123
+ return `${prefix}:${digest}`;
124
+ }
125
+ function toNumber(value) {
126
+ if (value === null || value === void 0) return 0;
127
+ const n = Number(value);
128
+ return Number.isFinite(n) ? n : 0;
129
+ }
130
+ function assertKey(key) {
131
+ if (typeof key !== "string" || key.length === 0 || key.length > MAX_KEY_LENGTH) {
132
+ throw new TypeError("coordination key must be a non-empty string of at most 191 characters");
133
+ }
134
+ }
135
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
136
+ var LockTimeoutError = class extends Error {
137
+ constructor(name) {
138
+ super(`Timed out waiting for lock "${name}"`);
139
+ this.name = "LockTimeoutError";
140
+ }
141
+ };
142
+ function createMemoryBackend() {
143
+ const counters = /* @__PURE__ */ new Map();
144
+ const leases = /* @__PURE__ */ new Map();
145
+ const revisions = /* @__PURE__ */ new Map();
146
+ const lockTails = /* @__PURE__ */ new Map();
147
+ const pruneCounters = (now) => {
148
+ if (counters.size < 5e3) return;
149
+ for (const [k, v] of counters) {
150
+ if (v.expiresAt <= now && v.blockedUntil <= now) counters.delete(k);
151
+ }
152
+ };
153
+ return {
154
+ mode: "memory",
155
+ async hit(key, windowMs, now = Date.now()) {
156
+ pruneCounters(now);
157
+ let entry = counters.get(key);
158
+ if (!entry) {
159
+ entry = { hits: 0, windowStart: 0, blockedUntil: 0, expiresAt: 0 };
160
+ counters.set(key, entry);
161
+ }
162
+ if (entry.windowStart <= now - windowMs) {
163
+ entry.hits = 1;
164
+ entry.windowStart = now;
165
+ } else {
166
+ entry.hits += 1;
167
+ }
168
+ entry.expiresAt = Math.max(entry.expiresAt, now + windowMs);
169
+ return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
170
+ },
171
+ async peek(key) {
172
+ const entry = counters.get(key);
173
+ if (!entry) return null;
174
+ return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
175
+ },
176
+ async block(key, untilMs) {
177
+ const entry = counters.get(key) || {
178
+ hits: 0,
179
+ windowStart: 0,
180
+ blockedUntil: 0,
181
+ expiresAt: 0
182
+ };
183
+ if (entry.blockedUntil < untilMs) entry.blockedUntil = untilMs;
184
+ entry.expiresAt = Math.max(entry.expiresAt, untilMs);
185
+ counters.set(key, entry);
186
+ },
187
+ async clear(key) {
188
+ counters.delete(key);
189
+ },
190
+ async release(key) {
191
+ const entry = counters.get(key);
192
+ if (entry && entry.hits > 0) entry.hits -= 1;
193
+ },
194
+ async getRevision(name) {
195
+ return revisions.get(name) || 0;
196
+ },
197
+ async bumpRevision(name) {
198
+ const next = (revisions.get(name) || 0) + 1;
199
+ revisions.set(name, next);
200
+ return next;
201
+ },
202
+ async tryAcquireLease(name, ttlMs, owner, now = Date.now()) {
203
+ const lease = leases.get(name);
204
+ if (lease && lease.until > now && lease.owner !== owner && lease.until <= now + ttlMs + LEASE_SHRINK_MARGIN_MS) {
205
+ return false;
206
+ }
207
+ leases.set(name, { owner, until: now + ttlMs });
208
+ return true;
209
+ },
210
+ async releaseLease(name, owner) {
211
+ const lease = leases.get(name);
212
+ if (lease && lease.owner === owner) leases.delete(name);
213
+ },
214
+ async withLock(name, fn) {
215
+ const previous = lockTails.get(name) || Promise.resolve();
216
+ let release;
217
+ const current = new Promise((resolve) => {
218
+ release = resolve;
219
+ });
220
+ const tail = previous.then(() => current);
221
+ lockTails.set(name, tail);
222
+ await previous;
223
+ try {
224
+ return await fn();
225
+ } finally {
226
+ release();
227
+ if (lockTails.get(name) === tail) lockTails.delete(name);
228
+ }
229
+ },
230
+ // The shared cache is an L2 behind per-module L1 caches; in memory mode
231
+ // the L1 caches already cover the process, so this layer stays empty.
232
+ async cacheGet() {
233
+ return null;
234
+ },
235
+ async cacheSet() {
236
+ },
237
+ async prune(now = Date.now()) {
238
+ let removed = 0;
239
+ for (const [k, v] of counters) {
240
+ if (v.expiresAt <= now && v.blockedUntil <= now) {
241
+ counters.delete(k);
242
+ removed++;
243
+ }
244
+ }
245
+ return removed;
246
+ },
247
+ reset() {
248
+ counters.clear();
249
+ leases.clear();
250
+ revisions.clear();
251
+ lockTails.clear();
252
+ }
253
+ };
254
+ }
255
+ function normalizeDialect(client) {
256
+ const value = String(client || "").toLowerCase();
257
+ if (value === "postgres" || value === "pg" || value === "postgresql") return "postgres";
258
+ if (value === "mysql" || value === "mysql2" || value === "mariadb") return "mysql";
259
+ if (value === "sqlite" || value === "sqlite3" || value === "better-sqlite3") return "sqlite";
260
+ return "other";
261
+ }
262
+ async function ensureTables(knex) {
263
+ const definitions = [
264
+ [
265
+ TABLES.counters,
266
+ (table) => {
267
+ table.string("k", MAX_KEY_LENGTH).notNullable().primary();
268
+ table.integer("hits").notNullable().defaultTo(0);
269
+ table.bigInteger("window_start").notNullable().defaultTo(0);
270
+ table.bigInteger("blocked_until").notNullable().defaultTo(0);
271
+ table.bigInteger("expires_at").notNullable().defaultTo(0);
272
+ table.index(["expires_at"], "magic_sm_counters_expires_idx");
273
+ }
274
+ ],
275
+ [
276
+ TABLES.leases,
277
+ (table) => {
278
+ table.string("name", MAX_KEY_LENGTH).notNullable().primary();
279
+ table.string("owner", MAX_KEY_LENGTH).notNullable().defaultTo("");
280
+ table.bigInteger("lease_until").notNullable().defaultTo(0);
281
+ }
282
+ ],
283
+ [
284
+ TABLES.cache,
285
+ (table) => {
286
+ table.string("k", MAX_KEY_LENGTH).notNullable().primary();
287
+ table.text("v");
288
+ table.bigInteger("expires_at").notNullable().defaultTo(0);
289
+ table.index(["expires_at"], "magic_sm_cache_expires_idx");
290
+ }
291
+ ]
292
+ ];
293
+ for (const [name, build] of definitions) {
294
+ if (await knex.schema.hasTable(name)) continue;
295
+ try {
296
+ await knex.schema.createTable(name, build);
297
+ } catch (err) {
298
+ if (!await knex.schema.hasTable(name)) throw err;
299
+ }
300
+ }
301
+ }
302
+ function createDatabaseBackend({ knex, dialect }) {
303
+ const kind = normalizeDialect(dialect);
304
+ const readCounter = async (key) => {
305
+ const row = await knex(TABLES.counters).select("hits", "window_start", "blocked_until").where({ k: key }).first();
306
+ if (!row) return null;
307
+ return {
308
+ hits: toNumber(row.hits),
309
+ windowStart: toNumber(row.window_start),
310
+ blockedUntil: toNumber(row.blocked_until)
311
+ };
312
+ };
313
+ const ensureCounterRow = (key, expiresAt) => knex(TABLES.counters).insert({ k: key, hits: 0, window_start: 0, blocked_until: 0, expires_at: expiresAt }).onConflict("k").ignore();
314
+ const supportsReturning = kind === "postgres" || kind === "sqlite";
315
+ const toCounter = (row) => row ? {
316
+ hits: toNumber(row.hits),
317
+ windowStart: toNumber(row.window_start),
318
+ blockedUntil: toNumber(row.blocked_until)
319
+ } : null;
320
+ const updateCounterReturning = async (key, withReturning, withoutReturning) => {
321
+ if (supportsReturning) {
322
+ const rows = await withReturning(knex(TABLES.counters).where({ k: key }));
323
+ return Array.isArray(rows) && rows.length > 0 ? toCounter(rows[0]) : null;
324
+ }
325
+ return knex.transaction(async (trx) => {
326
+ if (toNumber(await withoutReturning(trx)) === 0) return null;
327
+ const row = await trx(TABLES.counters).select(...COUNTER_COLUMNS).where({ k: key }).forUpdate().first();
328
+ return toCounter(row);
329
+ });
330
+ };
331
+ const tryAcquireLease = async (name, ttlMs, owner, now = Date.now()) => {
332
+ await knex(TABLES.leases).insert({ name, owner: "", lease_until: 0 }).onConflict("name").ignore();
333
+ const changed = await knex(TABLES.leases).where({ name }).andWhere((qb) => {
334
+ qb.where("lease_until", "<=", now).orWhere("owner", owner).orWhere("lease_until", ">", now + ttlMs + LEASE_SHRINK_MARGIN_MS);
335
+ }).update({ owner, lease_until: now + ttlMs });
336
+ return toNumber(changed) === 1;
337
+ };
338
+ const releaseLease = async (name, owner) => {
339
+ await knex(TABLES.leases).where({ name, owner }).update({ lease_until: 0 });
340
+ };
341
+ return {
342
+ mode: "database",
343
+ dialect: kind,
344
+ /**
345
+ * Increments a fixed-window counter in one atomic UPDATE and returns the
346
+ * value written by THIS update. The CASE expressions only read
347
+ * `window_start`, which is assigned last, so the result is the same under
348
+ * MySQL's left-to-right SET evaluation and the all-old-values semantics
349
+ * of PostgreSQL and SQLite.
350
+ *
351
+ * Reading the row in a separate statement after the UPDATE would return
352
+ * the count after later concurrent increments as well, so under a burst
353
+ * most callers would see a number above the limit and be rejected
354
+ * (measured: 2 of 48 parallel requests allowed with a limit of 10).
355
+ * PostgreSQL and SQLite therefore use `UPDATE ... RETURNING` (knex
356
+ * `returning`, SQLite >= 3.35); other dialects run UPDATE and SELECT in
357
+ * one transaction, where the row lock taken by the UPDATE keeps other
358
+ * writers out until the read is done.
359
+ */
360
+ async hit(key, windowMs, now = Date.now()) {
361
+ const cutoff = now - windowMs;
362
+ const data = {
363
+ hits: knex.raw("CASE WHEN window_start <= ? THEN 1 ELSE hits + 1 END", [cutoff]),
364
+ expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
365
+ now + windowMs,
366
+ now + windowMs
367
+ ]),
368
+ window_start: knex.raw("CASE WHEN window_start <= ? THEN ? ELSE window_start END", [
369
+ cutoff,
370
+ now
371
+ ])
372
+ };
373
+ const update = () => updateCounterReturning(
374
+ key,
375
+ (qb) => qb.update(data, [...COUNTER_COLUMNS]),
376
+ (trx) => trx(TABLES.counters).where({ k: key }).update(data)
377
+ );
378
+ let row = await update();
379
+ if (!row) {
380
+ await ensureCounterRow(key, now + windowMs);
381
+ row = await update();
382
+ }
383
+ return row || await readCounter(key) || { hits: 1, windowStart: now, blockedUntil: 0 };
384
+ },
385
+ /**
386
+ * Gives back one attempt counted by `hit` (for example when the request
387
+ * ended with a server error and must not count as a failed login).
388
+ */
389
+ async release(key) {
390
+ await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
391
+ },
392
+ peek: readCounter,
393
+ async block(key, untilMs) {
394
+ await ensureCounterRow(key, untilMs);
395
+ await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
396
+ blocked_until: untilMs,
397
+ expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
398
+ untilMs,
399
+ untilMs
400
+ ])
401
+ });
402
+ },
403
+ async clear(key) {
404
+ await knex(TABLES.counters).where({ k: key }).del();
405
+ },
406
+ async getRevision(name) {
407
+ const row = await knex(TABLES.counters).select("hits").where({ k: `rev:${name}` }).first();
408
+ return row ? toNumber(row.hits) : 0;
409
+ },
410
+ async bumpRevision(name) {
411
+ const key = `rev:${name}`;
412
+ await ensureCounterRow(key, NEVER_EXPIRES);
413
+ const data = { hits: knex.raw("hits + 1"), expires_at: NEVER_EXPIRES };
414
+ const row = await updateCounterReturning(
415
+ key,
416
+ (qb) => qb.update(data, [...COUNTER_COLUMNS]),
417
+ (trx) => trx(TABLES.counters).where({ k: key }).update(data)
418
+ );
419
+ return row ? row.hits : this.getRevision(name);
420
+ },
421
+ tryAcquireLease,
422
+ releaseLease,
423
+ /**
424
+ * Runs `fn` while holding a cluster-wide named lock.
425
+ *
426
+ * PostgreSQL: a transaction-level advisory lock (`pg_advisory_xact_lock`)
427
+ * on a dedicated transaction; it is released when that transaction ends,
428
+ * also when the process dies. `fn` runs on other connections, so it must
429
+ * not depend on that transaction. Other dialects: a lease row, polled
430
+ * until it is free or `waitMs` elapses; the lease expires after `ttlMs`
431
+ * if the holder dies.
432
+ */
433
+ async withLock(name, fn, { waitMs = 15e3, ttlMs = 3e4, owner } = {}) {
434
+ if (kind === "postgres") {
435
+ const timeout = Math.max(1, Math.floor(waitMs));
436
+ return knex.transaction(async (trx) => {
437
+ try {
438
+ await trx.raw(`SET LOCAL lock_timeout = '${timeout}ms'`);
439
+ await trx.raw("SELECT pg_advisory_xact_lock(?, hashtext(?))", [
440
+ PG_LOCK_NAMESPACE,
441
+ name
442
+ ]);
443
+ } catch (err) {
444
+ if (err?.code === "55P03") throw new LockTimeoutError(name);
445
+ throw err;
446
+ }
447
+ return fn();
448
+ });
449
+ }
450
+ const leaseName = `lock:${name}`;
451
+ const deadline = Date.now() + waitMs;
452
+ let delay = 25;
453
+ while (!await tryAcquireLease(leaseName, ttlMs, owner)) {
454
+ if (Date.now() >= deadline) throw new LockTimeoutError(name);
455
+ await sleep(delay + Math.floor(Math.random() * delay));
456
+ delay = Math.min(delay * 2, 250);
457
+ }
458
+ try {
459
+ return await fn();
460
+ } finally {
461
+ await releaseLease(leaseName, owner).catch(() => {
462
+ });
463
+ }
464
+ },
465
+ async cacheGet(key, now = Date.now()) {
466
+ const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: key }).andWhere("expires_at", ">", now).first();
467
+ if (!row || row.v === null || row.v === void 0) return null;
468
+ try {
469
+ return JSON.parse(row.v);
470
+ } catch {
471
+ return null;
472
+ }
473
+ },
474
+ async cacheSet(key, value, ttlMs, now = Date.now()) {
475
+ const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
476
+ await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
477
+ },
478
+ async prune(now = Date.now()) {
479
+ const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
480
+ const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
481
+ return toNumber(counters) + toNumber(cache);
482
+ }
483
+ };
484
+ }
485
+ var sharedMemory = createMemoryBackend();
486
+ var coordinators = /* @__PURE__ */ new WeakMap();
487
+ function createCoordinator({
488
+ database = null,
489
+ counterStore = null,
490
+ log = null,
491
+ owner = getInstanceId()
492
+ } = {}) {
493
+ let db = database;
494
+ let lastFallbackLogAt = 0;
495
+ const reportFallback = (operation, err) => {
496
+ const now = Date.now();
497
+ if (now - lastFallbackLogAt < 6e4) return;
498
+ lastFallbackLogAt = now;
499
+ log?.warn?.(
500
+ `[COORDINATION] ${operation} failed on the shared store, using process-local state:`,
501
+ err?.name || "Error"
502
+ );
503
+ };
504
+ const run = async (operation, sharedCall, memoryCall) => {
505
+ if (!db) return memoryCall();
506
+ try {
507
+ return await sharedCall(db);
508
+ } catch (err) {
509
+ if (err instanceof LockTimeoutError) throw err;
510
+ reportFallback(operation, err);
511
+ return memoryCall();
512
+ }
513
+ };
514
+ const counterCall = async (operation, method, args) => {
515
+ if (counterStore && typeof counterStore[method] === "function") {
516
+ try {
517
+ return await counterStore[method](...args);
518
+ } catch (err) {
519
+ reportFallback(`${operation} (custom store)`, err);
520
+ }
521
+ }
522
+ return run(
523
+ operation,
524
+ (backend) => backend[method](...args),
525
+ () => sharedMemory[method](...args)
526
+ );
527
+ };
528
+ return {
529
+ owner,
530
+ get mode() {
531
+ if (counterStore) return db ? "custom+database" : "custom+memory";
532
+ return db ? "database" : "memory";
533
+ },
534
+ get dialect() {
535
+ return db?.dialect || null;
536
+ },
537
+ /** Switches the coordinator to the database backend. */
538
+ attachDatabase(backend) {
539
+ db = backend;
540
+ },
541
+ /** Switches the coordinator back to process-local state. */
542
+ detachDatabase() {
543
+ db = null;
544
+ },
545
+ /**
546
+ * Increments the fixed-window counter `key`.
547
+ * @returns {Promise<{hits: number, windowStart: number, blockedUntil: number}>}
548
+ */
549
+ hit(key, windowMs) {
550
+ assertKey(key);
551
+ return counterCall("counter increment", "hit", [key, windowMs]);
552
+ },
553
+ /** @returns {Promise<{hits: number, windowStart: number, blockedUntil: number}|null>} */
554
+ peek(key) {
555
+ assertKey(key);
556
+ return counterCall("counter read", "peek", [key]);
557
+ },
558
+ /** Raises the block deadline of `key` to `untilMs` (never lowers it). */
559
+ block(key, untilMs) {
560
+ assertKey(key);
561
+ return counterCall("counter block", "block", [key, untilMs]);
562
+ },
563
+ /** Removes counter `key`. */
564
+ clear(key) {
565
+ assertKey(key);
566
+ return counterCall("counter clear", "clear", [key]);
567
+ },
568
+ /**
569
+ * Gives back one hit of counter `key`. Optional for a custom
570
+ * `counterStore`: a store without `release` keeps the hit.
571
+ */
572
+ async release(key) {
573
+ assertKey(key);
574
+ if (counterStore && typeof counterStore.release !== "function") return;
575
+ return counterCall("counter release", "release", [key]);
576
+ },
577
+ getRevision(name) {
578
+ return run(
579
+ "revision read",
580
+ (backend) => backend.getRevision(name),
581
+ () => sharedMemory.getRevision(name)
582
+ );
583
+ },
584
+ bumpRevision(name) {
585
+ return run(
586
+ "revision bump",
587
+ (backend) => backend.bumpRevision(name),
588
+ () => sharedMemory.bumpRevision(name)
589
+ );
590
+ },
591
+ /**
592
+ * Takes the lease `name` for `ttlMs` unless another process holds an
593
+ * unexpired lease. Re-acquiring an own lease extends it.
594
+ * @returns {Promise<boolean>}
595
+ */
596
+ tryAcquireLease(name, ttlMs) {
597
+ return run(
598
+ "lease acquire",
599
+ (backend) => backend.tryAcquireLease(name, ttlMs, owner),
600
+ () => sharedMemory.tryAcquireLease(name, ttlMs, owner)
601
+ );
602
+ },
603
+ releaseLease(name) {
604
+ return run(
605
+ "lease release",
606
+ (backend) => backend.releaseLease(name, owner),
607
+ () => sharedMemory.releaseLease(name, owner)
608
+ );
609
+ },
610
+ /**
611
+ * Runs `fn` inside the cluster-wide critical section `name`. A process-
612
+ * local mutex is always taken first, so concurrent callers in one process
613
+ * do not compete for database connections.
614
+ *
615
+ * @template T
616
+ * @param {string} name
617
+ * @param {() => Promise<T>} fn
618
+ * @param {{waitMs?: number, ttlMs?: number}} [options]
619
+ * @returns {Promise<T>}
620
+ * @throws {LockTimeoutError} When the lock could not be taken in time
621
+ */
622
+ withLock(name, fn, options = {}) {
623
+ const held = heldLocks.getStore();
624
+ if (held && held.has(name)) return fn();
625
+ const inner = () => heldLocks.run(/* @__PURE__ */ new Set([...held || [], name]), fn);
626
+ return sharedMemory.withLock(`local:${name}`, async () => {
627
+ if (!db) return inner();
628
+ let entered = false;
629
+ try {
630
+ return await db.withLock(
631
+ name,
632
+ () => {
633
+ entered = true;
634
+ return inner();
635
+ },
636
+ { ...options, owner }
637
+ );
638
+ } catch (err) {
639
+ if (entered || err instanceof LockTimeoutError) throw err;
640
+ reportFallback("lock", err);
641
+ return inner();
642
+ }
643
+ });
644
+ },
645
+ cacheGet(key) {
646
+ assertKey(key);
647
+ return run(
648
+ "cache read",
649
+ (backend) => backend.cacheGet(key),
650
+ () => sharedMemory.cacheGet(key)
651
+ );
652
+ },
653
+ cacheSet(key, value, ttlMs) {
654
+ assertKey(key);
655
+ return run(
656
+ "cache write",
657
+ (backend) => backend.cacheSet(key, value, ttlMs),
658
+ () => sharedMemory.cacheSet(key, value, ttlMs)
659
+ );
660
+ },
661
+ prune() {
662
+ return run(
663
+ "prune",
664
+ (backend) => backend.prune(),
665
+ () => sharedMemory.prune()
666
+ );
667
+ }
668
+ };
669
+ }
670
+ function getCoordinator(strapi2) {
671
+ const key = strapi2 && typeof strapi2 === "object" ? strapi2 : sharedMemory;
672
+ let coordinator = coordinators.get(key);
673
+ if (!coordinator) {
674
+ const config = readCoordinationConfig(strapi2);
675
+ coordinator = createCoordinator({
676
+ counterStore: config.counterStore,
677
+ log: strapi2?.log || null
678
+ });
679
+ coordinators.set(key, coordinator);
680
+ }
681
+ return coordinator;
682
+ }
683
+ function readCoordinationConfig(strapi2) {
684
+ let raw;
685
+ try {
686
+ raw = strapi2?.config?.get?.("plugin::magic-sessionmanager.coordination") || null;
687
+ } catch {
688
+ raw = null;
689
+ }
690
+ const config = raw && typeof raw === "object" ? raw : {};
691
+ const counterStore = config.counterStore && typeof config.counterStore === "object" ? config.counterStore : null;
692
+ return { enabled: config.enabled !== false, counterStore };
693
+ }
694
+ async function initCoordination(strapi2, log = strapi2?.log) {
695
+ const coordinator = getCoordinator(strapi2);
696
+ const config = readCoordinationConfig(strapi2);
697
+ if (!config.enabled) {
698
+ log?.info?.("[COORDINATION] Disabled by config; using process-local state");
699
+ return coordinator;
700
+ }
701
+ const knex = strapi2?.db?.connection;
702
+ if (typeof knex !== "function" || !knex.schema) {
703
+ log?.warn?.("[COORDINATION] No database connection; using process-local state");
704
+ return coordinator;
705
+ }
706
+ try {
707
+ await ensureTables(knex);
708
+ coordinator.attachDatabase(
709
+ createDatabaseBackend({
710
+ knex,
711
+ dialect: strapi2.db?.dialect?.client || knex.client?.config?.client
712
+ })
713
+ );
714
+ log?.info?.(`[COORDINATION] Shared state enabled (${coordinator.mode})`);
715
+ } catch (err) {
716
+ log?.error?.(
717
+ "[COORDINATION] Could not prepare shared tables; using process-local state:",
718
+ err?.name || "Error"
719
+ );
720
+ }
721
+ return coordinator;
722
+ }
723
+ module.exports = {
724
+ TABLES,
725
+ LockTimeoutError,
726
+ createCoordinator,
727
+ createDatabaseBackend,
728
+ createMemoryBackend,
729
+ ensureTables,
730
+ getCoordinator,
731
+ getHostFingerprint,
732
+ getInstanceId,
733
+ hashedKey,
734
+ initCoordination,
735
+ normalizeDialect,
736
+ __resetMemoryForTests() {
737
+ sharedMemory.reset();
738
+ }
739
+ };
740
+ }
741
+ });
742
+
743
+ // server/src/utils/plugin-store.js
744
+ var require_plugin_store = __commonJS({
745
+ "server/src/utils/plugin-store.js"(exports, module) {
746
+ "use strict";
747
+ var { getCoordinator } = require_coordination();
748
+ var PLUGIN_ID = "magic-sessionmanager";
749
+ var CORE_STORE_UID = "strapi::core-store";
750
+ function coreStoreKey(key) {
751
+ return `plugin_${PLUGIN_ID}_${key}`;
752
+ }
753
+ async function collapseDuplicateStoreRows(strapi2, key) {
754
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
755
+ if (!query || typeof query.findMany !== "function") return 0;
756
+ const rows = await query.findMany({
757
+ where: { key: coreStoreKey(key), environment: null, tag: null },
758
+ select: ["id"],
759
+ orderBy: { id: "desc" }
760
+ });
761
+ if (!Array.isArray(rows) || rows.length < 2) return 0;
762
+ const extraIds = rows.slice(1).map((row) => row.id);
763
+ const result = await query.deleteMany({ where: { id: { $in: extraIds } } });
764
+ return Number(result?.count) || 0;
765
+ }
766
+ async function withPluginStoreKey(strapi2, key, fn) {
767
+ const store = strapi2.store({ type: "plugin", name: PLUGIN_ID });
768
+ return getCoordinator(strapi2).withLock(`store:${key}`, async () => {
769
+ try {
770
+ const removed = await collapseDuplicateStoreRows(strapi2, key);
771
+ if (removed > 0) {
772
+ strapi2.log?.warn?.(
773
+ `[magic-sessionmanager] [STORE] Removed ${removed} duplicate store row(s) for "${key}"`
774
+ );
775
+ }
776
+ } catch (err) {
777
+ strapi2.log?.debug?.(
778
+ "[magic-sessionmanager] [STORE] Duplicate check failed:",
779
+ err?.name || "Error"
780
+ );
781
+ }
782
+ return fn(store);
783
+ });
784
+ }
785
+ async function setPluginStoreValue(strapi2, key, value) {
786
+ await withPluginStoreKey(strapi2, key, (store) => store.set({ key, value }));
787
+ }
788
+ module.exports = {
789
+ PLUGIN_ID,
790
+ collapseDuplicateStoreRows,
791
+ coreStoreKey,
792
+ setPluginStoreValue,
793
+ withPluginStoreKey
794
+ };
795
+ }
796
+ });
797
+
88
798
  // server/src/utils/content-api-permissions.js
89
799
  var require_content_api_permissions = __commonJS({
90
800
  "server/src/utils/content-api-permissions.js"(exports, module) {
91
801
  "use strict";
802
+ var { withPluginStoreKey } = require_plugin_store();
92
803
  var CONTENT_API_PERMISSIONS_VERSION = 2;
93
- var MAGIC_SESSIONMANAGER_STORE = "magic-sessionmanager";
94
804
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
95
805
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
96
806
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
97
807
  if (role?.type !== "authenticated") return false;
98
- const pluginStore = strapi2.store({ type: "plugin", name: MAGIC_SESSIONMANAGER_STORE });
99
- const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
100
- if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
101
- await pluginStore.set({
102
- key: CONTENT_API_PERMISSIONS_VERSION_KEY,
103
- value: CONTENT_API_PERMISSIONS_VERSION
808
+ return withPluginStoreKey(strapi2, CONTENT_API_PERMISSIONS_VERSION_KEY, async (pluginStore) => {
809
+ const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
810
+ if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
811
+ await pluginStore.set({
812
+ key: CONTENT_API_PERMISSIONS_VERSION_KEY,
813
+ value: CONTENT_API_PERMISSIONS_VERSION
814
+ });
815
+ return true;
104
816
  });
105
- return true;
106
817
  }
107
818
  function createContentApiPermissionsLifecycle(strapi2) {
108
819
  return {
@@ -382,7 +1093,11 @@ var require_encryption = __commonJS({
382
1093
  if (!token) return null;
383
1094
  return crypto.createHash("sha256").update(token).digest("hex");
384
1095
  }
1096
+ function getEncryptionKeyCheck() {
1097
+ return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
1098
+ }
385
1099
  module.exports = {
1100
+ getEncryptionKeyCheck,
386
1101
  encryptToken,
387
1102
  decryptToken,
388
1103
  generateSessionId,
@@ -441,13 +1156,18 @@ var require_resolve_user = __commonJS({
441
1156
  var require_settings_loader = __commonJS({
442
1157
  "server/src/utils/settings-loader.js"(exports, module) {
443
1158
  "use strict";
1159
+ var { getCoordinator } = require_coordination();
444
1160
  var PLUGIN_ID = "magic-sessionmanager";
445
1161
  var SETTINGS_KEY = "settings";
446
1162
  var CACHE_TTL_MS = 30 * 1e3;
1163
+ var REVISION_CHECK_MS = 2 * 1e3;
1164
+ var SETTINGS_REVISION = "settings";
447
1165
  var GEO_IP_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
448
1166
  var GEO_LOOKUP_FAILURE_MODES = /* @__PURE__ */ new Set(["auto", "allow", "block"]);
449
1167
  var cached = null;
450
1168
  var cachedAt = 0;
1169
+ var cachedRevision = null;
1170
+ var revisionCheckedAt = 0;
451
1171
  function toIntInRange(value, fallback, min, max) {
452
1172
  const n = Number.parseInt(value, 10);
453
1173
  if (!Number.isFinite(n)) return fallback;
@@ -561,8 +1281,23 @@ var require_settings_loader = __commonJS({
561
1281
  }
562
1282
  async function getPluginSettings(strapi2) {
563
1283
  const now = Date.now();
1284
+ const coordinator = getCoordinator(strapi2);
564
1285
  if (cached && now - cachedAt < CACHE_TTL_MS) {
565
- return cached;
1286
+ if (now - revisionCheckedAt < REVISION_CHECK_MS) return cached;
1287
+ revisionCheckedAt = now;
1288
+ let revision2;
1289
+ try {
1290
+ revision2 = await coordinator.getRevision(SETTINGS_REVISION);
1291
+ } catch {
1292
+ return cached;
1293
+ }
1294
+ if (revision2 === cachedRevision) return cached;
1295
+ }
1296
+ let revision;
1297
+ try {
1298
+ revision = await coordinator.getRevision(SETTINGS_REVISION);
1299
+ } catch {
1300
+ revision = null;
566
1301
  }
567
1302
  const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
568
1303
  let storedSettings;
@@ -579,6 +1314,8 @@ var require_settings_loader = __commonJS({
579
1314
  const merged = { ...staticConfig, ...storedSettings };
580
1315
  cached = merged;
581
1316
  cachedAt = now;
1317
+ cachedRevision = revision;
1318
+ revisionCheckedAt = now;
582
1319
  return merged;
583
1320
  }
584
1321
  function getPluginSettingsSync(strapi2) {
@@ -588,11 +1325,30 @@ var require_settings_loader = __commonJS({
588
1325
  function invalidateSettingsCache() {
589
1326
  cached = null;
590
1327
  cachedAt = 0;
1328
+ cachedRevision = null;
1329
+ revisionCheckedAt = 0;
1330
+ }
1331
+ async function getSettingsRevision(strapi2) {
1332
+ return getCoordinator(strapi2).getRevision(SETTINGS_REVISION);
1333
+ }
1334
+ async function notifySettingsChanged(strapi2) {
1335
+ invalidateSettingsCache();
1336
+ try {
1337
+ return await getCoordinator(strapi2).bumpRevision(SETTINGS_REVISION);
1338
+ } catch (err) {
1339
+ strapi2?.log?.warn?.(
1340
+ `[${PLUGIN_ID}] settings-loader: could not publish the settings revision:`,
1341
+ err?.name || "Error"
1342
+ );
1343
+ return null;
1344
+ }
591
1345
  }
592
1346
  module.exports = {
593
1347
  getPluginSettings,
594
1348
  getPluginSettingsSync,
595
1349
  invalidateSettingsCache,
1350
+ notifySettingsChanged,
1351
+ getSettingsRevision,
596
1352
  normalizeStoredSettings,
597
1353
  normalizeRetentionDays,
598
1354
  getSessionCreationGraceMs,
@@ -5133,7 +5889,7 @@ var require_bootstrap = __commonJS({
5133
5889
  "server/src/bootstrap.js"(exports, module) {
5134
5890
  "use strict";
5135
5891
  var getClientIp = require_getClientIp();
5136
- var { encryptToken, hashToken } = require_encryption();
5892
+ var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
5137
5893
  var { createLogger } = require_logger();
5138
5894
  var { resolveUserDocumentId } = require_resolve_user();
5139
5895
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -5143,6 +5899,13 @@ var require_bootstrap = __commonJS({
5143
5899
  var { REVOCATION_UID } = require_session_revocation();
5144
5900
  var { getNativeSessionManager } = require_native_session_manager();
5145
5901
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
5902
+ var {
5903
+ getCoordinator,
5904
+ hashedKey,
5905
+ initCoordination,
5906
+ LockTimeoutError
5907
+ } = require_coordination();
5908
+ var { withPluginStoreKey } = require_plugin_store();
5146
5909
  var {
5147
5910
  classifyJwtIssuingRequest,
5148
5911
  isFailedLoginTrackedPath,
@@ -5156,6 +5919,12 @@ var require_bootstrap = __commonJS({
5156
5919
  stripAuthTokensFromResponse
5157
5920
  } = require_refresh_token();
5158
5921
  var SESSION_UID = "plugin::magic-sessionmanager.session";
5922
+ var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
5923
+ var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5924
+ var JOB_LEASES = Object.freeze({
5925
+ idleCleanup: "job:idle-cleanup",
5926
+ retention: "job:retention"
5927
+ });
5159
5928
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
5160
5929
  var deferredContentApiPermissionSetup = /* @__PURE__ */ new WeakMap();
5161
5930
  async function getRequestSettings(strapi2, ctx) {
@@ -5180,6 +5949,8 @@ var require_bootstrap = __commonJS({
5180
5949
  throw e;
5181
5950
  }
5182
5951
  try {
5952
+ const coordinator = await initCoordination(strapi2, log);
5953
+ await checkEncryptionKeyConsistency(strapi2, log);
5183
5954
  await ensureSessionLookupIndexes(strapi2, log);
5184
5955
  await registerSessionAwareAuthStrategy(strapi2);
5185
5956
  const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
@@ -5189,12 +5960,27 @@ var require_bootstrap = __commonJS({
5189
5960
  if (!strapi2.sessionManagerIntervals) {
5190
5961
  strapi2.sessionManagerIntervals = {};
5191
5962
  }
5963
+ const runIdleCleanupIfLeader = async (intervalMs, useDbDirect) => {
5964
+ const leaseMs = Math.max(60 * 1e3, intervalMs - 30 * 1e3);
5965
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.idleCleanup, leaseMs)) {
5966
+ log.debug("[CLEANUP] Another instance holds the cleanup lease; skipping this run");
5967
+ return;
5968
+ }
5969
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
5970
+ await service.cleanupInactiveSessions({ useDbDirect });
5971
+ try {
5972
+ await coordinator.prune();
5973
+ } catch (err) {
5974
+ log.debug("[CLEANUP] Shared counter pruning failed:", err?.name || "Error");
5975
+ }
5976
+ };
5192
5977
  log.info("Running initial session cleanup...");
5193
5978
  try {
5194
5979
  const settings = await getPluginSettings(strapi2);
5195
- await sessionService.cleanupInactiveSessions({
5196
- useDbDirect: settings.cleanupUseDbDirect === true
5197
- });
5980
+ await runIdleCleanupIfLeader(
5981
+ Math.max(5 * 60 * 1e3, settings.cleanupInterval || 30 * 60 * 1e3),
5982
+ settings.cleanupUseDbDirect === true
5983
+ );
5198
5984
  } catch (cleanupErr) {
5199
5985
  log.warn("Initial cleanup failed:", cleanupErr?.name || "Error");
5200
5986
  }
@@ -5209,8 +5995,7 @@ var require_bootstrap = __commonJS({
5209
5995
  }
5210
5996
  const handle = setTimeout(async () => {
5211
5997
  try {
5212
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5213
- await service.cleanupInactiveSessions({ useDbDirect });
5998
+ await runIdleCleanupIfLeader(intervalMs, useDbDirect);
5214
5999
  } catch (err) {
5215
6000
  log.error("Periodic cleanup error:", err?.name || "Error");
5216
6001
  }
@@ -5219,7 +6004,6 @@ var require_bootstrap = __commonJS({
5219
6004
  strapi2.sessionManagerIntervals.cleanupTimeout = handle;
5220
6005
  };
5221
6006
  await scheduleIdleCleanup();
5222
- const RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5223
6007
  const scheduleRetention = async () => {
5224
6008
  let useDbDirect = false;
5225
6009
  try {
@@ -5229,8 +6013,7 @@ var require_bootstrap = __commonJS({
5229
6013
  }
5230
6014
  const handle = setTimeout(async () => {
5231
6015
  try {
5232
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5233
- await service.deleteOldSessions({ useDbDirect });
6016
+ await runRetentionIfLeader(useDbDirect);
5234
6017
  } catch (err) {
5235
6018
  log.error("Retention cleanup error:", err?.name || "Error");
5236
6019
  }
@@ -5238,8 +6021,23 @@ var require_bootstrap = __commonJS({
5238
6021
  }, RETENTION_INTERVAL_MS);
5239
6022
  strapi2.sessionManagerIntervals.retentionTimeout = handle;
5240
6023
  };
6024
+ const runRetentionIfLeader = async (useDbDirect) => {
6025
+ const leaseMs = RETENTION_INTERVAL_MS - 60 * 60 * 1e3;
6026
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.retention, leaseMs)) {
6027
+ log.debug("[RETENTION] Another instance holds the retention lease; skipping this run");
6028
+ return;
6029
+ }
6030
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
6031
+ await service.deleteOldSessions({ useDbDirect });
6032
+ };
5241
6033
  strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
5242
- () => {
6034
+ async () => {
6035
+ try {
6036
+ const settings = await getPluginSettings(strapi2);
6037
+ await runRetentionIfLeader(settings.cleanupUseDbDirect === true);
6038
+ } catch (err) {
6039
+ log.error("Retention cleanup error:", err?.name || "Error");
6040
+ }
5243
6041
  scheduleRetention();
5244
6042
  },
5245
6043
  5 * 60 * 1e3
@@ -5269,6 +6067,24 @@ var require_bootstrap = __commonJS({
5269
6067
  log.error("[ERROR] Bootstrap error:", err?.name || "Error");
5270
6068
  }
5271
6069
  };
6070
+ async function checkEncryptionKeyConsistency(strapi2, log) {
6071
+ const coordinator = getCoordinator(strapi2);
6072
+ if (!coordinator.dialect) return;
6073
+ try {
6074
+ const current = getEncryptionKeyCheck();
6075
+ const stored = await coordinator.cacheGet("instance:encryption-key-check");
6076
+ if (stored && stored !== current) {
6077
+ log.error(
6078
+ "[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."
6079
+ );
6080
+ }
6081
+ if (stored !== current) {
6082
+ await coordinator.cacheSet("instance:encryption-key-check", current, Infinity);
6083
+ }
6084
+ } catch (err) {
6085
+ log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
6086
+ }
6087
+ }
5272
6088
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
5273
6089
  strapi2.server.use(async (ctx, next) => {
5274
6090
  if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
@@ -5478,31 +6294,9 @@ var require_bootstrap = __commonJS({
5478
6294
  }
5479
6295
  }
5480
6296
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
5481
- const WINDOW_MS = 15 * 60 * 1e3;
5482
- const failed = /* @__PURE__ */ new Map();
5483
- const prune = (now) => {
5484
- if (failed.size < 5e3) return;
5485
- for (const [k, v] of failed) {
5486
- if (v.blockedUntil < now && now - v.firstFailAt > WINDOW_MS) failed.delete(k);
5487
- }
5488
- };
5489
- const recordFailure = (ip, max) => {
5490
- const now = Date.now();
5491
- prune(now);
5492
- const entry = failed.get(ip) || { count: 0, firstFailAt: now, blockedUntil: 0 };
5493
- if (now - entry.firstFailAt > WINDOW_MS) {
5494
- entry.count = 0;
5495
- entry.firstFailAt = now;
5496
- entry.blockedUntil = 0;
5497
- }
5498
- entry.count += 1;
5499
- if (entry.count >= max) {
5500
- entry.blockedUntil = now + WINDOW_MS;
5501
- }
5502
- failed.set(ip, entry);
5503
- return entry;
5504
- };
5505
- const clearFailures = (ip) => failed.delete(ip);
6297
+ const WINDOW_MS = FAILED_LOGIN_WINDOW_MS;
6298
+ const coordinator = getCoordinator(strapi2);
6299
+ const keyFor = (ip) => hashedKey("lf", ip);
5506
6300
  strapi2.server.use(async (ctx, next) => {
5507
6301
  if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
5508
6302
  const settings = await getRequestSettings(strapi2, ctx);
@@ -5510,10 +6304,15 @@ var require_bootstrap = __commonJS({
5510
6304
  if (maxFailed <= 0) return next();
5511
6305
  const ip = getClientIp(ctx);
5512
6306
  if (!ip || ip === "unknown") return next();
6307
+ const key = keyFor(ip);
5513
6308
  const now = Date.now();
5514
- const existing = failed.get(ip);
5515
- if (existing && existing.blockedUntil > now) {
5516
- const retrySec = Math.ceil((existing.blockedUntil - now) / 1e3);
6309
+ let existing = null;
6310
+ try {
6311
+ existing = await coordinator.peek(key);
6312
+ } catch (err) {
6313
+ log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
6314
+ }
6315
+ const rejectLocked = (retrySec) => {
5517
6316
  ctx.set("Retry-After", String(retrySec));
5518
6317
  log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
5519
6318
  ctx.status = 429;
@@ -5525,20 +6324,80 @@ var require_bootstrap = __commonJS({
5525
6324
  details: { retryAfter: retrySec }
5526
6325
  }
5527
6326
  };
6327
+ };
6328
+ if (existing && existing.blockedUntil > now) {
6329
+ rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
5528
6330
  return;
5529
6331
  }
5530
- await next();
5531
- if (ctx.status === 200 && ctx.body && ctx.body.jwt) {
5532
- clearFailures(ip);
5533
- } else if (ctx.status >= 400 && ctx.status < 500 && ctx.status !== 429) {
5534
- const entry = recordFailure(ip, maxFailed);
5535
- if (entry.blockedUntil > now) {
5536
- log.warn(`[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`);
6332
+ let reserved = null;
6333
+ try {
6334
+ reserved = await coordinator.hit(key, WINDOW_MS);
6335
+ } catch (err) {
6336
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
6337
+ }
6338
+ if (reserved && reserved.hits > maxFailed) {
6339
+ try {
6340
+ await coordinator.release(key);
6341
+ } catch (err) {
6342
+ log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
5537
6343
  }
6344
+ ctx.set("Retry-After", "1");
6345
+ ctx.status = 429;
6346
+ ctx.body = {
6347
+ error: {
6348
+ status: 429,
6349
+ name: "TooManyRequestsError",
6350
+ message: "Too many login attempts at once. Please try again.",
6351
+ details: { retryAfter: 1 }
6352
+ }
6353
+ };
6354
+ return;
5538
6355
  }
6356
+ let thrown = null;
6357
+ try {
6358
+ await next();
6359
+ } catch (err) {
6360
+ thrown = err;
6361
+ }
6362
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
6363
+ try {
6364
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) {
6365
+ await coordinator.clear(key);
6366
+ } else if (status >= 400 && status < 500 && status !== 429) {
6367
+ if (reserved && reserved.hits >= maxFailed) {
6368
+ await coordinator.block(key, Date.now() + WINDOW_MS);
6369
+ log.warn(
6370
+ `[LOCKOUT] Client locked for 15min after ${reserved.hits} failed login attempts`
6371
+ );
6372
+ }
6373
+ } else if (reserved) {
6374
+ await coordinator.release(key);
6375
+ }
6376
+ } catch (err) {
6377
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
6378
+ }
6379
+ if (thrown) throw thrown;
5539
6380
  });
5540
6381
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
5541
6382
  }
6383
+ function statusOfThrownError(err) {
6384
+ const status = Number(err?.status ?? err?.statusCode);
6385
+ if (Number.isInteger(status) && status >= 400 && status < 600) return status;
6386
+ const byName = {
6387
+ UnauthorizedError: 401,
6388
+ ForbiddenError: 403,
6389
+ NotFoundError: 404,
6390
+ PayloadTooLargeError: 413,
6391
+ RateLimitError: 429,
6392
+ NotImplementedError: 501,
6393
+ ApplicationError: 400,
6394
+ ValidationError: 400,
6395
+ YupValidationError: 400,
6396
+ PaginationError: 400,
6397
+ PolicyError: 403
6398
+ };
6399
+ return byName[err?.name] || 500;
6400
+ }
5542
6401
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
5543
6402
  strapi2.server.use(async (ctx, next) => {
5544
6403
  const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
@@ -6017,77 +6876,110 @@ var require_bootstrap = __commonJS({
6017
6876
  }
6018
6877
  async function ensureContentApiPermissions(strapi2, log) {
6019
6878
  try {
6020
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
6021
- const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6022
- if (storedVersion === void 0) {
6023
- const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6024
- if (legacyFlag === true) {
6025
- await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6026
- }
6027
- }
6028
- const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6029
- if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6030
- log.debug("Content-API permissions already at current version (skipping auto-setup)");
6031
- return true;
6032
- }
6033
- const ROLE_UID = "plugin::users-permissions.role";
6034
- const PERMISSION_UID = "plugin::users-permissions.permission";
6035
- const roles = await strapi2.documents(ROLE_UID).findMany({
6036
- filters: { type: "authenticated" },
6037
- fields: ["id"],
6038
- limit: 1
6039
- });
6040
- const authenticatedRole = roles?.[0];
6041
- if (!authenticatedRole) {
6042
- log.warn("Authenticated role not found - skipping permission setup");
6879
+ return await withPluginStoreKey(
6880
+ strapi2,
6881
+ "contentApiPermissionsVersion",
6882
+ (pluginStore) => ensureContentApiPermissionsLocked(strapi2, log, pluginStore)
6883
+ );
6884
+ } catch (err) {
6885
+ if (err instanceof LockTimeoutError) {
6886
+ log.warn("Content-API permission setup is busy on another instance; will retry");
6043
6887
  return false;
6044
6888
  }
6045
- const requiredActions = [
6046
- "plugin::magic-sessionmanager.session.logout",
6047
- "plugin::magic-sessionmanager.session.logoutAll",
6048
- "plugin::magic-sessionmanager.session.logoutOthers",
6049
- "plugin::magic-sessionmanager.session.getOwnSessions",
6050
- "plugin::magic-sessionmanager.session.getUserSessions",
6051
- "plugin::magic-sessionmanager.session.getCurrentSession",
6052
- "plugin::magic-sessionmanager.session.terminateOwnSession"
6053
- ];
6054
- const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6055
- filters: {
6056
- role: authenticatedRole.id,
6057
- action: { $in: requiredActions }
6058
- },
6059
- fields: ["action"],
6060
- limit: requiredActions.length
6061
- });
6062
- const existingActions = existingPermissions.map((p) => p.action);
6063
- const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6064
- if (missingActions.length === 0) {
6065
- await pluginStore.set({
6066
- key: "contentApiPermissionsVersion",
6067
- value: CONTENT_API_PERMISSIONS_VERSION
6068
- });
6069
- log.debug("Content-API permissions already configured");
6070
- return true;
6071
- }
6072
- for (const action of missingActions) {
6073
- await strapi2.documents(PERMISSION_UID).create({
6074
- data: { action, role: authenticatedRole.id }
6075
- });
6076
- log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6889
+ log.warn("Could not auto-configure permissions:", err?.name || "Error");
6890
+ log.warn(
6891
+ "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6892
+ );
6893
+ return false;
6894
+ }
6895
+ }
6896
+ async function ensureContentApiPermissionsLocked(strapi2, log, pluginStore) {
6897
+ const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6898
+ if (storedVersion === void 0 || storedVersion === null) {
6899
+ const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6900
+ if (legacyFlag === true) {
6901
+ await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6077
6902
  }
6903
+ }
6904
+ const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6905
+ if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6906
+ log.debug("Content-API permissions already at current version (skipping auto-setup)");
6907
+ return true;
6908
+ }
6909
+ const ROLE_UID = "plugin::users-permissions.role";
6910
+ const PERMISSION_UID = "plugin::users-permissions.permission";
6911
+ const roles = await strapi2.documents(ROLE_UID).findMany({
6912
+ filters: { type: "authenticated" },
6913
+ fields: ["id"],
6914
+ limit: 1
6915
+ });
6916
+ const authenticatedRole = roles?.[0];
6917
+ if (!authenticatedRole) {
6918
+ log.warn("Authenticated role not found - skipping permission setup");
6919
+ return false;
6920
+ }
6921
+ const requiredActions = [
6922
+ "plugin::magic-sessionmanager.session.logout",
6923
+ "plugin::magic-sessionmanager.session.logoutAll",
6924
+ "plugin::magic-sessionmanager.session.logoutOthers",
6925
+ "plugin::magic-sessionmanager.session.getOwnSessions",
6926
+ "plugin::magic-sessionmanager.session.getUserSessions",
6927
+ "plugin::magic-sessionmanager.session.getCurrentSession",
6928
+ "plugin::magic-sessionmanager.session.terminateOwnSession"
6929
+ ];
6930
+ const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6931
+ filters: {
6932
+ role: authenticatedRole.id,
6933
+ action: { $in: requiredActions }
6934
+ },
6935
+ fields: ["id", "documentId", "action"],
6936
+ sort: { id: "asc" },
6937
+ limit: requiredActions.length * 10
6938
+ });
6939
+ await removeDuplicatePermissions(strapi2, log, PERMISSION_UID, existingPermissions);
6940
+ const existingActions = existingPermissions.map((p) => p.action);
6941
+ const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6942
+ if (missingActions.length === 0) {
6078
6943
  await pluginStore.set({
6079
6944
  key: "contentApiPermissionsVersion",
6080
6945
  value: CONTENT_API_PERMISSIONS_VERSION
6081
6946
  });
6082
- log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6947
+ log.debug("Content-API permissions already configured");
6083
6948
  return true;
6084
- } catch (err) {
6085
- log.warn("Could not auto-configure permissions:", err?.name || "Error");
6086
- log.warn(
6087
- "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6088
- );
6089
- return false;
6090
6949
  }
6950
+ for (const action of missingActions) {
6951
+ await strapi2.documents(PERMISSION_UID).create({
6952
+ data: { action, role: authenticatedRole.id }
6953
+ });
6954
+ log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6955
+ }
6956
+ await pluginStore.set({
6957
+ key: "contentApiPermissionsVersion",
6958
+ value: CONTENT_API_PERMISSIONS_VERSION
6959
+ });
6960
+ log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6961
+ return true;
6962
+ }
6963
+ async function removeDuplicatePermissions(strapi2, log, permissionUid, permissions) {
6964
+ const seen = /* @__PURE__ */ new Set();
6965
+ let removed = 0;
6966
+ for (const permission of permissions || []) {
6967
+ if (!seen.has(permission.action)) {
6968
+ seen.add(permission.action);
6969
+ continue;
6970
+ }
6971
+ if (!permission.documentId) continue;
6972
+ try {
6973
+ await strapi2.documents(permissionUid).delete({ documentId: permission.documentId });
6974
+ removed++;
6975
+ } catch (err) {
6976
+ log.debug("[PERMISSION] Could not remove a duplicate permission:", err?.name || "Error");
6977
+ }
6978
+ }
6979
+ if (removed > 0) {
6980
+ log.warn(`[PERMISSION] Removed ${removed} duplicate Content-API permission row(s)`);
6981
+ }
6982
+ return removed;
6091
6983
  }
6092
6984
  function mountDeferredContentApiPermissionRetry({
6093
6985
  strapi: strapi2,
@@ -6130,44 +7022,10 @@ var require_bootstrap = __commonJS({
6130
7022
  }
6131
7023
  async function ensureSessionLookupIndexes(strapi2, log) {
6132
7024
  try {
6133
- const knex = strapi2.db.connection;
6134
- const tableName = "magic_sessions";
6135
- const definitions = [
6136
- { column: "token_hash", name: "idx_magic_sessions_token_hash" },
6137
- { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
6138
- ];
6139
- if (!await knex.schema.hasTable(tableName)) return;
6140
- for (const definition of definitions) {
6141
- const dialect = strapi2.db.dialect.client;
6142
- let hasIndex = false;
6143
- if (dialect === "postgres") {
6144
- const result = await knex.raw(
6145
- "SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
6146
- [tableName, definition.name]
6147
- );
6148
- hasIndex = result.rows.length > 0;
6149
- } else if (dialect === "mysql" || dialect === "mysql2") {
6150
- const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
6151
- tableName,
6152
- definition.name
6153
- ]);
6154
- hasIndex = result[0].length > 0;
6155
- } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
6156
- const result = await knex.raw(
6157
- "SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
6158
- [definition.name]
6159
- );
6160
- hasIndex = result.length > 0;
6161
- }
6162
- if (hasIndex) {
6163
- log.debug(`[INDEX] ${definition.name} already exists`);
6164
- continue;
6165
- }
6166
- await knex.schema.alterTable(tableName, (table) => {
6167
- table.index([definition.column, "is_active"], definition.name);
6168
- });
6169
- log.info(`[INDEX] Created ${definition.name}`);
6170
- }
7025
+ await getCoordinator(strapi2).withLock(
7026
+ "schema:session-indexes",
7027
+ () => createSessionLookupIndexes(strapi2, log)
7028
+ );
6171
7029
  } catch (err) {
6172
7030
  log.debug(
6173
7031
  "[INDEX] Could not create session lookup indexes (will retry on next startup):",
@@ -6175,6 +7033,54 @@ var require_bootstrap = __commonJS({
6175
7033
  );
6176
7034
  }
6177
7035
  }
7036
+ async function createSessionLookupIndexes(strapi2, log) {
7037
+ const knex = strapi2.db.connection;
7038
+ const tableName = "magic_sessions";
7039
+ const definitions = [
7040
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7041
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
7042
+ ];
7043
+ if (!await knex.schema.hasTable(tableName)) return;
7044
+ const dialect = strapi2.db.dialect.client;
7045
+ for (const definition of definitions) {
7046
+ if (dialect === "postgres" || dialect === "sqlite" || dialect === "better-sqlite3") {
7047
+ const exists = dialect === "postgres" ? (await knex.raw("SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
7048
+ tableName,
7049
+ definition.name
7050
+ ])).rows.length > 0 : (await knex.raw("SELECT name FROM sqlite_master WHERE type='index' AND name = ?", [
7051
+ definition.name
7052
+ ])).length > 0;
7053
+ if (exists) {
7054
+ log.debug(`[INDEX] ${definition.name} already exists`);
7055
+ continue;
7056
+ }
7057
+ await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7058
+ definition.name,
7059
+ tableName,
7060
+ definition.column,
7061
+ "is_active"
7062
+ ]);
7063
+ log.info(`[INDEX] Created ${definition.name}`);
7064
+ continue;
7065
+ }
7066
+ let hasIndex = false;
7067
+ if (dialect === "mysql" || dialect === "mysql2") {
7068
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
7069
+ tableName,
7070
+ definition.name
7071
+ ]);
7072
+ hasIndex = result[0].length > 0;
7073
+ }
7074
+ if (hasIndex) {
7075
+ log.debug(`[INDEX] ${definition.name} already exists`);
7076
+ continue;
7077
+ }
7078
+ await knex.schema.alterTable(tableName, (table) => {
7079
+ table.index([definition.column, "is_active"], definition.name);
7080
+ });
7081
+ log.info(`[INDEX] Created ${definition.name}`);
7082
+ }
7083
+ }
6178
7084
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
6179
7085
  var MAX_CONSECUTIVE_ERRORS = 10;
6180
7086
  var ERROR_RESET_INTERVAL = 60 * 1e3;
@@ -6357,8 +7263,8 @@ var require_bootstrap = __commonJS({
6357
7263
  strapi2.log.info(
6358
7264
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days`
6359
7265
  );
6360
- await strapi2.documents(SESSION_UID).update({
6361
- documentId: thisSession.documentId,
7266
+ await strapi2.db.query(SESSION_UID).updateMany({
7267
+ where: { documentId: thisSession.documentId, isActive: true },
6362
7268
  data: {
6363
7269
  isActive: false,
6364
7270
  terminatedManually: false,
@@ -6376,8 +7282,8 @@ var require_bootstrap = __commonJS({
6376
7282
  strapi2.log.info(
6377
7283
  `[magic-sessionmanager] [JWT-IDLE] Session too idle to reactivate (${Math.round(idleFor / 1e3)}s > ${inactivityTimeout / 1e3}s)`
6378
7284
  );
6379
- await strapi2.documents(SESSION_UID).update({
6380
- documentId: thisSession.documentId,
7285
+ await strapi2.db.query(SESSION_UID).updateMany({
7286
+ where: { documentId: thisSession.documentId, isActive: true },
6381
7287
  data: {
6382
7288
  isActive: false,
6383
7289
  terminatedManually: false,
@@ -6392,10 +7298,22 @@ var require_bootstrap = __commonJS({
6392
7298
  resetErrorCounter();
6393
7299
  return decoded;
6394
7300
  }
6395
- await strapi2.documents(SESSION_UID).update({
6396
- documentId: thisSession.documentId,
7301
+ const reactivated = await strapi2.db.query(SESSION_UID).updateMany({
7302
+ where: {
7303
+ documentId: thisSession.documentId,
7304
+ isActive: false,
7305
+ terminationReason: { $null: true },
7306
+ $or: [{ terminatedManually: false }, { terminatedManually: { $null: true } }]
7307
+ },
6397
7308
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
6398
7309
  });
7310
+ if (Number(reactivated?.count) !== 1) {
7311
+ strapi2.log.info(
7312
+ "[magic-sessionmanager] [JWT-REJECTED] Session was terminated concurrently"
7313
+ );
7314
+ setSessionRejectionReason(tokenHashValue, "manual");
7315
+ return null;
7316
+ }
6399
7317
  strapi2.log.info("[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated");
6400
7318
  resetErrorCounter();
6401
7319
  return decoded;
@@ -6461,6 +7379,8 @@ var require_bootstrap = __commonJS({
6461
7379
  }
6462
7380
  module.exports.__private = {
6463
7381
  registerSessionAwareAuthStrategy,
7382
+ mountFailedLoginLockout,
7383
+ ensureSessionLookupIndexes,
6464
7384
  mountPreLoginGeoGuard,
6465
7385
  mountLoginInterceptor,
6466
7386
  mountRefreshTokenInterceptor,
@@ -6532,7 +7452,16 @@ var require_config = __commonJS({
6532
7452
  enableWebhooks: false,
6533
7453
  discordWebhookUrl: "",
6534
7454
  slackWebhookUrl: "",
6535
- trustedProxies: null
7455
+ trustedProxies: null,
7456
+ // Cross-process state for pm2 cluster / several replicas. `enabled:
7457
+ // false` keeps every counter, lease and cache per process (the pre-4.10
7458
+ // behaviour). `counterStore` may supply an object with async
7459
+ // hit/peek/block/clear methods (for example backed by Redis) for the
7460
+ // lockout and rate-limit counters; see README "Running several instances".
7461
+ coordination: {
7462
+ enabled: true,
7463
+ counterStore: null
7464
+ }
6536
7465
  },
6537
7466
  validator: (config) => {
6538
7467
  if (config.lastSeenRateLimit !== void 0 && typeof config.lastSeenRateLimit !== "number") {
@@ -6562,6 +7491,24 @@ var require_config = __commonJS({
6562
7491
  if (config.geoLookupFailureMode !== void 0 && !["auto", "allow", "block"].includes(config.geoLookupFailureMode)) {
6563
7492
  throw new Error("geoLookupFailureMode must be one of: auto, allow, block");
6564
7493
  }
7494
+ if (config.coordination !== void 0 && config.coordination !== null) {
7495
+ const coordination = config.coordination;
7496
+ if (typeof coordination !== "object" || Array.isArray(coordination)) {
7497
+ throw new Error("coordination must be an object");
7498
+ }
7499
+ if (coordination.enabled !== void 0 && typeof coordination.enabled !== "boolean") {
7500
+ throw new Error("coordination.enabled must be a boolean");
7501
+ }
7502
+ const store = coordination.counterStore;
7503
+ if (store !== void 0 && store !== null) {
7504
+ const required = ["hit", "peek", "block", "clear"];
7505
+ if (typeof store !== "object" || required.some((method) => typeof store[method] !== "function")) {
7506
+ throw new Error(
7507
+ "coordination.counterStore must implement async hit, peek, block and clear methods"
7508
+ );
7509
+ }
7510
+ }
7511
+ }
6565
7512
  }
6566
7513
  };
6567
7514
  }
@@ -7415,6 +8362,7 @@ var require_session = __commonJS({
7415
8362
  var { parseNativeSessionKey } = require_native_session_view();
7416
8363
  var { runWithCallerRevocation } = require_block_revocation_scope();
7417
8364
  var { sendServerError } = require_http_errors();
8365
+ var { getCoordinator } = require_coordination();
7418
8366
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7419
8367
  var USER_UID = "plugin::users-permissions.user";
7420
8368
  var OWN_SESSIONS_LIMIT = 200;
@@ -8299,19 +9247,25 @@ var require_session = __commonJS({
8299
9247
  if (!userDocumentId) {
8300
9248
  return ctx.notFound("User not found");
8301
9249
  }
8302
- const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
8303
- if (!user) {
9250
+ const mode = hasRequestedState ? "explicit" : "toggle";
9251
+ const applyBlockedState = async () => {
9252
+ const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
9253
+ if (!user) return null;
9254
+ const nextBlocked = hasRequestedState ? requestedBlocked : !user.blocked;
9255
+ await runWithCallerRevocation(
9256
+ userDocumentId,
9257
+ () => strapi.documents(USER_UID).update({
9258
+ documentId: userDocumentId,
9259
+ data: { blocked: nextBlocked }
9260
+ })
9261
+ );
9262
+ return { blocked: nextBlocked };
9263
+ };
9264
+ const applied = mode === "toggle" ? await getCoordinator(strapi).withLock(`user-block:${userDocumentId}`, applyBlockedState) : await applyBlockedState();
9265
+ if (!applied) {
8304
9266
  return ctx.notFound("User not found");
8305
9267
  }
8306
- const mode = hasRequestedState ? "explicit" : "toggle";
8307
- const newBlockedStatus = hasRequestedState ? requestedBlocked : !user.blocked;
8308
- await runWithCallerRevocation(
8309
- userDocumentId,
8310
- () => strapi.documents(USER_UID).update({
8311
- documentId: userDocumentId,
8312
- data: { blocked: newBlockedStatus }
8313
- })
8314
- );
9268
+ const newBlockedStatus = applied.blocked;
8315
9269
  if (newBlockedStatus) {
8316
9270
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8317
9271
  await sessionService.terminateSession({ userId: userDocumentId, reason: "blocked" });
@@ -8824,10 +9778,13 @@ var require_settings = __commonJS({
8824
9778
  "server/src/controllers/settings.js"(exports, module) {
8825
9779
  "use strict";
8826
9780
  var {
8827
- invalidateSettingsCache,
9781
+ getSettingsRevision,
8828
9782
  normalizeGeoIpProvider,
8829
- normalizeGeoLookupFailureMode
9783
+ normalizeGeoLookupFailureMode,
9784
+ notifySettingsChanged
8830
9785
  } = require_settings_loader();
9786
+ var { withPluginStoreKey } = require_plugin_store();
9787
+ var { LockTimeoutError } = require_coordination();
8831
9788
  var { resolveDatabaseTarget } = require_geoip_updater();
8832
9789
  var { sendServerError, sendValidationError } = require_http_errors();
8833
9790
  var path = __require("node:path");
@@ -9215,6 +10172,26 @@ var require_settings = __commonJS({
9215
10172
  }
9216
10173
  return { settings, errors };
9217
10174
  }
10175
+ async function readRevision() {
10176
+ try {
10177
+ return await getSettingsRevision(strapi);
10178
+ } catch {
10179
+ return null;
10180
+ }
10181
+ }
10182
+ function sendSettingsConflict(ctx, currentRevision) {
10183
+ ctx.status = 409;
10184
+ ctx.body = {
10185
+ data: null,
10186
+ error: {
10187
+ status: 409,
10188
+ name: "ConflictError",
10189
+ message: "Settings were changed by another administrator. Reload and try again.",
10190
+ details: { revision: currentRevision }
10191
+ }
10192
+ };
10193
+ return ctx.body;
10194
+ }
9218
10195
  module.exports = {
9219
10196
  /**
9220
10197
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -9231,8 +10208,10 @@ var require_settings = __commonJS({
9231
10208
  });
9232
10209
  const storedSettings = await pluginStore.get({ key: "settings" });
9233
10210
  const settings = mergeSettingsWithDefaults(storedSettings);
10211
+ const revision = await readRevision();
9234
10212
  ctx.send({
9235
10213
  settings,
10214
+ ...revision === null ? {} : { revision },
9236
10215
  success: true
9237
10216
  });
9238
10217
  } catch (error) {
@@ -9256,42 +10235,60 @@ var require_settings = __commonJS({
9256
10235
  * @returns {Promise<void>}
9257
10236
  */
9258
10237
  async updateSettings(ctx) {
9259
- let pluginStore;
9260
- let current;
9261
10238
  try {
9262
10239
  const { body } = ctx.request;
9263
10240
  if (!body || typeof body !== "object" || Array.isArray(body)) {
9264
10241
  return ctx.badRequest("Settings data must be an object");
9265
10242
  }
9266
- pluginStore = strapi.store({
9267
- type: "plugin",
9268
- name: "magic-sessionmanager"
9269
- });
9270
- const stored = await pluginStore.get({ key: "settings" });
9271
- const storedObject = stored && typeof stored === "object" ? stored : {};
9272
- current = {
9273
- ...mergeSettingsWithDefaults(storedObject),
9274
- geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
9275
- };
9276
- const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
9277
- if (errors.length > 0) {
9278
- return sendValidationError(ctx, "Invalid settings", errors);
10243
+ const hasBaseRevision = Object.prototype.hasOwnProperty.call(body, "revision");
10244
+ if (hasBaseRevision && !(Number.isInteger(body.revision) && body.revision >= 0)) {
10245
+ return sendValidationError(ctx, "Invalid settings", [
10246
+ { path: ["revision"], message: "revision must be a non-negative integer" }
10247
+ ]);
9279
10248
  }
9280
- await pluginStore.set({
9281
- key: "settings",
9282
- value: sanitizedSettings
10249
+ const outcome = await withPluginStoreKey(strapi, "settings", async (pluginStore) => {
10250
+ if (hasBaseRevision) {
10251
+ const currentRevision = await readRevision();
10252
+ if (currentRevision !== null && currentRevision !== body.revision) {
10253
+ return { conflict: true, currentRevision };
10254
+ }
10255
+ }
10256
+ const stored = await pluginStore.get({ key: "settings" });
10257
+ const storedObject = stored && typeof stored === "object" ? stored : {};
10258
+ const current = {
10259
+ ...mergeSettingsWithDefaults(storedObject),
10260
+ geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
10261
+ };
10262
+ const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
10263
+ if (errors.length > 0) return { errors };
10264
+ await pluginStore.set({
10265
+ key: "settings",
10266
+ value: sanitizedSettings
10267
+ });
10268
+ const revision = await notifySettingsChanged(strapi);
10269
+ return { settings: sanitizedSettings, revision };
9283
10270
  });
9284
- invalidateSettingsCache();
10271
+ if (outcome.conflict) {
10272
+ return sendSettingsConflict(ctx, outcome.currentRevision);
10273
+ }
10274
+ if (outcome.errors) {
10275
+ return sendValidationError(ctx, "Invalid settings", outcome.errors);
10276
+ }
9285
10277
  strapi.log.info("[magic-sessionmanager/settings] Settings updated successfully");
9286
10278
  ctx.send({
9287
10279
  settings: {
9288
- ...sanitizedSettings,
9289
- geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
10280
+ ...outcome.settings,
10281
+ geoIpDatabasePath: getSafeGeoIpFilename(outcome.settings.geoIpDatabasePath)
9290
10282
  },
10283
+ ...outcome.revision === null || outcome.revision === void 0 ? {} : { revision: outcome.revision },
9291
10284
  success: true,
9292
10285
  message: "Settings saved successfully!"
9293
10286
  });
9294
10287
  } catch (error) {
10288
+ if (error instanceof LockTimeoutError) {
10289
+ strapi.log.warn("[magic-sessionmanager/settings] Settings are being saved elsewhere");
10290
+ return sendServerError(ctx, 503, "Settings are being saved by another request");
10291
+ }
9295
10292
  strapi.log.error(
9296
10293
  "[magic-sessionmanager/settings] Error updating settings:",
9297
10294
  error?.name || "Error"
@@ -9326,6 +10323,8 @@ var require_geoip = __commonJS({
9326
10323
  normalizeGeoIpDatabasePath
9327
10324
  } = require_settings_loader();
9328
10325
  var { sendServerError } = require_http_errors();
10326
+ var { setPluginStoreValue } = require_plugin_store();
10327
+ var { getHostFingerprint } = require_coordination();
9329
10328
  var CREDENTIALS_KEY = "geoipCredentials";
9330
10329
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
9331
10330
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -9348,11 +10347,7 @@ var require_geoip = __commonJS({
9348
10347
  };
9349
10348
  }
9350
10349
  async function setStoredCredentials(strapi2, credentials) {
9351
- const store = getGeoIpStore(strapi2);
9352
- await store.set({
9353
- key: CREDENTIALS_KEY,
9354
- value: credentials
9355
- });
10350
+ await setPluginStoreValue(strapi2, CREDENTIALS_KEY, credentials);
9356
10351
  }
9357
10352
  function getCredentialSource(storedCredentials) {
9358
10353
  if (process.env.MAXMIND_ACCOUNT_ID && process.env.MAXMIND_LICENSE_KEY) {
@@ -9419,7 +10414,12 @@ var require_geoip = __commonJS({
9419
10414
  metadata,
9420
10415
  hasCredentials: credentialSource !== "missing",
9421
10416
  credentialSource,
9422
- accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || ""
10417
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
10418
+ // The MMDB file lives on the local disk of the instance that
10419
+ // answered. In multi-instance deployments each instance reports
10420
+ // its own file; `instance` is a non-reversible host fingerprint.
10421
+ scope: "instance",
10422
+ instance: getHostFingerprint()
9423
10423
  }
9424
10424
  });
9425
10425
  } catch (error) {
@@ -9650,6 +10650,7 @@ var require_session2 = __commonJS({
9650
10650
  if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9651
10651
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9652
10652
  if (!revoked) {
10653
+ if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9653
10654
  throw new Error(
9654
10655
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9655
10656
  );
@@ -9680,7 +10681,10 @@ var require_session2 = __commonJS({
9680
10681
  }
9681
10682
  if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
9682
10683
  const revoked = await nativeManager.revokeSessionById(userId, parsed.nativeSessionId);
9683
- if (!revoked) throw new Error("Native session revocation was not confirmed.");
10684
+ if (!revoked) {
10685
+ if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
10686
+ throw new Error("Native session revocation was not confirmed.");
10687
+ }
9684
10688
  return true;
9685
10689
  }
9686
10690
  async function listNativeSessionsForUser(nativeManager, user, linkedIds = /* @__PURE__ */ new Set()) {
@@ -9817,6 +10821,7 @@ var require_session2 = __commonJS({
9817
10821
  if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9818
10822
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9819
10823
  if (!revoked) {
10824
+ if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9820
10825
  throw new Error(
9821
10826
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9822
10827
  );
@@ -10421,8 +11426,13 @@ var require_session2 = __commonJS({
10421
11426
  if (ts < cutoff) this._lastTouchCache.delete(k);
10422
11427
  }
10423
11428
  }
10424
- await strapi2.documents(SESSION_UID).update({
10425
- documentId: sessionDocId,
11429
+ const staleBefore = new Date(now.getTime() - rateLimit);
11430
+ await strapi2.db.query(SESSION_UID).updateMany({
11431
+ where: {
11432
+ documentId: sessionDocId,
11433
+ isActive: true,
11434
+ $or: [{ lastActive: { $lt: staleBefore } }, { lastActive: { $null: true } }]
11435
+ },
10426
11436
  data: { lastActive: now }
10427
11437
  });
10428
11438
  log.debug("[TOUCH] End-user session lastActive updated");
@@ -10512,9 +11522,24 @@ var require_session2 = __commonJS({
10512
11522
  let deactivatedCount = 0;
10513
11523
  for (const session of sessionsToDeactivate) {
10514
11524
  try {
10515
- if (nativeManager) await revokeNativeSessionForSidecar(nativeManager, session);
10516
- await strapi2.documents(SESSION_UID).update({
11525
+ const idleWhere = {
10517
11526
  documentId: session.documentId,
11527
+ isActive: true,
11528
+ $or: [
11529
+ { lastActive: { $lt: cutoffTime } },
11530
+ { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
11531
+ ]
11532
+ };
11533
+ if (nativeManager) {
11534
+ const stillIdle = await strapi2.documents(SESSION_UID).findFirst({
11535
+ filters: idleWhere,
11536
+ fields: ["documentId"]
11537
+ });
11538
+ if (!stillIdle) continue;
11539
+ await revokeNativeSessionForSidecar(nativeManager, session);
11540
+ }
11541
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
11542
+ where: idleWhere,
10518
11543
  data: {
10519
11544
  isActive: false,
10520
11545
  terminatedManually: false,
@@ -10522,7 +11547,7 @@ var require_session2 = __commonJS({
10522
11547
  logoutTime: now
10523
11548
  }
10524
11549
  });
10525
- deactivatedCount++;
11550
+ if (Number(result?.count) === 1) deactivatedCount++;
10526
11551
  } catch (err) {
10527
11552
  log.debug("[CLEANUP] Failed to deactivate an end-user session:", err?.name || "Error");
10528
11553
  }
@@ -10713,7 +11738,7 @@ var require_session2 = __commonJS({
10713
11738
  var require_package = __commonJS({
10714
11739
  "package.json"(exports, module) {
10715
11740
  module.exports = {
10716
- version: "4.9.0",
11741
+ version: "4.10.0",
10717
11742
  keywords: [
10718
11743
  "strapi",
10719
11744
  "plugin",
@@ -10761,6 +11786,7 @@ var require_package = __commonJS({
10761
11786
  scripts: {
10762
11787
  clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`,
10763
11788
  test: "node --test tests/*.test.js tests/*.test.mjs",
11789
+ "test:concurrency": "node scripts/concurrency/run.mjs",
10764
11790
  "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
10765
11791
  "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
10766
11792
  lint: "eslint .",
@@ -10791,11 +11817,13 @@ var require_package = __commonJS({
10791
11817
  "@strapi/icons": "^2.2.4",
10792
11818
  "@strapi/sdk-plugin": "^6.1.1",
10793
11819
  "@strapi/strapi": "5.61.0",
11820
+ "better-sqlite3": "^13.0.3",
10794
11821
  esbuild: "^0.28.2",
10795
11822
  eslint: "^10.14.0",
10796
11823
  "eslint-config-prettier": "^10.1.8",
10797
11824
  "eslint-plugin-react-hooks": "^7.1.1",
10798
11825
  globals: "^17.14.0",
11826
+ pg: "^8.23.1",
10799
11827
  prettier: "^3.9.10",
10800
11828
  react: "^18.3.1",
10801
11829
  "react-dom": "^18.3.1",
@@ -10849,6 +11877,7 @@ var require_license_guard = __commonJS({
10849
11877
  var os = __require("os");
10850
11878
  var pluginPkg = require_package();
10851
11879
  var { createLogger } = require_logger();
11880
+ var { setPluginStoreValue, withPluginStoreKey } = require_plugin_store();
10852
11881
  var DEFAULT_LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
10853
11882
  var envTimeout = Number(process.env.MAGIC_LICENSE_TIMEOUT_MS);
10854
11883
  var DEFAULT_FETCH_TIMEOUT_MS = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 12e3;
@@ -10882,29 +11911,30 @@ var require_license_guard = __commonJS({
10882
11911
  },
10883
11912
  async generateDeviceId() {
10884
11913
  try {
10885
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
10886
- const stored = await pluginStore.get({ key: "deviceId" });
10887
- if (stored && typeof stored === "string" && stored.length >= 16) {
10888
- return stored;
10889
- }
10890
- let identifier;
10891
- try {
10892
- const networkInterfaces = os.networkInterfaces();
10893
- const macAddresses = [];
10894
- Object.values(networkInterfaces).forEach((interfaces) => {
10895
- interfaces?.forEach((iface) => {
10896
- if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
10897
- macAddresses.push(iface.mac);
10898
- }
11914
+ return await withPluginStoreKey(strapi2, "deviceId", async (pluginStore) => {
11915
+ const stored = await pluginStore.get({ key: "deviceId" });
11916
+ if (stored && typeof stored === "string" && stored.length >= 16) {
11917
+ return stored;
11918
+ }
11919
+ let identifier;
11920
+ try {
11921
+ const networkInterfaces = os.networkInterfaces();
11922
+ const macAddresses = [];
11923
+ Object.values(networkInterfaces).forEach((interfaces) => {
11924
+ interfaces?.forEach((iface) => {
11925
+ if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
11926
+ macAddresses.push(iface.mac);
11927
+ }
11928
+ });
10899
11929
  });
10900
- });
10901
- identifier = `${macAddresses.join("-")}-${os.hostname()}`;
10902
- } catch {
10903
- identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
10904
- }
10905
- const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
10906
- await pluginStore.set({ key: "deviceId", value: deviceId });
10907
- return deviceId;
11930
+ identifier = `${macAddresses.join("-")}-${os.hostname()}`;
11931
+ } catch {
11932
+ identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
11933
+ }
11934
+ const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
11935
+ await pluginStore.set({ key: "deviceId", value: deviceId });
11936
+ return deviceId;
11937
+ });
10908
11938
  } catch {
10909
11939
  return crypto.randomBytes(16).toString("hex");
10910
11940
  }
@@ -10986,8 +12016,7 @@ var require_license_guard = __commonJS({
10986
12016
  );
10987
12017
  const data = await response.json();
10988
12018
  if (data.success && data.data) {
10989
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
10990
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
12019
+ await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
10991
12020
  return { valid: true, data: data.data };
10992
12021
  }
10993
12022
  return { valid: false, data: null };
@@ -11020,9 +12049,8 @@ var require_license_guard = __commonJS({
11020
12049
  return null;
11021
12050
  },
11022
12051
  async storeLicenseKey(licenseKey) {
11023
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
11024
- await pluginStore.set({ key: "licenseKey", value: licenseKey });
11025
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
12052
+ await setPluginStoreValue(strapi2, "licenseKey", licenseKey);
12053
+ await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
11026
12054
  log.info("[SUCCESS] License key stored");
11027
12055
  return true;
11028
12056
  },
@@ -11075,6 +12103,7 @@ var require_geolocation = __commonJS({
11075
12103
  var net = __require("node:net");
11076
12104
  var path = __require("node:path");
11077
12105
  var { getPluginSettings } = require_settings_loader();
12106
+ var { getCoordinator, hashedKey } = require_coordination();
11078
12107
  var { resolveDatabaseTarget } = require_geoip_updater();
11079
12108
  var GEO_API_TIMEOUT_MS = 4e3;
11080
12109
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -11083,6 +12112,7 @@ var require_geolocation = __commonJS({
11083
12112
  var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
11084
12113
  var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
11085
12114
  var IPAPI_MAX_QUEUE_SIZE = 50;
12115
+ var SHARED_BACKOFF_KEY = "geo:ipapi:backoff";
11086
12116
  var DEFAULT_CITY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
11087
12117
  var DEFAULT_COUNTRY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-Country.mmdb");
11088
12118
  var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
@@ -11159,6 +12189,50 @@ var require_geolocation = __commonJS({
11159
12189
  expiresAt: Date.now() + ttlMs
11160
12190
  });
11161
12191
  }
12192
+ async function getSharedIpapiResult(strapiInstance, lookupIp) {
12193
+ try {
12194
+ const data = await getCoordinator(strapiInstance).cacheGet(hashedKey("geo:ipapi", lookupIp));
12195
+ return data && typeof data === "object" ? { ...data, ip: lookupIp } : null;
12196
+ } catch {
12197
+ return null;
12198
+ }
12199
+ }
12200
+ async function shareIpapiResult(strapiInstance, lookupIp, data, ttlMs) {
12201
+ if (!lookupIp || !data || ttlMs <= 0) return;
12202
+ try {
12203
+ const { ip: _ip, ...withoutIp } = data;
12204
+ await getCoordinator(strapiInstance).cacheSet(
12205
+ hashedKey("geo:ipapi", lookupIp),
12206
+ withoutIp,
12207
+ ttlMs
12208
+ );
12209
+ } catch {
12210
+ }
12211
+ }
12212
+ async function cacheIpapiResultEverywhere(strapiInstance, lookupIp, data, ttlMs) {
12213
+ cacheIpapiResult(lookupIp, data, ttlMs);
12214
+ await shareIpapiResult(strapiInstance, lookupIp, data, ttlMs);
12215
+ }
12216
+ async function syncSharedIpapiBackoff(strapiInstance) {
12217
+ try {
12218
+ const until = Number(await getCoordinator(strapiInstance).cacheGet(SHARED_BACKOFF_KEY));
12219
+ if (Number.isFinite(until) && until > ipapiRateLimitedUntil) ipapiRateLimitedUntil = until;
12220
+ } catch {
12221
+ }
12222
+ return getIpapiRateLimitRemainingMs();
12223
+ }
12224
+ async function shareIpapiBackoff(strapiInstance) {
12225
+ const remaining = getIpapiRateLimitRemainingMs();
12226
+ if (remaining <= 0) return;
12227
+ try {
12228
+ await getCoordinator(strapiInstance).cacheSet(
12229
+ SHARED_BACKOFF_KEY,
12230
+ ipapiRateLimitedUntil,
12231
+ remaining
12232
+ );
12233
+ } catch {
12234
+ }
12235
+ }
11162
12236
  function getRetryAfterMs(response) {
11163
12237
  const retryAfter = response?.headers?.get?.("retry-after");
11164
12238
  if (!retryAfter) return null;
@@ -11465,7 +12539,12 @@ var require_geolocation = __commonJS({
11465
12539
  }
11466
12540
  const cached = getCachedIpapiResult(lookupIp);
11467
12541
  if (cached) return cached;
11468
- const rateLimitRemainingMs = getIpapiRateLimitRemainingMs();
12542
+ const shared = await getSharedIpapiResult(strapi2, lookupIp);
12543
+ if (shared) {
12544
+ cacheIpapiResult(lookupIp, shared, IPAPI_FAILURE_CACHE_TTL_MS);
12545
+ return cloneGeoData(shared);
12546
+ }
12547
+ const rateLimitRemainingMs = await syncSharedIpapiBackoff(strapi2);
11469
12548
  if (rateLimitRemainingMs > 0) {
11470
12549
  logIpapiRateLimit(
11471
12550
  strapi2,
@@ -11490,7 +12569,7 @@ var require_geolocation = __commonJS({
11490
12569
  "ipapi",
11491
12570
  "Remote GeoIP provider concurrency limit reached"
11492
12571
  );
11493
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12572
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11494
12573
  return fallback;
11495
12574
  }
11496
12575
  const queuedRateLimitRemainingMs = getIpapiRateLimitRemainingMs();
@@ -11519,6 +12598,7 @@ var require_geolocation = __commonJS({
11519
12598
  const reason = response.status === 429 ? "rate_limited" : "error";
11520
12599
  if (response.status === 429) {
11521
12600
  const backoffMs = markIpapiRateLimited(response);
12601
+ await shareIpapiBackoff(strapi2);
11522
12602
  logIpapiRateLimit(
11523
12603
  strapi2,
11524
12604
  `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11534,7 +12614,7 @@ var require_geolocation = __commonJS({
11534
12614
  "ipapi",
11535
12615
  `HTTP ${response.status}`
11536
12616
  );
11537
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12617
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11538
12618
  return fallback;
11539
12619
  }
11540
12620
  const data = await response.json();
@@ -11542,6 +12622,7 @@ var require_geolocation = __commonJS({
11542
12622
  const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
11543
12623
  if (reason === "rate_limited") {
11544
12624
  const backoffMs = markIpapiRateLimited();
12625
+ await shareIpapiBackoff(strapi2);
11545
12626
  logIpapiRateLimit(
11546
12627
  strapi2,
11547
12628
  `[magic-sessionmanager/geolocation] API reported rate limit; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11550,7 +12631,7 @@ var require_geolocation = __commonJS({
11550
12631
  strapi2.log.warn("[magic-sessionmanager/geolocation] Provider rejected the lookup");
11551
12632
  }
11552
12633
  const fallback = this.getFallbackData(lookupIp, reason, "ipapi", data.reason);
11553
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12634
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11554
12635
  return fallback;
11555
12636
  }
11556
12637
  const result = {
@@ -11587,7 +12668,7 @@ var require_geolocation = __commonJS({
11587
12668
  _source: "ipapi"
11588
12669
  };
11589
12670
  strapi2.log.debug("[magic-sessionmanager/geolocation] ipapi lookup completed");
11590
- cacheIpapiResult(lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
12671
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
11591
12672
  return result;
11592
12673
  } catch (error) {
11593
12674
  const status = error?.name === "AbortError" ? "error" : "error";
@@ -11596,7 +12677,7 @@ var require_geolocation = __commonJS({
11596
12677
  error?.name || "Error"
11597
12678
  );
11598
12679
  const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
11599
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12680
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11600
12681
  return fallback;
11601
12682
  } finally {
11602
12683
  clearTimeout(timer);
@@ -12183,12 +13264,7 @@ var require_rate_limit = __commonJS({
12183
13264
  "server/src/middlewares/rate-limit.js"(exports, module) {
12184
13265
  "use strict";
12185
13266
  var { getPluginSettings } = require_settings_loader();
12186
- var buckets = /* @__PURE__ */ new Map();
12187
- var prune = (now) => {
12188
- for (const [key, entry] of buckets) {
12189
- if (entry.expiresAt <= now) buckets.delete(key);
12190
- }
12191
- };
13267
+ var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
12192
13268
  var callerKey = (ctx) => {
12193
13269
  const userId = ctx.state?.user?.id;
12194
13270
  if (userId) return `u:${userId}`;
@@ -12208,15 +13284,7 @@ var require_rate_limit = __commonJS({
12208
13284
  const normalizedPath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") || "/" : rawPath;
12209
13285
  return `${method} path:${normalizedPath}`;
12210
13286
  };
12211
- var RESOLVED_TTL_MS = 3e4;
12212
- var resolvedCache = /* @__PURE__ */ new Map();
12213
13287
  async function resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) {
12214
- const now = Date.now();
12215
- const cacheKey = `${profile}:${routeMax}:${routeWindowMs}`;
12216
- const cachedEntry = resolvedCache.get(cacheKey);
12217
- if (cachedEntry && now - cachedEntry.at < RESOLVED_TTL_MS) {
12218
- return { max: cachedEntry.max, windowMs: cachedEntry.windowMs };
12219
- }
12220
13288
  let settings;
12221
13289
  try {
12222
13290
  settings = await getPluginSettings(strapi2);
@@ -12244,7 +13312,6 @@ var require_rate_limit = __commonJS({
12244
13312
  } else {
12245
13313
  resolved = { max: routeMax, windowMs: routeWindowMs };
12246
13314
  }
12247
- resolvedCache.set(cacheKey, { ...resolved, at: now });
12248
13315
  return resolved;
12249
13316
  }
12250
13317
  var rateLimit = (cfg = {}, { strapi: strapi2 }) => {
@@ -12253,17 +13320,12 @@ var require_rate_limit = __commonJS({
12253
13320
  const profile = cfg.profile === "read" || cfg.profile === "write" ? cfg.profile : null;
12254
13321
  return async (ctx, next) => {
12255
13322
  const { max, windowMs } = profile ? await resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) : { max: routeMax, windowMs: routeWindowMs };
12256
- const key = `${routeKey(ctx)}::${callerKey(ctx)}`;
13323
+ const key = hashedKey("rl", `${routeKey(ctx)}::${callerKey(ctx)}`);
12257
13324
  const now = Date.now();
12258
- if (buckets.size > 5e3) prune(now);
12259
- let entry = buckets.get(key);
12260
- if (!entry || entry.expiresAt <= now) {
12261
- entry = { count: 0, expiresAt: now + windowMs };
12262
- buckets.set(key, entry);
12263
- }
12264
- entry.count += 1;
12265
- if (entry.count > max) {
12266
- const retryAfterSec = Math.ceil((entry.expiresAt - now) / 1e3);
13325
+ const entry = await getCoordinator(strapi2).hit(key, windowMs);
13326
+ const expiresAt = entry.windowStart + windowMs;
13327
+ if (entry.hits > max) {
13328
+ const retryAfterSec = Math.max(1, Math.ceil((expiresAt - now) / 1e3));
12267
13329
  ctx.set("Retry-After", String(retryAfterSec));
12268
13330
  strapi2.log.warn("[magic-sessionmanager] Content API rate limit exceeded");
12269
13331
  ctx.status = 429;
@@ -12285,8 +13347,7 @@ var require_rate_limit = __commonJS({
12285
13347
  resolveLimits,
12286
13348
  routeKey,
12287
13349
  reset() {
12288
- buckets.clear();
12289
- resolvedCache.clear();
13350
+ __resetMemoryForTests();
12290
13351
  }
12291
13352
  };
12292
13353
  module.exports = rateLimit;