strapi-plugin-magic-sessionmanager 4.9.1 → 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 +47 -4
  2. package/README.md +195 -41
  3. package/dist/admin/{Analytics-lVDnHBYp.js → Analytics-CdmRsigN.js} +1 -1
  4. package/dist/admin/{Analytics-dyJmyxO-.mjs → Analytics-PRqsLMEx.mjs} +1 -1
  5. package/dist/admin/{App-Cgf_CSjw.mjs → App-BSeYF7KA.mjs} +1 -1
  6. package/dist/admin/{App-CdgiY_Y7.js → App-DUMCbuCr.js} +1 -1
  7. package/dist/admin/{License-1XUfQty5.js → License-BeD7Du6r.js} +1 -1
  8. package/dist/admin/{License-C4WSYoqY.mjs → License-D5W_l35e.mjs} +1 -1
  9. package/dist/admin/{OnlineUsersWidget-DJC4V1KS.mjs → OnlineUsersWidget-B5pXzqM9.mjs} +1 -1
  10. package/dist/admin/{OnlineUsersWidget-DMPtuIpm.js → OnlineUsersWidget-CDZ19_PT.js} +1 -1
  11. package/dist/admin/{Settings-DgeuUiMF.mjs → Settings-B-GRuWjT.mjs} +13 -3
  12. package/dist/admin/{Settings-0QsyY7fe.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-Ck19e8qw.mjs → index-CHACmZsg.mjs} +10 -10
  22. package/dist/admin/{index-D-Nr0TCm.js → index-CaLVyCio.js} +10 -10
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +1 -1
  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
@@ -79,24 +79,735 @@ 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
+ module2.exports = {
783
+ PLUGIN_ID,
784
+ collapseDuplicateStoreRows,
785
+ coreStoreKey,
786
+ setPluginStoreValue,
787
+ withPluginStoreKey
788
+ };
789
+ }
790
+ });
791
+
82
792
  // server/src/utils/content-api-permissions.js
83
793
  var require_content_api_permissions = __commonJS({
84
794
  "server/src/utils/content-api-permissions.js"(exports2, module2) {
85
795
  "use strict";
796
+ var { withPluginStoreKey } = require_plugin_store();
86
797
  var CONTENT_API_PERMISSIONS_VERSION = 2;
87
- var MAGIC_SESSIONMANAGER_STORE = "magic-sessionmanager";
88
798
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
89
799
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
90
800
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
91
801
  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
802
+ return withPluginStoreKey(strapi2, CONTENT_API_PERMISSIONS_VERSION_KEY, async (pluginStore) => {
803
+ const storedVersion = await pluginStore.get({ key: CONTENT_API_PERMISSIONS_VERSION_KEY });
804
+ if (Number(storedVersion) >= CONTENT_API_PERMISSIONS_VERSION) return false;
805
+ await pluginStore.set({
806
+ key: CONTENT_API_PERMISSIONS_VERSION_KEY,
807
+ value: CONTENT_API_PERMISSIONS_VERSION
808
+ });
809
+ return true;
98
810
  });
99
- return true;
100
811
  }
101
812
  function createContentApiPermissionsLifecycle(strapi2) {
102
813
  return {
@@ -376,7 +1087,11 @@ var require_encryption = __commonJS({
376
1087
  if (!token) return null;
377
1088
  return crypto.createHash("sha256").update(token).digest("hex");
378
1089
  }
1090
+ function getEncryptionKeyCheck() {
1091
+ return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
1092
+ }
379
1093
  module2.exports = {
1094
+ getEncryptionKeyCheck,
380
1095
  encryptToken,
381
1096
  decryptToken,
382
1097
  generateSessionId,
@@ -435,13 +1150,18 @@ var require_resolve_user = __commonJS({
435
1150
  var require_settings_loader = __commonJS({
436
1151
  "server/src/utils/settings-loader.js"(exports2, module2) {
437
1152
  "use strict";
1153
+ var { getCoordinator } = require_coordination();
438
1154
  var PLUGIN_ID = "magic-sessionmanager";
439
1155
  var SETTINGS_KEY = "settings";
440
1156
  var CACHE_TTL_MS = 30 * 1e3;
1157
+ var REVISION_CHECK_MS = 2 * 1e3;
1158
+ var SETTINGS_REVISION = "settings";
441
1159
  var GEO_IP_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
442
1160
  var GEO_LOOKUP_FAILURE_MODES = /* @__PURE__ */ new Set(["auto", "allow", "block"]);
443
1161
  var cached = null;
444
1162
  var cachedAt = 0;
1163
+ var cachedRevision = null;
1164
+ var revisionCheckedAt = 0;
445
1165
  function toIntInRange(value, fallback, min, max) {
446
1166
  const n = Number.parseInt(value, 10);
447
1167
  if (!Number.isFinite(n)) return fallback;
@@ -555,8 +1275,23 @@ var require_settings_loader = __commonJS({
555
1275
  }
556
1276
  async function getPluginSettings(strapi2) {
557
1277
  const now = Date.now();
1278
+ const coordinator = getCoordinator(strapi2);
558
1279
  if (cached && now - cachedAt < CACHE_TTL_MS) {
559
- return cached;
1280
+ if (now - revisionCheckedAt < REVISION_CHECK_MS) return cached;
1281
+ revisionCheckedAt = now;
1282
+ let revision2;
1283
+ try {
1284
+ revision2 = await coordinator.getRevision(SETTINGS_REVISION);
1285
+ } catch {
1286
+ return cached;
1287
+ }
1288
+ if (revision2 === cachedRevision) return cached;
1289
+ }
1290
+ let revision;
1291
+ try {
1292
+ revision = await coordinator.getRevision(SETTINGS_REVISION);
1293
+ } catch {
1294
+ revision = null;
560
1295
  }
561
1296
  const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
562
1297
  let storedSettings;
@@ -573,6 +1308,8 @@ var require_settings_loader = __commonJS({
573
1308
  const merged = { ...staticConfig, ...storedSettings };
574
1309
  cached = merged;
575
1310
  cachedAt = now;
1311
+ cachedRevision = revision;
1312
+ revisionCheckedAt = now;
576
1313
  return merged;
577
1314
  }
578
1315
  function getPluginSettingsSync(strapi2) {
@@ -582,11 +1319,30 @@ var require_settings_loader = __commonJS({
582
1319
  function invalidateSettingsCache() {
583
1320
  cached = null;
584
1321
  cachedAt = 0;
1322
+ cachedRevision = null;
1323
+ revisionCheckedAt = 0;
1324
+ }
1325
+ async function getSettingsRevision(strapi2) {
1326
+ return getCoordinator(strapi2).getRevision(SETTINGS_REVISION);
1327
+ }
1328
+ async function notifySettingsChanged(strapi2) {
1329
+ invalidateSettingsCache();
1330
+ try {
1331
+ return await getCoordinator(strapi2).bumpRevision(SETTINGS_REVISION);
1332
+ } catch (err) {
1333
+ strapi2?.log?.warn?.(
1334
+ `[${PLUGIN_ID}] settings-loader: could not publish the settings revision:`,
1335
+ err?.name || "Error"
1336
+ );
1337
+ return null;
1338
+ }
585
1339
  }
586
1340
  module2.exports = {
587
1341
  getPluginSettings,
588
1342
  getPluginSettingsSync,
589
1343
  invalidateSettingsCache,
1344
+ notifySettingsChanged,
1345
+ getSettingsRevision,
590
1346
  normalizeStoredSettings,
591
1347
  normalizeRetentionDays,
592
1348
  getSessionCreationGraceMs,
@@ -5127,7 +5883,7 @@ var require_bootstrap = __commonJS({
5127
5883
  "server/src/bootstrap.js"(exports2, module2) {
5128
5884
  "use strict";
5129
5885
  var getClientIp = require_getClientIp();
5130
- var { encryptToken, hashToken } = require_encryption();
5886
+ var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
5131
5887
  var { createLogger } = require_logger();
5132
5888
  var { resolveUserDocumentId } = require_resolve_user();
5133
5889
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -5137,6 +5893,13 @@ var require_bootstrap = __commonJS({
5137
5893
  var { REVOCATION_UID } = require_session_revocation();
5138
5894
  var { getNativeSessionManager } = require_native_session_manager();
5139
5895
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
5896
+ var {
5897
+ getCoordinator,
5898
+ hashedKey,
5899
+ initCoordination,
5900
+ LockTimeoutError
5901
+ } = require_coordination();
5902
+ var { withPluginStoreKey } = require_plugin_store();
5140
5903
  var {
5141
5904
  classifyJwtIssuingRequest,
5142
5905
  isFailedLoginTrackedPath,
@@ -5150,6 +5913,12 @@ var require_bootstrap = __commonJS({
5150
5913
  stripAuthTokensFromResponse
5151
5914
  } = require_refresh_token();
5152
5915
  var SESSION_UID = "plugin::magic-sessionmanager.session";
5916
+ var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
5917
+ var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5918
+ var JOB_LEASES = Object.freeze({
5919
+ idleCleanup: "job:idle-cleanup",
5920
+ retention: "job:retention"
5921
+ });
5153
5922
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
5154
5923
  var deferredContentApiPermissionSetup = /* @__PURE__ */ new WeakMap();
5155
5924
  async function getRequestSettings(strapi2, ctx) {
@@ -5174,6 +5943,8 @@ var require_bootstrap = __commonJS({
5174
5943
  throw e;
5175
5944
  }
5176
5945
  try {
5946
+ const coordinator = await initCoordination(strapi2, log);
5947
+ await checkEncryptionKeyConsistency(strapi2, log);
5177
5948
  await ensureSessionLookupIndexes(strapi2, log);
5178
5949
  await registerSessionAwareAuthStrategy(strapi2);
5179
5950
  const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
@@ -5183,12 +5954,27 @@ var require_bootstrap = __commonJS({
5183
5954
  if (!strapi2.sessionManagerIntervals) {
5184
5955
  strapi2.sessionManagerIntervals = {};
5185
5956
  }
5957
+ const runIdleCleanupIfLeader = async (intervalMs, useDbDirect) => {
5958
+ const leaseMs = Math.max(60 * 1e3, intervalMs - 30 * 1e3);
5959
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.idleCleanup, leaseMs)) {
5960
+ log.debug("[CLEANUP] Another instance holds the cleanup lease; skipping this run");
5961
+ return;
5962
+ }
5963
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
5964
+ await service.cleanupInactiveSessions({ useDbDirect });
5965
+ try {
5966
+ await coordinator.prune();
5967
+ } catch (err) {
5968
+ log.debug("[CLEANUP] Shared counter pruning failed:", err?.name || "Error");
5969
+ }
5970
+ };
5186
5971
  log.info("Running initial session cleanup...");
5187
5972
  try {
5188
5973
  const settings = await getPluginSettings(strapi2);
5189
- await sessionService.cleanupInactiveSessions({
5190
- useDbDirect: settings.cleanupUseDbDirect === true
5191
- });
5974
+ await runIdleCleanupIfLeader(
5975
+ Math.max(5 * 60 * 1e3, settings.cleanupInterval || 30 * 60 * 1e3),
5976
+ settings.cleanupUseDbDirect === true
5977
+ );
5192
5978
  } catch (cleanupErr) {
5193
5979
  log.warn("Initial cleanup failed:", cleanupErr?.name || "Error");
5194
5980
  }
@@ -5203,8 +5989,7 @@ var require_bootstrap = __commonJS({
5203
5989
  }
5204
5990
  const handle = setTimeout(async () => {
5205
5991
  try {
5206
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5207
- await service.cleanupInactiveSessions({ useDbDirect });
5992
+ await runIdleCleanupIfLeader(intervalMs, useDbDirect);
5208
5993
  } catch (err) {
5209
5994
  log.error("Periodic cleanup error:", err?.name || "Error");
5210
5995
  }
@@ -5213,7 +5998,6 @@ var require_bootstrap = __commonJS({
5213
5998
  strapi2.sessionManagerIntervals.cleanupTimeout = handle;
5214
5999
  };
5215
6000
  await scheduleIdleCleanup();
5216
- const RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
5217
6001
  const scheduleRetention = async () => {
5218
6002
  let useDbDirect = false;
5219
6003
  try {
@@ -5223,8 +6007,7 @@ var require_bootstrap = __commonJS({
5223
6007
  }
5224
6008
  const handle = setTimeout(async () => {
5225
6009
  try {
5226
- const service = strapi2.plugin("magic-sessionmanager").service("session");
5227
- await service.deleteOldSessions({ useDbDirect });
6010
+ await runRetentionIfLeader(useDbDirect);
5228
6011
  } catch (err) {
5229
6012
  log.error("Retention cleanup error:", err?.name || "Error");
5230
6013
  }
@@ -5232,8 +6015,23 @@ var require_bootstrap = __commonJS({
5232
6015
  }, RETENTION_INTERVAL_MS);
5233
6016
  strapi2.sessionManagerIntervals.retentionTimeout = handle;
5234
6017
  };
6018
+ const runRetentionIfLeader = async (useDbDirect) => {
6019
+ const leaseMs = RETENTION_INTERVAL_MS - 60 * 60 * 1e3;
6020
+ if (!await coordinator.tryAcquireLease(JOB_LEASES.retention, leaseMs)) {
6021
+ log.debug("[RETENTION] Another instance holds the retention lease; skipping this run");
6022
+ return;
6023
+ }
6024
+ const service = strapi2.plugin("magic-sessionmanager").service("session");
6025
+ await service.deleteOldSessions({ useDbDirect });
6026
+ };
5235
6027
  strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
5236
- () => {
6028
+ async () => {
6029
+ try {
6030
+ const settings = await getPluginSettings(strapi2);
6031
+ await runRetentionIfLeader(settings.cleanupUseDbDirect === true);
6032
+ } catch (err) {
6033
+ log.error("Retention cleanup error:", err?.name || "Error");
6034
+ }
5237
6035
  scheduleRetention();
5238
6036
  },
5239
6037
  5 * 60 * 1e3
@@ -5263,6 +6061,24 @@ var require_bootstrap = __commonJS({
5263
6061
  log.error("[ERROR] Bootstrap error:", err?.name || "Error");
5264
6062
  }
5265
6063
  };
6064
+ async function checkEncryptionKeyConsistency(strapi2, log) {
6065
+ const coordinator = getCoordinator(strapi2);
6066
+ if (!coordinator.dialect) return;
6067
+ try {
6068
+ const current = getEncryptionKeyCheck();
6069
+ const stored = await coordinator.cacheGet("instance:encryption-key-check");
6070
+ if (stored && stored !== current) {
6071
+ log.error(
6072
+ "[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."
6073
+ );
6074
+ }
6075
+ if (stored !== current) {
6076
+ await coordinator.cacheSet("instance:encryption-key-check", current, Infinity);
6077
+ }
6078
+ } catch (err) {
6079
+ log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
6080
+ }
6081
+ }
5266
6082
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
5267
6083
  strapi2.server.use(async (ctx, next) => {
5268
6084
  if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
@@ -5472,31 +6288,9 @@ var require_bootstrap = __commonJS({
5472
6288
  }
5473
6289
  }
5474
6290
  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);
6291
+ const WINDOW_MS = FAILED_LOGIN_WINDOW_MS;
6292
+ const coordinator = getCoordinator(strapi2);
6293
+ const keyFor = (ip) => hashedKey("lf", ip);
5500
6294
  strapi2.server.use(async (ctx, next) => {
5501
6295
  if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
5502
6296
  const settings = await getRequestSettings(strapi2, ctx);
@@ -5504,10 +6298,15 @@ var require_bootstrap = __commonJS({
5504
6298
  if (maxFailed <= 0) return next();
5505
6299
  const ip = getClientIp(ctx);
5506
6300
  if (!ip || ip === "unknown") return next();
6301
+ const key = keyFor(ip);
5507
6302
  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);
6303
+ let existing = null;
6304
+ try {
6305
+ existing = await coordinator.peek(key);
6306
+ } catch (err) {
6307
+ log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
6308
+ }
6309
+ const rejectLocked = (retrySec) => {
5511
6310
  ctx.set("Retry-After", String(retrySec));
5512
6311
  log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
5513
6312
  ctx.status = 429;
@@ -5519,20 +6318,80 @@ var require_bootstrap = __commonJS({
5519
6318
  details: { retryAfter: retrySec }
5520
6319
  }
5521
6320
  };
6321
+ };
6322
+ if (existing && existing.blockedUntil > now) {
6323
+ rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
5522
6324
  return;
5523
6325
  }
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`);
6326
+ let reserved = null;
6327
+ try {
6328
+ reserved = await coordinator.hit(key, WINDOW_MS);
6329
+ } catch (err) {
6330
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
6331
+ }
6332
+ if (reserved && reserved.hits > maxFailed) {
6333
+ try {
6334
+ await coordinator.release(key);
6335
+ } catch (err) {
6336
+ log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
5531
6337
  }
6338
+ ctx.set("Retry-After", "1");
6339
+ ctx.status = 429;
6340
+ ctx.body = {
6341
+ error: {
6342
+ status: 429,
6343
+ name: "TooManyRequestsError",
6344
+ message: "Too many login attempts at once. Please try again.",
6345
+ details: { retryAfter: 1 }
6346
+ }
6347
+ };
6348
+ return;
5532
6349
  }
6350
+ let thrown = null;
6351
+ try {
6352
+ await next();
6353
+ } catch (err) {
6354
+ thrown = err;
6355
+ }
6356
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
6357
+ try {
6358
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) {
6359
+ await coordinator.clear(key);
6360
+ } else if (status >= 400 && status < 500 && status !== 429) {
6361
+ if (reserved && reserved.hits >= maxFailed) {
6362
+ await coordinator.block(key, Date.now() + WINDOW_MS);
6363
+ log.warn(
6364
+ `[LOCKOUT] Client locked for 15min after ${reserved.hits} failed login attempts`
6365
+ );
6366
+ }
6367
+ } else if (reserved) {
6368
+ await coordinator.release(key);
6369
+ }
6370
+ } catch (err) {
6371
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
6372
+ }
6373
+ if (thrown) throw thrown;
5533
6374
  });
5534
6375
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
5535
6376
  }
6377
+ function statusOfThrownError(err) {
6378
+ const status = Number(err?.status ?? err?.statusCode);
6379
+ if (Number.isInteger(status) && status >= 400 && status < 600) return status;
6380
+ const byName = {
6381
+ UnauthorizedError: 401,
6382
+ ForbiddenError: 403,
6383
+ NotFoundError: 404,
6384
+ PayloadTooLargeError: 413,
6385
+ RateLimitError: 429,
6386
+ NotImplementedError: 501,
6387
+ ApplicationError: 400,
6388
+ ValidationError: 400,
6389
+ YupValidationError: 400,
6390
+ PaginationError: 400,
6391
+ PolicyError: 403
6392
+ };
6393
+ return byName[err?.name] || 500;
6394
+ }
5536
6395
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
5537
6396
  strapi2.server.use(async (ctx, next) => {
5538
6397
  const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
@@ -6011,77 +6870,110 @@ var require_bootstrap = __commonJS({
6011
6870
  }
6012
6871
  async function ensureContentApiPermissions(strapi2, log) {
6013
6872
  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");
6873
+ return await withPluginStoreKey(
6874
+ strapi2,
6875
+ "contentApiPermissionsVersion",
6876
+ (pluginStore) => ensureContentApiPermissionsLocked(strapi2, log, pluginStore)
6877
+ );
6878
+ } catch (err) {
6879
+ if (err instanceof LockTimeoutError) {
6880
+ log.warn("Content-API permission setup is busy on another instance; will retry");
6037
6881
  return false;
6038
6882
  }
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`);
6883
+ log.warn("Could not auto-configure permissions:", err?.name || "Error");
6884
+ log.warn(
6885
+ "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6886
+ );
6887
+ return false;
6888
+ }
6889
+ }
6890
+ async function ensureContentApiPermissionsLocked(strapi2, log, pluginStore) {
6891
+ const storedVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6892
+ if (storedVersion === void 0 || storedVersion === null) {
6893
+ const legacyFlag = await pluginStore.get({ key: "contentApiPermissionsInitialized" });
6894
+ if (legacyFlag === true) {
6895
+ await pluginStore.set({ key: "contentApiPermissionsVersion", value: 1 });
6071
6896
  }
6897
+ }
6898
+ const effectiveVersion = await pluginStore.get({ key: "contentApiPermissionsVersion" });
6899
+ if (effectiveVersion >= CONTENT_API_PERMISSIONS_VERSION) {
6900
+ log.debug("Content-API permissions already at current version (skipping auto-setup)");
6901
+ return true;
6902
+ }
6903
+ const ROLE_UID = "plugin::users-permissions.role";
6904
+ const PERMISSION_UID = "plugin::users-permissions.permission";
6905
+ const roles = await strapi2.documents(ROLE_UID).findMany({
6906
+ filters: { type: "authenticated" },
6907
+ fields: ["id"],
6908
+ limit: 1
6909
+ });
6910
+ const authenticatedRole = roles?.[0];
6911
+ if (!authenticatedRole) {
6912
+ log.warn("Authenticated role not found - skipping permission setup");
6913
+ return false;
6914
+ }
6915
+ const requiredActions = [
6916
+ "plugin::magic-sessionmanager.session.logout",
6917
+ "plugin::magic-sessionmanager.session.logoutAll",
6918
+ "plugin::magic-sessionmanager.session.logoutOthers",
6919
+ "plugin::magic-sessionmanager.session.getOwnSessions",
6920
+ "plugin::magic-sessionmanager.session.getUserSessions",
6921
+ "plugin::magic-sessionmanager.session.getCurrentSession",
6922
+ "plugin::magic-sessionmanager.session.terminateOwnSession"
6923
+ ];
6924
+ const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
6925
+ filters: {
6926
+ role: authenticatedRole.id,
6927
+ action: { $in: requiredActions }
6928
+ },
6929
+ fields: ["id", "documentId", "action"],
6930
+ sort: { id: "asc" },
6931
+ limit: requiredActions.length * 10
6932
+ });
6933
+ await removeDuplicatePermissions(strapi2, log, PERMISSION_UID, existingPermissions);
6934
+ const existingActions = existingPermissions.map((p) => p.action);
6935
+ const missingActions = requiredActions.filter((action) => !existingActions.includes(action));
6936
+ if (missingActions.length === 0) {
6072
6937
  await pluginStore.set({
6073
6938
  key: "contentApiPermissionsVersion",
6074
6939
  value: CONTENT_API_PERMISSIONS_VERSION
6075
6940
  });
6076
- log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6941
+ log.debug("Content-API permissions already configured");
6077
6942
  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
6943
  }
6944
+ for (const action of missingActions) {
6945
+ await strapi2.documents(PERMISSION_UID).create({
6946
+ data: { action, role: authenticatedRole.id }
6947
+ });
6948
+ log.info(`[PERMISSION] Enabled ${action} for authenticated users`);
6949
+ }
6950
+ await pluginStore.set({
6951
+ key: "contentApiPermissionsVersion",
6952
+ value: CONTENT_API_PERMISSIONS_VERSION
6953
+ });
6954
+ log.info("[SUCCESS] Content-API permissions configured for authenticated users");
6955
+ return true;
6956
+ }
6957
+ async function removeDuplicatePermissions(strapi2, log, permissionUid, permissions) {
6958
+ const seen = /* @__PURE__ */ new Set();
6959
+ let removed = 0;
6960
+ for (const permission of permissions || []) {
6961
+ if (!seen.has(permission.action)) {
6962
+ seen.add(permission.action);
6963
+ continue;
6964
+ }
6965
+ if (!permission.documentId) continue;
6966
+ try {
6967
+ await strapi2.documents(permissionUid).delete({ documentId: permission.documentId });
6968
+ removed++;
6969
+ } catch (err) {
6970
+ log.debug("[PERMISSION] Could not remove a duplicate permission:", err?.name || "Error");
6971
+ }
6972
+ }
6973
+ if (removed > 0) {
6974
+ log.warn(`[PERMISSION] Removed ${removed} duplicate Content-API permission row(s)`);
6975
+ }
6976
+ return removed;
6085
6977
  }
6086
6978
  function mountDeferredContentApiPermissionRetry({
6087
6979
  strapi: strapi2,
@@ -6124,44 +7016,10 @@ var require_bootstrap = __commonJS({
6124
7016
  }
6125
7017
  async function ensureSessionLookupIndexes(strapi2, log) {
6126
7018
  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
- }
7019
+ await getCoordinator(strapi2).withLock(
7020
+ "schema:session-indexes",
7021
+ () => createSessionLookupIndexes(strapi2, log)
7022
+ );
6165
7023
  } catch (err) {
6166
7024
  log.debug(
6167
7025
  "[INDEX] Could not create session lookup indexes (will retry on next startup):",
@@ -6169,6 +7027,54 @@ var require_bootstrap = __commonJS({
6169
7027
  );
6170
7028
  }
6171
7029
  }
7030
+ async function createSessionLookupIndexes(strapi2, log) {
7031
+ const knex = strapi2.db.connection;
7032
+ const tableName = "magic_sessions";
7033
+ const definitions = [
7034
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7035
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
7036
+ ];
7037
+ if (!await knex.schema.hasTable(tableName)) return;
7038
+ const dialect = strapi2.db.dialect.client;
7039
+ for (const definition of definitions) {
7040
+ if (dialect === "postgres" || dialect === "sqlite" || dialect === "better-sqlite3") {
7041
+ const exists = dialect === "postgres" ? (await knex.raw("SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
7042
+ tableName,
7043
+ definition.name
7044
+ ])).rows.length > 0 : (await knex.raw("SELECT name FROM sqlite_master WHERE type='index' AND name = ?", [
7045
+ definition.name
7046
+ ])).length > 0;
7047
+ if (exists) {
7048
+ log.debug(`[INDEX] ${definition.name} already exists`);
7049
+ continue;
7050
+ }
7051
+ await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7052
+ definition.name,
7053
+ tableName,
7054
+ definition.column,
7055
+ "is_active"
7056
+ ]);
7057
+ log.info(`[INDEX] Created ${definition.name}`);
7058
+ continue;
7059
+ }
7060
+ let hasIndex = false;
7061
+ if (dialect === "mysql" || dialect === "mysql2") {
7062
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
7063
+ tableName,
7064
+ definition.name
7065
+ ]);
7066
+ hasIndex = result[0].length > 0;
7067
+ }
7068
+ if (hasIndex) {
7069
+ log.debug(`[INDEX] ${definition.name} already exists`);
7070
+ continue;
7071
+ }
7072
+ await knex.schema.alterTable(tableName, (table) => {
7073
+ table.index([definition.column, "is_active"], definition.name);
7074
+ });
7075
+ log.info(`[INDEX] Created ${definition.name}`);
7076
+ }
7077
+ }
6172
7078
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
6173
7079
  var MAX_CONSECUTIVE_ERRORS = 10;
6174
7080
  var ERROR_RESET_INTERVAL = 60 * 1e3;
@@ -6351,8 +7257,8 @@ var require_bootstrap = __commonJS({
6351
7257
  strapi2.log.info(
6352
7258
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days`
6353
7259
  );
6354
- await strapi2.documents(SESSION_UID).update({
6355
- documentId: thisSession.documentId,
7260
+ await strapi2.db.query(SESSION_UID).updateMany({
7261
+ where: { documentId: thisSession.documentId, isActive: true },
6356
7262
  data: {
6357
7263
  isActive: false,
6358
7264
  terminatedManually: false,
@@ -6370,8 +7276,8 @@ var require_bootstrap = __commonJS({
6370
7276
  strapi2.log.info(
6371
7277
  `[magic-sessionmanager] [JWT-IDLE] Session too idle to reactivate (${Math.round(idleFor / 1e3)}s > ${inactivityTimeout / 1e3}s)`
6372
7278
  );
6373
- await strapi2.documents(SESSION_UID).update({
6374
- documentId: thisSession.documentId,
7279
+ await strapi2.db.query(SESSION_UID).updateMany({
7280
+ where: { documentId: thisSession.documentId, isActive: true },
6375
7281
  data: {
6376
7282
  isActive: false,
6377
7283
  terminatedManually: false,
@@ -6386,10 +7292,22 @@ var require_bootstrap = __commonJS({
6386
7292
  resetErrorCounter();
6387
7293
  return decoded;
6388
7294
  }
6389
- await strapi2.documents(SESSION_UID).update({
6390
- documentId: thisSession.documentId,
7295
+ const reactivated = await strapi2.db.query(SESSION_UID).updateMany({
7296
+ where: {
7297
+ documentId: thisSession.documentId,
7298
+ isActive: false,
7299
+ terminationReason: { $null: true },
7300
+ $or: [{ terminatedManually: false }, { terminatedManually: { $null: true } }]
7301
+ },
6391
7302
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
6392
7303
  });
7304
+ if (Number(reactivated?.count) !== 1) {
7305
+ strapi2.log.info(
7306
+ "[magic-sessionmanager] [JWT-REJECTED] Session was terminated concurrently"
7307
+ );
7308
+ setSessionRejectionReason(tokenHashValue, "manual");
7309
+ return null;
7310
+ }
6393
7311
  strapi2.log.info("[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated");
6394
7312
  resetErrorCounter();
6395
7313
  return decoded;
@@ -6455,6 +7373,8 @@ var require_bootstrap = __commonJS({
6455
7373
  }
6456
7374
  module2.exports.__private = {
6457
7375
  registerSessionAwareAuthStrategy,
7376
+ mountFailedLoginLockout,
7377
+ ensureSessionLookupIndexes,
6458
7378
  mountPreLoginGeoGuard,
6459
7379
  mountLoginInterceptor,
6460
7380
  mountRefreshTokenInterceptor,
@@ -6526,7 +7446,16 @@ var require_config = __commonJS({
6526
7446
  enableWebhooks: false,
6527
7447
  discordWebhookUrl: "",
6528
7448
  slackWebhookUrl: "",
6529
- trustedProxies: null
7449
+ trustedProxies: null,
7450
+ // Cross-process state for pm2 cluster / several replicas. `enabled:
7451
+ // false` keeps every counter, lease and cache per process (the pre-4.10
7452
+ // behaviour). `counterStore` may supply an object with async
7453
+ // hit/peek/block/clear methods (for example backed by Redis) for the
7454
+ // lockout and rate-limit counters; see README "Running several instances".
7455
+ coordination: {
7456
+ enabled: true,
7457
+ counterStore: null
7458
+ }
6530
7459
  },
6531
7460
  validator: (config2) => {
6532
7461
  if (config2.lastSeenRateLimit !== void 0 && typeof config2.lastSeenRateLimit !== "number") {
@@ -6556,6 +7485,24 @@ var require_config = __commonJS({
6556
7485
  if (config2.geoLookupFailureMode !== void 0 && !["auto", "allow", "block"].includes(config2.geoLookupFailureMode)) {
6557
7486
  throw new Error("geoLookupFailureMode must be one of: auto, allow, block");
6558
7487
  }
7488
+ if (config2.coordination !== void 0 && config2.coordination !== null) {
7489
+ const coordination = config2.coordination;
7490
+ if (typeof coordination !== "object" || Array.isArray(coordination)) {
7491
+ throw new Error("coordination must be an object");
7492
+ }
7493
+ if (coordination.enabled !== void 0 && typeof coordination.enabled !== "boolean") {
7494
+ throw new Error("coordination.enabled must be a boolean");
7495
+ }
7496
+ const store = coordination.counterStore;
7497
+ if (store !== void 0 && store !== null) {
7498
+ const required = ["hit", "peek", "block", "clear"];
7499
+ if (typeof store !== "object" || required.some((method) => typeof store[method] !== "function")) {
7500
+ throw new Error(
7501
+ "coordination.counterStore must implement async hit, peek, block and clear methods"
7502
+ );
7503
+ }
7504
+ }
7505
+ }
6559
7506
  }
6560
7507
  };
6561
7508
  }
@@ -7409,6 +8356,7 @@ var require_session = __commonJS({
7409
8356
  var { parseNativeSessionKey } = require_native_session_view();
7410
8357
  var { runWithCallerRevocation } = require_block_revocation_scope();
7411
8358
  var { sendServerError } = require_http_errors();
8359
+ var { getCoordinator } = require_coordination();
7412
8360
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7413
8361
  var USER_UID = "plugin::users-permissions.user";
7414
8362
  var OWN_SESSIONS_LIMIT = 200;
@@ -8293,19 +9241,25 @@ var require_session = __commonJS({
8293
9241
  if (!userDocumentId) {
8294
9242
  return ctx.notFound("User not found");
8295
9243
  }
8296
- const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
8297
- if (!user) {
9244
+ const mode = hasRequestedState ? "explicit" : "toggle";
9245
+ const applyBlockedState = async () => {
9246
+ const user = await strapi.documents(USER_UID).findOne({ documentId: userDocumentId });
9247
+ if (!user) return null;
9248
+ const nextBlocked = hasRequestedState ? requestedBlocked : !user.blocked;
9249
+ await runWithCallerRevocation(
9250
+ userDocumentId,
9251
+ () => strapi.documents(USER_UID).update({
9252
+ documentId: userDocumentId,
9253
+ data: { blocked: nextBlocked }
9254
+ })
9255
+ );
9256
+ return { blocked: nextBlocked };
9257
+ };
9258
+ const applied = mode === "toggle" ? await getCoordinator(strapi).withLock(`user-block:${userDocumentId}`, applyBlockedState) : await applyBlockedState();
9259
+ if (!applied) {
8298
9260
  return ctx.notFound("User not found");
8299
9261
  }
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
- );
9262
+ const newBlockedStatus = applied.blocked;
8309
9263
  if (newBlockedStatus) {
8310
9264
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8311
9265
  await sessionService.terminateSession({ userId: userDocumentId, reason: "blocked" });
@@ -8818,10 +9772,13 @@ var require_settings = __commonJS({
8818
9772
  "server/src/controllers/settings.js"(exports2, module2) {
8819
9773
  "use strict";
8820
9774
  var {
8821
- invalidateSettingsCache,
9775
+ getSettingsRevision,
8822
9776
  normalizeGeoIpProvider,
8823
- normalizeGeoLookupFailureMode
9777
+ normalizeGeoLookupFailureMode,
9778
+ notifySettingsChanged
8824
9779
  } = require_settings_loader();
9780
+ var { withPluginStoreKey } = require_plugin_store();
9781
+ var { LockTimeoutError } = require_coordination();
8825
9782
  var { resolveDatabaseTarget } = require_geoip_updater();
8826
9783
  var { sendServerError, sendValidationError } = require_http_errors();
8827
9784
  var path = require("node:path");
@@ -9209,6 +10166,26 @@ var require_settings = __commonJS({
9209
10166
  }
9210
10167
  return { settings, errors };
9211
10168
  }
10169
+ async function readRevision() {
10170
+ try {
10171
+ return await getSettingsRevision(strapi);
10172
+ } catch {
10173
+ return null;
10174
+ }
10175
+ }
10176
+ function sendSettingsConflict(ctx, currentRevision) {
10177
+ ctx.status = 409;
10178
+ ctx.body = {
10179
+ data: null,
10180
+ error: {
10181
+ status: 409,
10182
+ name: "ConflictError",
10183
+ message: "Settings were changed by another administrator. Reload and try again.",
10184
+ details: { revision: currentRevision }
10185
+ }
10186
+ };
10187
+ return ctx.body;
10188
+ }
9212
10189
  module2.exports = {
9213
10190
  /**
9214
10191
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -9225,8 +10202,10 @@ var require_settings = __commonJS({
9225
10202
  });
9226
10203
  const storedSettings = await pluginStore.get({ key: "settings" });
9227
10204
  const settings = mergeSettingsWithDefaults(storedSettings);
10205
+ const revision = await readRevision();
9228
10206
  ctx.send({
9229
10207
  settings,
10208
+ ...revision === null ? {} : { revision },
9230
10209
  success: true
9231
10210
  });
9232
10211
  } catch (error) {
@@ -9250,42 +10229,60 @@ var require_settings = __commonJS({
9250
10229
  * @returns {Promise<void>}
9251
10230
  */
9252
10231
  async updateSettings(ctx) {
9253
- let pluginStore;
9254
- let current;
9255
10232
  try {
9256
10233
  const { body } = ctx.request;
9257
10234
  if (!body || typeof body !== "object" || Array.isArray(body)) {
9258
10235
  return ctx.badRequest("Settings data must be an object");
9259
10236
  }
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);
10237
+ const hasBaseRevision = Object.prototype.hasOwnProperty.call(body, "revision");
10238
+ if (hasBaseRevision && !(Number.isInteger(body.revision) && body.revision >= 0)) {
10239
+ return sendValidationError(ctx, "Invalid settings", [
10240
+ { path: ["revision"], message: "revision must be a non-negative integer" }
10241
+ ]);
9273
10242
  }
9274
- await pluginStore.set({
9275
- key: "settings",
9276
- value: sanitizedSettings
10243
+ const outcome = await withPluginStoreKey(strapi, "settings", async (pluginStore) => {
10244
+ if (hasBaseRevision) {
10245
+ const currentRevision = await readRevision();
10246
+ if (currentRevision !== null && currentRevision !== body.revision) {
10247
+ return { conflict: true, currentRevision };
10248
+ }
10249
+ }
10250
+ const stored = await pluginStore.get({ key: "settings" });
10251
+ const storedObject = stored && typeof stored === "object" ? stored : {};
10252
+ const current = {
10253
+ ...mergeSettingsWithDefaults(storedObject),
10254
+ geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
10255
+ };
10256
+ const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
10257
+ if (errors.length > 0) return { errors };
10258
+ await pluginStore.set({
10259
+ key: "settings",
10260
+ value: sanitizedSettings
10261
+ });
10262
+ const revision = await notifySettingsChanged(strapi);
10263
+ return { settings: sanitizedSettings, revision };
9277
10264
  });
9278
- invalidateSettingsCache();
10265
+ if (outcome.conflict) {
10266
+ return sendSettingsConflict(ctx, outcome.currentRevision);
10267
+ }
10268
+ if (outcome.errors) {
10269
+ return sendValidationError(ctx, "Invalid settings", outcome.errors);
10270
+ }
9279
10271
  strapi.log.info("[magic-sessionmanager/settings] Settings updated successfully");
9280
10272
  ctx.send({
9281
10273
  settings: {
9282
- ...sanitizedSettings,
9283
- geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
10274
+ ...outcome.settings,
10275
+ geoIpDatabasePath: getSafeGeoIpFilename(outcome.settings.geoIpDatabasePath)
9284
10276
  },
10277
+ ...outcome.revision === null || outcome.revision === void 0 ? {} : { revision: outcome.revision },
9285
10278
  success: true,
9286
10279
  message: "Settings saved successfully!"
9287
10280
  });
9288
10281
  } catch (error) {
10282
+ if (error instanceof LockTimeoutError) {
10283
+ strapi.log.warn("[magic-sessionmanager/settings] Settings are being saved elsewhere");
10284
+ return sendServerError(ctx, 503, "Settings are being saved by another request");
10285
+ }
9289
10286
  strapi.log.error(
9290
10287
  "[magic-sessionmanager/settings] Error updating settings:",
9291
10288
  error?.name || "Error"
@@ -9320,6 +10317,8 @@ var require_geoip = __commonJS({
9320
10317
  normalizeGeoIpDatabasePath
9321
10318
  } = require_settings_loader();
9322
10319
  var { sendServerError } = require_http_errors();
10320
+ var { setPluginStoreValue } = require_plugin_store();
10321
+ var { getHostFingerprint } = require_coordination();
9323
10322
  var CREDENTIALS_KEY = "geoipCredentials";
9324
10323
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
9325
10324
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -9342,11 +10341,7 @@ var require_geoip = __commonJS({
9342
10341
  };
9343
10342
  }
9344
10343
  async function setStoredCredentials(strapi2, credentials) {
9345
- const store = getGeoIpStore(strapi2);
9346
- await store.set({
9347
- key: CREDENTIALS_KEY,
9348
- value: credentials
9349
- });
10344
+ await setPluginStoreValue(strapi2, CREDENTIALS_KEY, credentials);
9350
10345
  }
9351
10346
  function getCredentialSource(storedCredentials) {
9352
10347
  if (process.env.MAXMIND_ACCOUNT_ID && process.env.MAXMIND_LICENSE_KEY) {
@@ -9413,7 +10408,12 @@ var require_geoip = __commonJS({
9413
10408
  metadata,
9414
10409
  hasCredentials: credentialSource !== "missing",
9415
10410
  credentialSource,
9416
- accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || ""
10411
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
10412
+ // The MMDB file lives on the local disk of the instance that
10413
+ // answered. In multi-instance deployments each instance reports
10414
+ // its own file; `instance` is a non-reversible host fingerprint.
10415
+ scope: "instance",
10416
+ instance: getHostFingerprint()
9417
10417
  }
9418
10418
  });
9419
10419
  } catch (error) {
@@ -9644,6 +10644,7 @@ var require_session2 = __commonJS({
9644
10644
  if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9645
10645
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9646
10646
  if (!revoked) {
10647
+ if (!await nativeManager.isSessionActive(nativeSessionId)) return false;
9647
10648
  throw new Error(
9648
10649
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9649
10650
  );
@@ -9674,7 +10675,10 @@ var require_session2 = __commonJS({
9674
10675
  }
9675
10676
  if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
9676
10677
  const revoked = await nativeManager.revokeSessionById(userId, parsed.nativeSessionId);
9677
- if (!revoked) throw new Error("Native session revocation was not confirmed.");
10678
+ if (!revoked) {
10679
+ if (!await nativeManager.isSessionActive(parsed.nativeSessionId)) return false;
10680
+ throw new Error("Native session revocation was not confirmed.");
10681
+ }
9678
10682
  return true;
9679
10683
  }
9680
10684
  async function listNativeSessionsForUser(nativeManager, user, linkedIds = /* @__PURE__ */ new Set()) {
@@ -9811,6 +10815,7 @@ var require_session2 = __commonJS({
9811
10815
  if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9812
10816
  const revoked = await nativeManager.revokeSessionById(userId, nativeSessionId);
9813
10817
  if (!revoked) {
10818
+ if (!await nativeManager.isSessionActive(nativeSessionId)) continue;
9814
10819
  throw new Error(
9815
10820
  "Native session revocation was not confirmed; Magic session data was left unchanged."
9816
10821
  );
@@ -10415,8 +11420,13 @@ var require_session2 = __commonJS({
10415
11420
  if (ts < cutoff) this._lastTouchCache.delete(k);
10416
11421
  }
10417
11422
  }
10418
- await strapi2.documents(SESSION_UID).update({
10419
- documentId: sessionDocId,
11423
+ const staleBefore = new Date(now.getTime() - rateLimit);
11424
+ await strapi2.db.query(SESSION_UID).updateMany({
11425
+ where: {
11426
+ documentId: sessionDocId,
11427
+ isActive: true,
11428
+ $or: [{ lastActive: { $lt: staleBefore } }, { lastActive: { $null: true } }]
11429
+ },
10420
11430
  data: { lastActive: now }
10421
11431
  });
10422
11432
  log.debug("[TOUCH] End-user session lastActive updated");
@@ -10506,9 +11516,24 @@ var require_session2 = __commonJS({
10506
11516
  let deactivatedCount = 0;
10507
11517
  for (const session of sessionsToDeactivate) {
10508
11518
  try {
10509
- if (nativeManager) await revokeNativeSessionForSidecar(nativeManager, session);
10510
- await strapi2.documents(SESSION_UID).update({
11519
+ const idleWhere = {
10511
11520
  documentId: session.documentId,
11521
+ isActive: true,
11522
+ $or: [
11523
+ { lastActive: { $lt: cutoffTime } },
11524
+ { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
11525
+ ]
11526
+ };
11527
+ if (nativeManager) {
11528
+ const stillIdle = await strapi2.documents(SESSION_UID).findFirst({
11529
+ filters: idleWhere,
11530
+ fields: ["documentId"]
11531
+ });
11532
+ if (!stillIdle) continue;
11533
+ await revokeNativeSessionForSidecar(nativeManager, session);
11534
+ }
11535
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
11536
+ where: idleWhere,
10512
11537
  data: {
10513
11538
  isActive: false,
10514
11539
  terminatedManually: false,
@@ -10516,7 +11541,7 @@ var require_session2 = __commonJS({
10516
11541
  logoutTime: now
10517
11542
  }
10518
11543
  });
10519
- deactivatedCount++;
11544
+ if (Number(result?.count) === 1) deactivatedCount++;
10520
11545
  } catch (err) {
10521
11546
  log.debug("[CLEANUP] Failed to deactivate an end-user session:", err?.name || "Error");
10522
11547
  }
@@ -10707,7 +11732,7 @@ var require_session2 = __commonJS({
10707
11732
  var require_package = __commonJS({
10708
11733
  "package.json"(exports2, module2) {
10709
11734
  module2.exports = {
10710
- version: "4.9.1",
11735
+ version: "4.10.0",
10711
11736
  keywords: [
10712
11737
  "strapi",
10713
11738
  "plugin",
@@ -10755,6 +11780,7 @@ var require_package = __commonJS({
10755
11780
  scripts: {
10756
11781
  clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`,
10757
11782
  test: "node --test tests/*.test.js tests/*.test.mjs",
11783
+ "test:concurrency": "node scripts/concurrency/run.mjs",
10758
11784
  "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
10759
11785
  "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
10760
11786
  lint: "eslint .",
@@ -10785,11 +11811,13 @@ var require_package = __commonJS({
10785
11811
  "@strapi/icons": "^2.2.4",
10786
11812
  "@strapi/sdk-plugin": "^6.1.1",
10787
11813
  "@strapi/strapi": "5.61.0",
11814
+ "better-sqlite3": "^13.0.3",
10788
11815
  esbuild: "^0.28.2",
10789
11816
  eslint: "^10.14.0",
10790
11817
  "eslint-config-prettier": "^10.1.8",
10791
11818
  "eslint-plugin-react-hooks": "^7.1.1",
10792
11819
  globals: "^17.14.0",
11820
+ pg: "^8.23.1",
10793
11821
  prettier: "^3.9.10",
10794
11822
  react: "^18.3.1",
10795
11823
  "react-dom": "^18.3.1",
@@ -10843,6 +11871,7 @@ var require_license_guard = __commonJS({
10843
11871
  var os = require("os");
10844
11872
  var pluginPkg = require_package();
10845
11873
  var { createLogger } = require_logger();
11874
+ var { setPluginStoreValue, withPluginStoreKey } = require_plugin_store();
10846
11875
  var DEFAULT_LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
10847
11876
  var envTimeout = Number(process.env.MAGIC_LICENSE_TIMEOUT_MS);
10848
11877
  var DEFAULT_FETCH_TIMEOUT_MS = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 12e3;
@@ -10876,29 +11905,30 @@ var require_license_guard = __commonJS({
10876
11905
  },
10877
11906
  async generateDeviceId() {
10878
11907
  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
- }
11908
+ return await withPluginStoreKey(strapi2, "deviceId", async (pluginStore) => {
11909
+ const stored = await pluginStore.get({ key: "deviceId" });
11910
+ if (stored && typeof stored === "string" && stored.length >= 16) {
11911
+ return stored;
11912
+ }
11913
+ let identifier;
11914
+ try {
11915
+ const networkInterfaces = os.networkInterfaces();
11916
+ const macAddresses = [];
11917
+ Object.values(networkInterfaces).forEach((interfaces) => {
11918
+ interfaces?.forEach((iface) => {
11919
+ if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
11920
+ macAddresses.push(iface.mac);
11921
+ }
11922
+ });
10893
11923
  });
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;
11924
+ identifier = `${macAddresses.join("-")}-${os.hostname()}`;
11925
+ } catch {
11926
+ identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
11927
+ }
11928
+ const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
11929
+ await pluginStore.set({ key: "deviceId", value: deviceId });
11930
+ return deviceId;
11931
+ });
10902
11932
  } catch {
10903
11933
  return crypto.randomBytes(16).toString("hex");
10904
11934
  }
@@ -10980,8 +12010,7 @@ var require_license_guard = __commonJS({
10980
12010
  );
10981
12011
  const data = await response.json();
10982
12012
  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() });
12013
+ await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
10985
12014
  return { valid: true, data: data.data };
10986
12015
  }
10987
12016
  return { valid: false, data: null };
@@ -11014,9 +12043,8 @@ var require_license_guard = __commonJS({
11014
12043
  return null;
11015
12044
  },
11016
12045
  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() });
12046
+ await setPluginStoreValue(strapi2, "licenseKey", licenseKey);
12047
+ await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
11020
12048
  log.info("[SUCCESS] License key stored");
11021
12049
  return true;
11022
12050
  },
@@ -11069,6 +12097,7 @@ var require_geolocation = __commonJS({
11069
12097
  var net = require("node:net");
11070
12098
  var path = require("node:path");
11071
12099
  var { getPluginSettings } = require_settings_loader();
12100
+ var { getCoordinator, hashedKey } = require_coordination();
11072
12101
  var { resolveDatabaseTarget } = require_geoip_updater();
11073
12102
  var GEO_API_TIMEOUT_MS = 4e3;
11074
12103
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -11077,6 +12106,7 @@ var require_geolocation = __commonJS({
11077
12106
  var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
11078
12107
  var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
11079
12108
  var IPAPI_MAX_QUEUE_SIZE = 50;
12109
+ var SHARED_BACKOFF_KEY = "geo:ipapi:backoff";
11080
12110
  var DEFAULT_CITY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
11081
12111
  var DEFAULT_COUNTRY_MMDB_PATH = resolveDatabaseTarget("GeoLite2-Country.mmdb");
11082
12112
  var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
@@ -11153,6 +12183,50 @@ var require_geolocation = __commonJS({
11153
12183
  expiresAt: Date.now() + ttlMs
11154
12184
  });
11155
12185
  }
12186
+ async function getSharedIpapiResult(strapiInstance, lookupIp) {
12187
+ try {
12188
+ const data = await getCoordinator(strapiInstance).cacheGet(hashedKey("geo:ipapi", lookupIp));
12189
+ return data && typeof data === "object" ? { ...data, ip: lookupIp } : null;
12190
+ } catch {
12191
+ return null;
12192
+ }
12193
+ }
12194
+ async function shareIpapiResult(strapiInstance, lookupIp, data, ttlMs) {
12195
+ if (!lookupIp || !data || ttlMs <= 0) return;
12196
+ try {
12197
+ const { ip: _ip, ...withoutIp } = data;
12198
+ await getCoordinator(strapiInstance).cacheSet(
12199
+ hashedKey("geo:ipapi", lookupIp),
12200
+ withoutIp,
12201
+ ttlMs
12202
+ );
12203
+ } catch {
12204
+ }
12205
+ }
12206
+ async function cacheIpapiResultEverywhere(strapiInstance, lookupIp, data, ttlMs) {
12207
+ cacheIpapiResult(lookupIp, data, ttlMs);
12208
+ await shareIpapiResult(strapiInstance, lookupIp, data, ttlMs);
12209
+ }
12210
+ async function syncSharedIpapiBackoff(strapiInstance) {
12211
+ try {
12212
+ const until = Number(await getCoordinator(strapiInstance).cacheGet(SHARED_BACKOFF_KEY));
12213
+ if (Number.isFinite(until) && until > ipapiRateLimitedUntil) ipapiRateLimitedUntil = until;
12214
+ } catch {
12215
+ }
12216
+ return getIpapiRateLimitRemainingMs();
12217
+ }
12218
+ async function shareIpapiBackoff(strapiInstance) {
12219
+ const remaining = getIpapiRateLimitRemainingMs();
12220
+ if (remaining <= 0) return;
12221
+ try {
12222
+ await getCoordinator(strapiInstance).cacheSet(
12223
+ SHARED_BACKOFF_KEY,
12224
+ ipapiRateLimitedUntil,
12225
+ remaining
12226
+ );
12227
+ } catch {
12228
+ }
12229
+ }
11156
12230
  function getRetryAfterMs(response) {
11157
12231
  const retryAfter = response?.headers?.get?.("retry-after");
11158
12232
  if (!retryAfter) return null;
@@ -11459,7 +12533,12 @@ var require_geolocation = __commonJS({
11459
12533
  }
11460
12534
  const cached = getCachedIpapiResult(lookupIp);
11461
12535
  if (cached) return cached;
11462
- const rateLimitRemainingMs = getIpapiRateLimitRemainingMs();
12536
+ const shared = await getSharedIpapiResult(strapi2, lookupIp);
12537
+ if (shared) {
12538
+ cacheIpapiResult(lookupIp, shared, IPAPI_FAILURE_CACHE_TTL_MS);
12539
+ return cloneGeoData(shared);
12540
+ }
12541
+ const rateLimitRemainingMs = await syncSharedIpapiBackoff(strapi2);
11463
12542
  if (rateLimitRemainingMs > 0) {
11464
12543
  logIpapiRateLimit(
11465
12544
  strapi2,
@@ -11484,7 +12563,7 @@ var require_geolocation = __commonJS({
11484
12563
  "ipapi",
11485
12564
  "Remote GeoIP provider concurrency limit reached"
11486
12565
  );
11487
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12566
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11488
12567
  return fallback;
11489
12568
  }
11490
12569
  const queuedRateLimitRemainingMs = getIpapiRateLimitRemainingMs();
@@ -11513,6 +12592,7 @@ var require_geolocation = __commonJS({
11513
12592
  const reason = response.status === 429 ? "rate_limited" : "error";
11514
12593
  if (response.status === 429) {
11515
12594
  const backoffMs = markIpapiRateLimited(response);
12595
+ await shareIpapiBackoff(strapi2);
11516
12596
  logIpapiRateLimit(
11517
12597
  strapi2,
11518
12598
  `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11528,7 +12608,7 @@ var require_geolocation = __commonJS({
11528
12608
  "ipapi",
11529
12609
  `HTTP ${response.status}`
11530
12610
  );
11531
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12611
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11532
12612
  return fallback;
11533
12613
  }
11534
12614
  const data = await response.json();
@@ -11536,6 +12616,7 @@ var require_geolocation = __commonJS({
11536
12616
  const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
11537
12617
  if (reason === "rate_limited") {
11538
12618
  const backoffMs = markIpapiRateLimited();
12619
+ await shareIpapiBackoff(strapi2);
11539
12620
  logIpapiRateLimit(
11540
12621
  strapi2,
11541
12622
  `[magic-sessionmanager/geolocation] API reported rate limit; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
@@ -11544,7 +12625,7 @@ var require_geolocation = __commonJS({
11544
12625
  strapi2.log.warn("[magic-sessionmanager/geolocation] Provider rejected the lookup");
11545
12626
  }
11546
12627
  const fallback = this.getFallbackData(lookupIp, reason, "ipapi", data.reason);
11547
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12628
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11548
12629
  return fallback;
11549
12630
  }
11550
12631
  const result = {
@@ -11581,7 +12662,7 @@ var require_geolocation = __commonJS({
11581
12662
  _source: "ipapi"
11582
12663
  };
11583
12664
  strapi2.log.debug("[magic-sessionmanager/geolocation] ipapi lookup completed");
11584
- cacheIpapiResult(lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
12665
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
11585
12666
  return result;
11586
12667
  } catch (error) {
11587
12668
  const status = error?.name === "AbortError" ? "error" : "error";
@@ -11590,7 +12671,7 @@ var require_geolocation = __commonJS({
11590
12671
  error?.name || "Error"
11591
12672
  );
11592
12673
  const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
11593
- cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
12674
+ await cacheIpapiResultEverywhere(strapi2, lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11594
12675
  return fallback;
11595
12676
  } finally {
11596
12677
  clearTimeout(timer);
@@ -12177,12 +13258,7 @@ var require_rate_limit = __commonJS({
12177
13258
  "server/src/middlewares/rate-limit.js"(exports2, module2) {
12178
13259
  "use strict";
12179
13260
  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
- };
13261
+ var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
12186
13262
  var callerKey = (ctx) => {
12187
13263
  const userId = ctx.state?.user?.id;
12188
13264
  if (userId) return `u:${userId}`;
@@ -12202,15 +13278,7 @@ var require_rate_limit = __commonJS({
12202
13278
  const normalizedPath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") || "/" : rawPath;
12203
13279
  return `${method} path:${normalizedPath}`;
12204
13280
  };
12205
- var RESOLVED_TTL_MS = 3e4;
12206
- var resolvedCache = /* @__PURE__ */ new Map();
12207
13281
  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
13282
  let settings;
12215
13283
  try {
12216
13284
  settings = await getPluginSettings(strapi2);
@@ -12238,7 +13306,6 @@ var require_rate_limit = __commonJS({
12238
13306
  } else {
12239
13307
  resolved = { max: routeMax, windowMs: routeWindowMs };
12240
13308
  }
12241
- resolvedCache.set(cacheKey, { ...resolved, at: now });
12242
13309
  return resolved;
12243
13310
  }
12244
13311
  var rateLimit = (cfg = {}, { strapi: strapi2 }) => {
@@ -12247,17 +13314,12 @@ var require_rate_limit = __commonJS({
12247
13314
  const profile = cfg.profile === "read" || cfg.profile === "write" ? cfg.profile : null;
12248
13315
  return async (ctx, next) => {
12249
13316
  const { max, windowMs } = profile ? await resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) : { max: routeMax, windowMs: routeWindowMs };
12250
- const key = `${routeKey(ctx)}::${callerKey(ctx)}`;
13317
+ const key = hashedKey("rl", `${routeKey(ctx)}::${callerKey(ctx)}`);
12251
13318
  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);
13319
+ const entry = await getCoordinator(strapi2).hit(key, windowMs);
13320
+ const expiresAt = entry.windowStart + windowMs;
13321
+ if (entry.hits > max) {
13322
+ const retryAfterSec = Math.max(1, Math.ceil((expiresAt - now) / 1e3));
12261
13323
  ctx.set("Retry-After", String(retryAfterSec));
12262
13324
  strapi2.log.warn("[magic-sessionmanager] Content API rate limit exceeded");
12263
13325
  ctx.status = 429;
@@ -12279,8 +13341,7 @@ var require_rate_limit = __commonJS({
12279
13341
  resolveLimits,
12280
13342
  routeKey,
12281
13343
  reset() {
12282
- buckets.clear();
12283
- resolvedCache.clear();
13344
+ __resetMemoryForTests();
12284
13345
  }
12285
13346
  };
12286
13347
  module2.exports = rateLimit;