Skip to content

Commit

Permalink
Use crypto.randomUUID now that the value is memoized
Browse files Browse the repository at this point in the history
  • Loading branch information
mike182uk committed Dec 11, 2024
1 parent 822966f commit 0e4fde0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
8 changes: 2 additions & 6 deletions ghost/core/core/shared/config/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,11 @@ let processTmpDirPath = null;
*
* @returns {string} - tmp dir path for the current process
*/
function getProcessTmpDirPath(config) {
function getProcessTmpDirPath() {
// Memoize the computed path to avoid re-computing it on each call - The
// value should not change during the lifetime of the process.
if (processTmpDirPath === null) {
const siteHash = crypto.createHash('md5')
.update(config.getSiteUrl())
.digest('hex');

processTmpDirPath = path.join(os.tmpdir(), `ghost_${siteHash}_${process.pid}`);
processTmpDirPath = path.join(os.tmpdir(), `ghost_${crypto.randomUUID()}`);
}

return processTmpDirPath;
Expand Down
29 changes: 19 additions & 10 deletions ghost/core/test/unit/shared/config/helpers.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const crypto = require('crypto');
const os = require('os');
const path = require('path');
const should = require('should');

const configUtils = require('../../../utils/configUtils');

const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;

describe('vhost utils', function () {
beforeEach(function () {
configUtils.set('url', 'http://ghost.blog');
Expand Down Expand Up @@ -59,17 +59,26 @@ describe('vhost utils', function () {

describe('getContentPath', function () {
it('should return the correct path for type: public', function () {
const publicPath = configUtils.config.getContentPath('public');

// Path should be in the tmpdir
const tmpdir = os.tmpdir();
const siteUrl = configUtils.config.getSiteUrl();
const siteHash = crypto.createHash('md5')
.update(siteUrl)
.digest('hex');

const expectedPath = path.join(tmpdir, `ghost_${siteHash}_${process.pid}`, 'public/');
publicPath.startsWith(tmpdir).should.be.true();

// Path should end with /public/
publicPath.endsWith('/public/').should.be.true();

// Path should include ghost_
publicPath.includes('ghost_').should.be.true();

// Path should contain a uuid in the correct location
const publicPathParts = publicPath.split('/');
const uuidPart = publicPathParts[publicPathParts.length - 3].replace('ghost_', '');

configUtils.config.getContentPath('public').should.eql(expectedPath);
UUID_REGEX.test(uuidPart).should.be.true();

// Call again to ensure the path is deterministic
configUtils.config.getContentPath('public').should.eql(expectedPath);
// Path should be memoized
configUtils.config.getContentPath('public').should.eql(publicPath);
});
});

0 comments on commit 0e4fde0

Please sign in to comment.