strapi-plugin-magic-sessionmanager 4.7.2 → 4.9.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 (71) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +380 -663
  3. package/dist/admin/Analytics-B6d-39Qh.js +420 -0
  4. package/dist/admin/Analytics-DxOWXHn8.mjs +418 -0
  5. package/dist/admin/App-ZsSGj7n8.mjs +1894 -0
  6. package/dist/admin/App-mRFV50K6.js +1896 -0
  7. package/dist/admin/License-BE6UQ_V3.mjs +443 -0
  8. package/dist/admin/License-DXt2oi6u.js +443 -0
  9. package/dist/admin/OnlineUsersWidget-CFvM3Vbp.js +273 -0
  10. package/dist/admin/OnlineUsersWidget-_tJ6aeWl.mjs +254 -0
  11. package/dist/admin/SectionCard-BlWv8CRt.js +54 -0
  12. package/dist/admin/SectionCard-D51bv4Hi.mjs +55 -0
  13. package/dist/admin/Settings-BUc12TP5.js +3570 -0
  14. package/dist/admin/Settings-dtW7cjTX.mjs +3568 -0
  15. package/dist/admin/de-BFKoGEVT.js +544 -0
  16. package/dist/admin/de-j0oZH9Pz.mjs +544 -0
  17. package/dist/admin/en-UY4Tb5tE.mjs +544 -0
  18. package/dist/admin/en-s7Ksdkcg.js +544 -0
  19. package/dist/admin/es-07OGMe_5.js +544 -0
  20. package/dist/admin/es-DGBcZwQy.mjs +544 -0
  21. package/dist/admin/fr-B6-DWhGO.mjs +544 -0
  22. package/dist/admin/fr-ETj_2UBY.js +544 -0
  23. package/dist/admin/index-C_SyRULc.mjs +1750 -0
  24. package/dist/admin/index-D4kEnXSp.js +1751 -0
  25. package/dist/admin/index.js +1 -1
  26. package/dist/admin/index.mjs +2 -2
  27. package/dist/admin/maskSensitiveValue-BWcSjow7.js +9 -0
  28. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +10 -0
  29. package/dist/admin/pt-C7PwrQtV.js +544 -0
  30. package/dist/admin/pt-YMRLm9gx.mjs +544 -0
  31. package/dist/server/index.js +3555 -6350
  32. package/dist/server/index.mjs +3555 -6350
  33. package/package.json +30 -19
  34. package/pics/analytics.png +0 -0
  35. package/pics/dashboard-dark.png +0 -0
  36. package/pics/dashboard.png +0 -0
  37. package/pics/dashboardsessionmodal.png +0 -0
  38. package/pics/mobile-dashboard.png +0 -0
  39. package/pics/mobile-session.png +0 -0
  40. package/pics/sessioninfopanel.png +0 -0
  41. package/pics/settings1.png +0 -0
  42. package/pics/settings2.png +0 -0
  43. package/pics/widget.png +0 -0
  44. package/scripts/geoip-updater.cjs +266 -36
  45. package/scripts/update-geoip-db.mjs +3 -0
  46. package/dist/admin/Analytics-CsrpxJwQ.mjs +0 -497
  47. package/dist/admin/Analytics-D03ZNNMR.js +0 -499
  48. package/dist/admin/App-B2VCS3cz.js +0 -1481
  49. package/dist/admin/App-qxKnK7G2.mjs +0 -1479
  50. package/dist/admin/License-ClW7sZLR.mjs +0 -318
  51. package/dist/admin/License-fixnQ7wF.js +0 -320
  52. package/dist/admin/OnlineUsersWidget-mR_OMiwi.mjs +0 -185
  53. package/dist/admin/OnlineUsersWidget-qb9utPBy.js +0 -185
  54. package/dist/admin/Settings-U3V4eGMo.mjs +0 -2038
  55. package/dist/admin/Settings-gv2BF54w.js +0 -2040
  56. package/dist/admin/StyledButtons-Cz8oYhmc.mjs +0 -418
  57. package/dist/admin/StyledButtons-DDuxnYz8.js +0 -419
  58. package/dist/admin/de-BnqGCokx.js +0 -316
  59. package/dist/admin/de-JBE-iylO.mjs +0 -316
  60. package/dist/admin/en-BRmVwd8-.js +0 -316
  61. package/dist/admin/en-kQWtdEai.mjs +0 -316
  62. package/dist/admin/es-CH691xcL.js +0 -301
  63. package/dist/admin/es-DOQvBxih.mjs +0 -301
  64. package/dist/admin/fr-CLExO0w_.js +0 -301
  65. package/dist/admin/fr-CmfCpepX.mjs +0 -301
  66. package/dist/admin/index-B_lFjUAg.mjs +0 -551
  67. package/dist/admin/index-Duc7cR_d.js +0 -552
  68. package/dist/admin/pt-BJ_F0yNi.js +0 -301
  69. package/dist/admin/pt-BSzZdyAH.mjs +0 -301
  70. package/dist/admin/sessionStatus-D_fWEzgj.js +0 -11
  71. package/dist/admin/sessionStatus-kwggjEMw.mjs +0 -12
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.2",
2
+ "version": "4.9.0",
3
3
  "keywords": [
4
4
  "strapi",
5
5
  "plugin",
@@ -41,12 +41,18 @@
41
41
  "pics"
42
42
  ],
43
43
  "engines": {
44
- "node": ">=20.0.0 <=26.x.x",
44
+ "node": "^22.22.2 || >=24.15.0",
45
45
  "npm": ">=6.0.0"
46
46
  },
47
47
  "scripts": {
48
48
  "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
49
49
  "test": "node --test tests/*.test.js tests/*.test.mjs",
50
+ "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
51
+ "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
52
+ "lint": "eslint .",
53
+ "lint:fix": "eslint . --fix",
54
+ "format": "prettier --write .",
55
+ "format:check": "prettier --check .",
50
56
  "build": "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
51
57
  "watch": "strapi-plugin watch",
52
58
  "watch:link": "strapi-plugin watch:link",
@@ -56,28 +62,33 @@
56
62
  "prepublishOnly": "npm test && npm run build && npm run verify && npm run verify:runtime"
57
63
  },
58
64
  "dependencies": {
59
- "@maxmind/geoip2-node": "^6.3.4",
60
- "sanitize-html": "^2.17.6"
65
+ "@maxmind/geoip2-node": "^7.1.0",
66
+ "sanitize-html": "^2.18.0"
61
67
  },
62
68
  "devDependencies": {
63
- "@semantic-release/changelog": "^6.0.3",
64
- "@semantic-release/commit-analyzer": "^13.0.0",
65
- "@semantic-release/git": "^10.0.1",
66
- "@semantic-release/github": "^12.0.9",
67
- "@semantic-release/npm": "^13.1.5",
69
+ "@eslint/js": "^10.0.1",
70
+ "@semantic-release/changelog": "^7.0.0",
71
+ "@semantic-release/commit-analyzer": "^13.0.1",
72
+ "@semantic-release/git": "^11.0.1",
73
+ "@semantic-release/github": "^12.0.10",
74
+ "@semantic-release/npm": "^13.2.0",
68
75
  "@semantic-release/release-notes-generator": "^14.1.1",
69
- "@strapi/design-system": "^2.2.2",
70
- "@strapi/icons": "^2.2.2",
76
+ "@strapi/design-system": "^2.2.4",
77
+ "@strapi/icons": "^2.2.4",
71
78
  "@strapi/sdk-plugin": "^6.1.1",
72
- "@strapi/strapi": "^5.50.1",
73
- "esbuild": "^0.28.1",
74
- "prettier": "^3.9.5",
79
+ "@strapi/strapi": "5.61.0",
80
+ "esbuild": "^0.28.2",
81
+ "eslint": "^10.14.0",
82
+ "eslint-config-prettier": "^10.1.8",
83
+ "eslint-plugin-react-hooks": "^7.1.1",
84
+ "globals": "^17.14.0",
85
+ "prettier": "^3.9.10",
75
86
  "react": "^18.3.1",
76
87
  "react-dom": "^18.3.1",
77
- "react-intl": "^7.1.14",
78
- "react-router-dom": "^6.30.4",
79
- "semantic-release": "^25.0.5",
80
- "styled-components": "^6.4.3"
88
+ "react-intl": "^6.8.9",
89
+ "react-router-dom": "^6.30.6",
90
+ "semantic-release": "^25.0.9",
91
+ "styled-components": "^6.6.0"
81
92
  },
82
93
  "peerDependencies": {
83
94
  "@strapi/design-system": "^2.0.0",
@@ -86,7 +97,7 @@
86
97
  "@strapi/utils": "^5.0.0",
87
98
  "react": "^18.3.1",
88
99
  "react-dom": "^18.3.1",
89
- "react-intl": "^7.0.0",
100
+ "react-intl": "^6.0.0",
90
101
  "react-router-dom": "^6.0.0",
91
102
  "styled-components": "^6.0.0"
92
103
  },
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/pics/widget.png CHANGED
Binary file
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('node:fs/promises');
4
+ const crypto = require('node:crypto');
4
5
  const path = require('node:path');
5
6
  const process = require('node:process');
6
7
  const zlib = require('node:zlib');
@@ -10,18 +11,120 @@ const gunzip = promisify(zlib.gunzip);
10
11
 
11
12
  const DEFAULT_EDITION_ID = 'GeoLite2-City';
12
13
  const DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
13
- const DEFAULT_OUTPUT_PATH = path.resolve(process.cwd(), 'data', DEFAULT_MMDB_NAME);
14
+ const DEFAULT_GEOIP_DIRECTORY = path.resolve(
15
+ process.cwd(),
16
+ 'data',
17
+ 'magic-sessionmanager',
18
+ 'geoip'
19
+ );
20
+ const DEFAULT_OUTPUT_PATH = path.join(DEFAULT_GEOIP_DIRECTORY, DEFAULT_MMDB_NAME);
14
21
  const SUPPORTED_EDITION_IDS = new Set([
15
22
  'GeoLite2-City',
16
23
  'GeoLite2-Country',
17
24
  'GeoIP2-City',
18
25
  'GeoIP2-Country',
19
26
  ]);
27
+ const SUPPORTED_MMDB_NAMES = new Set(
28
+ [...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`)
29
+ );
30
+
31
+ /**
32
+ * Resolves a supported MMDB filename into the plugin's dedicated database
33
+ * directory. Absolute paths are accepted only when they already target that
34
+ * exact directory; nested paths, traversal and other directories are rejected.
35
+ *
36
+ * @param {string} [value] Filename or canonical path to an MMDB file
37
+ * @param {string} [directory] Dedicated database directory
38
+ * @returns {string} Lexically resolved MMDB destination
39
+ * @throws {Error} When the destination escapes the dedicated directory
40
+ */
41
+ function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
42
+ const root = path.resolve(directory);
43
+ if (value !== undefined && typeof value !== 'string') {
44
+ throw new Error('GeoIP database path must be a string');
45
+ }
46
+ const requested = typeof value === 'string' && value.trim() ? value.trim() : DEFAULT_MMDB_NAME;
47
+ let filename;
48
+
49
+ if (path.isAbsolute(requested)) {
50
+ const absolute = path.resolve(requested);
51
+ if (path.dirname(absolute) !== root) {
52
+ throw new Error('GeoIP database path must stay inside the dedicated GeoIP directory');
53
+ }
54
+ filename = path.basename(absolute);
55
+ } else {
56
+ if (path.basename(requested) !== requested || requested === '.' || requested === '..') {
57
+ throw new Error('GeoIP database path must stay inside the dedicated GeoIP directory');
58
+ }
59
+ filename = requested;
60
+ }
61
+
62
+ if (!SUPPORTED_MMDB_NAMES.has(filename)) {
63
+ throw new Error('GeoIP database path must use a supported MMDB filename');
64
+ }
65
+
66
+ return path.join(root, filename);
67
+ }
68
+
69
+ /**
70
+ * Creates and canonicalizes the dedicated GeoIP directory, then rejects
71
+ * symlinked directories, database files or metadata sidecars before a provider
72
+ * request occurs.
73
+ *
74
+ * @param {string} [value] Filename or canonical path to an MMDB file
75
+ * @param {string} [directory] Dedicated database directory
76
+ * @returns {Promise<string>} Canonical MMDB destination
77
+ * @throws {Error} When the directory, database or sidecar is unsafe
78
+ */
79
+ async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
80
+ const root = path.resolve(directory);
81
+ const target = resolveDatabaseTarget(value, root);
82
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
83
+
84
+ const rootStat = await fs.lstat(root);
85
+ const canonicalRoot = await fs.realpath(root);
86
+ if (rootStat.isSymbolicLink()) {
87
+ throw new Error('GeoIP database directory must not be a symlink');
88
+ }
89
+ const canonicalTarget = path.join(canonicalRoot, path.basename(target));
90
+
91
+ for (const candidate of [canonicalTarget, `${canonicalTarget}.metadata.json`]) {
92
+ try {
93
+ const stat = await fs.lstat(candidate);
94
+ if (stat.isSymbolicLink()) {
95
+ throw new Error('GeoIP database destination must not be a symlink');
96
+ }
97
+ if (!stat.isFile()) {
98
+ throw new Error('GeoIP database destination must be a regular file');
99
+ }
100
+ if (path.dirname(await fs.realpath(candidate)) !== canonicalRoot) {
101
+ throw new Error('GeoIP database destination is outside the canonical directory');
102
+ }
103
+ } catch (error) {
104
+ if (error.code !== 'ENOENT') throw error;
105
+ }
106
+ }
107
+
108
+ return canonicalTarget;
109
+ }
20
110
 
111
+ /**
112
+ * Selects a supported MaxMind edition or uses the configured safe default.
113
+ *
114
+ * @param {string} value Requested edition identifier
115
+ * @param {string} [fallback=DEFAULT_EDITION_ID] Fallback edition
116
+ * @returns {string} Supported edition identifier
117
+ */
21
118
  function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
22
119
  return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
23
120
  }
24
121
 
122
+ /**
123
+ * Infers the MaxMind edition from a database filename.
124
+ *
125
+ * @param {string} filePath Candidate MMDB path
126
+ * @returns {string} Supported edition identifier, or an empty string
127
+ */
25
128
  function inferEditionIdFromPath(filePath) {
26
129
  if (typeof filePath !== 'string' || filePath.trim() === '') return '';
27
130
 
@@ -36,14 +139,36 @@ function inferEditionIdFromPath(filePath) {
36
139
  return '';
37
140
  }
38
141
 
142
+ /**
143
+ * Builds the fixed MaxMind download endpoint for a supported edition.
144
+ *
145
+ * @param {string} [editionId=DEFAULT_EDITION_ID] MaxMind edition
146
+ * @returns {string} MaxMind archive URL
147
+ */
39
148
  function buildDownloadUrl(editionId = DEFAULT_EDITION_ID) {
40
149
  return `https://download.maxmind.com/geoip/databases/${encodeURIComponent(editionId)}/download?suffix=tar.gz`;
41
150
  }
42
151
 
152
+ /**
153
+ * Encodes MaxMind credentials for the updater request header.
154
+ *
155
+ * @param {string} accountId MaxMind account identifier
156
+ * @param {string} licenseKey MaxMind license key
157
+ * @returns {string} Basic authorization header value
158
+ */
43
159
  function buildBasicAuthHeader(accountId, licenseKey) {
44
160
  return `Basic ${Buffer.from(`${accountId}:${licenseKey}`).toString('base64')}`;
45
161
  }
46
162
 
163
+ /**
164
+ * Builds updater configuration and confines its output to the GeoIP directory.
165
+ *
166
+ * @param {NodeJS.ProcessEnv} [env=process.env] Environment values
167
+ * @param {string[]} [argv=process.argv.slice(2)] CLI arguments
168
+ * @param {object} [overrides] Explicit test or caller overrides
169
+ * @returns {object} Validated updater configuration
170
+ * @throws {Error} When a requested output path escapes its dedicated directory
171
+ */
47
172
  function resolveConfig(env = process.env, argv = process.argv.slice(2), overrides = {}) {
48
173
  const force = argv.includes('--force') || overrides.force === true;
49
174
  const configuredOutputPath =
@@ -53,11 +178,15 @@ function resolveConfig(env = process.env, argv = process.argv.slice(2), override
53
178
  '';
54
179
  const editionId = normalizeEditionId(
55
180
  overrides.editionId ||
56
- env.MAXMIND_EDITION_ID ||
57
- inferEditionIdFromPath(configuredOutputPath) ||
58
- DEFAULT_EDITION_ID
181
+ env.MAXMIND_EDITION_ID ||
182
+ inferEditionIdFromPath(configuredOutputPath) ||
183
+ DEFAULT_EDITION_ID
184
+ );
185
+ const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
186
+ const outputPath = resolveDatabaseTarget(
187
+ configuredOutputPath || `${editionId}.mmdb`,
188
+ databaseDirectory
59
189
  );
60
- const outputPath = configuredOutputPath || path.resolve(process.cwd(), 'data', `${editionId}.mmdb`);
61
190
 
62
191
  return {
63
192
  accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || '',
@@ -69,18 +198,27 @@ function resolveConfig(env = process.env, argv = process.argv.slice(2), override
69
198
  };
70
199
  }
71
200
 
72
- function needsDownload({
73
- force,
74
- localExists,
75
- localMetadata,
76
- remoteLastModified,
77
- }) {
201
+ /**
202
+ * Decides whether the local database differs from the remote edition.
203
+ *
204
+ * @param {object} options Comparison inputs and force flag
205
+ * @returns {boolean} Whether the updater should fetch a fresh archive
206
+ */
207
+ function needsDownload({ force, localExists, localMetadata, remoteLastModified }) {
78
208
  if (force) return true;
79
209
  if (!localExists) return true;
80
210
  if (!remoteLastModified) return true;
81
211
  return localMetadata?.lastModified !== remoteLastModified;
82
212
  }
83
213
 
214
+ /**
215
+ * Extracts only the requested regular MMDB file from a MaxMind tar.gz archive.
216
+ *
217
+ * @param {Buffer} archiveBuffer Compressed archive bytes
218
+ * @param {string} [preferredFileName=DEFAULT_MMDB_NAME] Expected database file
219
+ * @returns {Promise<{name: string, data: Buffer}>} Archive entry and contents
220
+ * @throws {Error} When the expected regular file is absent
221
+ */
84
222
  async function extractMmdbFromTarGz(archiveBuffer, preferredFileName = DEFAULT_MMDB_NAME) {
85
223
  const tarBuffer = await gunzip(archiveBuffer);
86
224
  let offset = 0;
@@ -120,12 +258,26 @@ async function extractMmdbFromTarGz(archiveBuffer, preferredFileName = DEFAULT_M
120
258
  throw new Error(`No ${preferredFileName} file found in MaxMind archive`);
121
259
  }
122
260
 
261
+ /**
262
+ * Reads a null-terminated UTF-8 value from a fixed-width tar header field.
263
+ *
264
+ * @param {Buffer} buffer Tar header bytes
265
+ * @param {number} start Field offset
266
+ * @param {number} length Field width
267
+ * @returns {string} Decoded header field
268
+ */
123
269
  function readTarString(buffer, start, length) {
124
270
  const slice = buffer.subarray(start, start + length);
125
271
  const nullIndex = slice.indexOf(0);
126
272
  return slice.subarray(0, nullIndex === -1 ? slice.length : nullIndex).toString('utf8');
127
273
  }
128
274
 
275
+ /**
276
+ * Reads updater metadata, returning null for missing or invalid JSON files.
277
+ *
278
+ * @param {string} metadataPath Canonical sidecar file path
279
+ * @returns {Promise<object|null>} Parsed metadata or null
280
+ */
129
281
  async function readMetadata(metadataPath) {
130
282
  try {
131
283
  return JSON.parse(await fs.readFile(metadataPath, 'utf8'));
@@ -134,6 +286,12 @@ async function readMetadata(metadataPath) {
134
286
  }
135
287
  }
136
288
 
289
+ /**
290
+ * Checks whether a database file can be accessed.
291
+ *
292
+ * @param {string} filePath Canonical database file path
293
+ * @returns {Promise<boolean>} Whether the file exists and is accessible
294
+ */
137
295
  async function fileExists(filePath) {
138
296
  try {
139
297
  await fs.access(filePath);
@@ -143,6 +301,14 @@ async function fileExists(filePath) {
143
301
  }
144
302
  }
145
303
 
304
+ /**
305
+ * Requests remote edition metadata from the fixed MaxMind provider.
306
+ *
307
+ * @param {string} url MaxMind edition URL
308
+ * @param {string} authHeader Authorization value
309
+ * @returns {Promise<{lastModified: string, contentDisposition: string}>}
310
+ * @sideeffect Sends an authenticated HEAD request to MaxMind
311
+ */
146
312
  async function fetchHead(url, authHeader) {
147
313
  const response = await fetch(url, {
148
314
  method: 'HEAD',
@@ -163,6 +329,14 @@ async function fetchHead(url, authHeader) {
163
329
  };
164
330
  }
165
331
 
332
+ /**
333
+ * Downloads a MaxMind archive for the selected edition.
334
+ *
335
+ * @param {string} url MaxMind edition URL
336
+ * @param {string} authHeader Authorization value
337
+ * @returns {Promise<Buffer>} Archive bytes
338
+ * @sideeffect Sends an authenticated GET request to MaxMind
339
+ */
166
340
  async function fetchArchive(url, authHeader) {
167
341
  const response = await fetch(url, {
168
342
  method: 'GET',
@@ -180,59 +354,112 @@ async function fetchArchive(url, authHeader) {
180
354
  return Buffer.from(await response.arrayBuffer());
181
355
  }
182
356
 
357
+ /**
358
+ * Writes a new file through a unique, exclusive temporary file and atomic rename.
359
+ *
360
+ * @param {string} outputPath Canonical destination inside the GeoIP directory
361
+ * @param {Buffer|string} data Database or metadata contents
362
+ * @returns {Promise<void>}
363
+ * @sideeffect Creates and renames files in the destination directory
364
+ */
183
365
  async function writeAtomic(outputPath, data) {
184
366
  const directory = path.dirname(outputPath);
185
- await fs.mkdir(directory, { recursive: true });
367
+ const tempPath = path.join(directory, `.${path.basename(outputPath)}.${crypto.randomUUID()}.tmp`);
368
+ let handle;
369
+ try {
370
+ handle = await fs.open(tempPath, 'wx', 0o600);
371
+ await handle.writeFile(data);
372
+ await handle.sync();
373
+ } catch (error) {
374
+ await handle?.close().catch(() => {});
375
+ await fs.rm(tempPath, { force: true }).catch(() => {});
376
+ throw error;
377
+ }
378
+
379
+ try {
380
+ await handle.close();
381
+ } catch (error) {
382
+ await fs.rm(tempPath, { force: true }).catch(() => {});
383
+ throw error;
384
+ }
186
385
 
187
- const tempPath = `${outputPath}.${process.pid}.${Date.now()}.tmp`;
188
- await fs.writeFile(tempPath, data);
189
- await fs.rename(tempPath, outputPath);
386
+ try {
387
+ await fs.rename(tempPath, outputPath);
388
+ } catch (error) {
389
+ await fs.rm(tempPath, { force: true }).catch(() => {});
390
+ throw error;
391
+ }
190
392
  }
191
393
 
394
+ /**
395
+ * Downloads, validates and atomically installs a MaxMind MMDB edition.
396
+ * Destination validation happens before the first provider request.
397
+ *
398
+ * @param {object} [config=resolveConfig()] Credentials, edition and destination
399
+ * @returns {Promise<object>} Safe update result with the installed file path
400
+ * @sideeffect Contacts MaxMind and writes the MMDB plus metadata sidecar
401
+ * @throws {Error} When credentials, destination, archive or provider fail
402
+ */
192
403
  async function updateGeoIpDatabase(config = resolveConfig()) {
193
404
  if (!config.accountId || !config.licenseKey) {
194
405
  throw new Error('MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY are required');
195
406
  }
196
407
 
197
- const url = buildDownloadUrl(config.editionId);
408
+ const editionId = normalizeEditionId(config.editionId);
409
+ const outputPath = await canonicalizeDatabaseTarget(config.outputPath);
410
+ const mmdbFileName = `${editionId}.mmdb`;
411
+ if (path.basename(outputPath) !== mmdbFileName) {
412
+ throw new Error('GeoIP database filename must match the selected edition');
413
+ }
414
+
415
+ const url = buildDownloadUrl(editionId);
198
416
  const authHeader = buildBasicAuthHeader(config.accountId, config.licenseKey);
199
- const metadataPath = `${config.outputPath}.metadata.json`;
417
+ const metadataPath = `${outputPath}.metadata.json`;
200
418
 
201
419
  const [head, localMetadata, localExists] = await Promise.all([
202
420
  fetchHead(url, authHeader),
203
421
  readMetadata(metadataPath),
204
- fileExists(config.outputPath),
422
+ fileExists(outputPath),
205
423
  ]);
206
424
 
207
- if (!needsDownload({
208
- force: config.force,
209
- localExists,
210
- localMetadata,
211
- remoteLastModified: head.lastModified,
212
- })) {
425
+ if (
426
+ !needsDownload({
427
+ force: config.force,
428
+ localExists,
429
+ localMetadata,
430
+ remoteLastModified: head.lastModified,
431
+ })
432
+ ) {
213
433
  return {
214
434
  changed: false,
215
- outputPath: config.outputPath,
435
+ outputPath,
216
436
  lastModified: head.lastModified,
217
437
  message: 'GeoIP database is already current',
218
438
  };
219
439
  }
220
440
 
221
441
  const archive = await fetchArchive(url, authHeader);
222
- const extracted = await extractMmdbFromTarGz(archive, config.mmdbFileName);
223
-
224
- await writeAtomic(config.outputPath, extracted.data);
225
- await fs.writeFile(metadataPath, JSON.stringify({
226
- editionId: config.editionId,
227
- sourceFile: extracted.name,
228
- lastModified: head.lastModified,
229
- downloadedAt: new Date().toISOString(),
230
- sourceUrl: url,
231
- }, null, 2));
442
+ const extracted = await extractMmdbFromTarGz(archive, mmdbFileName);
443
+
444
+ await writeAtomic(outputPath, extracted.data);
445
+ await writeAtomic(
446
+ metadataPath,
447
+ JSON.stringify(
448
+ {
449
+ editionId,
450
+ sourceFile: extracted.name,
451
+ lastModified: head.lastModified,
452
+ downloadedAt: new Date().toISOString(),
453
+ sourceUrl: url,
454
+ },
455
+ null,
456
+ 2
457
+ )
458
+ );
232
459
 
233
460
  return {
234
461
  changed: true,
235
- outputPath: config.outputPath,
462
+ outputPath,
236
463
  sourceFile: extracted.name,
237
464
  lastModified: head.lastModified,
238
465
  message: 'GeoIP database updated',
@@ -241,15 +468,18 @@ async function updateGeoIpDatabase(config = resolveConfig()) {
241
468
 
242
469
  module.exports = {
243
470
  DEFAULT_EDITION_ID,
471
+ DEFAULT_GEOIP_DIRECTORY,
244
472
  DEFAULT_MMDB_NAME,
245
473
  DEFAULT_OUTPUT_PATH,
246
474
  buildBasicAuthHeader,
247
475
  buildDownloadUrl,
476
+ canonicalizeDatabaseTarget,
248
477
  extractMmdbFromTarGz,
249
478
  fileExists,
250
479
  inferEditionIdFromPath,
251
480
  needsDownload,
252
481
  readMetadata,
482
+ resolveDatabaseTarget,
253
483
  resolveConfig,
254
484
  updateGeoIpDatabase,
255
485
  };
@@ -7,15 +7,18 @@ const require = createRequire(import.meta.url);
7
7
  const updater = require('./geoip-updater.cjs');
8
8
 
9
9
  export const DEFAULT_EDITION_ID = updater.DEFAULT_EDITION_ID;
10
+ export const DEFAULT_GEOIP_DIRECTORY = updater.DEFAULT_GEOIP_DIRECTORY;
10
11
  export const DEFAULT_MMDB_NAME = updater.DEFAULT_MMDB_NAME;
11
12
  export const DEFAULT_OUTPUT_PATH = updater.DEFAULT_OUTPUT_PATH;
12
13
  export const buildBasicAuthHeader = updater.buildBasicAuthHeader;
13
14
  export const buildDownloadUrl = updater.buildDownloadUrl;
15
+ export const canonicalizeDatabaseTarget = updater.canonicalizeDatabaseTarget;
14
16
  export const extractMmdbFromTarGz = updater.extractMmdbFromTarGz;
15
17
  export const fileExists = updater.fileExists;
16
18
  export const inferEditionIdFromPath = updater.inferEditionIdFromPath;
17
19
  export const needsDownload = updater.needsDownload;
18
20
  export const readMetadata = updater.readMetadata;
21
+ export const resolveDatabaseTarget = updater.resolveDatabaseTarget;
19
22
  export const resolveConfig = updater.resolveConfig;
20
23
  export const updateGeoIpDatabase = updater.updateGeoIpDatabase;
21
24