Skip to content

Commit

Permalink
update: address comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
ItzNotABug committed Jul 6, 2024
1 parent 6fd6486 commit e8118fa
Showing 1 changed file with 33 additions and 16 deletions.
49 changes: 33 additions & 16 deletions utils/misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,11 +292,11 @@ export default class Miscellaneous {
*/
static async isPostSecure(request) {
const payload = JSON.stringify(request.body);
const ghostConfigs = await ProjectConfigs.ghost();
const ghostSecretSignature = (await ProjectConfigs.ghost()).secret;
const signatureWithDateHeader = request.headers['x-ghost-signature'];

// Secret set on Ghosler but not recd. in the request headers.
if (ghostConfigs.secret && !signatureWithDateHeader) {
if (ghostSecretSignature && !signatureWithDateHeader) {
logError(
logTags.Express,
"The 'X-Ghost-Signature' header not found in the request. Did you setup the Secret Key correctly?",
Expand Down Expand Up @@ -327,25 +327,27 @@ export default class Miscellaneous {
}

/**
* Build signature with new logic for `Ghost:5.87.1` & above.
* @see https://github.com/TryGhost/Ghost/pull/20500
* Build signature for versions below `Ghost:5.87.1`.
*/
const expectedNewSignature = crypto
.createHmac('sha256', ghostConfigs.secret)
.update(`${payload}${timeStamp}`)
.digest('hex');
const expectedOldSignature = this.#createHmac(
ghostSecretSignature,
payload,
);

/**
* Build signature for versions below `Ghost:5.87.1`.
* Build signature with new logic for `Ghost:5.87.1` & above.
* @see https://github.com/TryGhost/Ghost/pull/20500
*/
const expectedOldSignature = crypto
.createHmac('sha256', ghostConfigs.secret)
.update(payload)
.digest('hex');
const expectedNewSignature = this.#createHmac(
ghostSecretSignature,
`${payload}${timeStamp}`,
);

if (signature === expectedNewSignature) {
return true;
} else if (signature === expectedOldSignature) {
// Check if either of the signatures match
if (
signature === expectedOldSignature ||
signature === expectedNewSignature
) {
return true;
} else {
logError(
Expand Down Expand Up @@ -374,4 +376,19 @@ export default class Miscellaneous {
audience,
});
}

/**
* Creates a signature based on given inputs.
*
* @param {string} secret - The ghost secret key.
* @param {string} payload - The payload to create the hash for.
*
* @returns {string} The generated HMAC hex digest.
*/
static #createHmac(secret, payload) {
return crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
}
}

0 comments on commit e8118fa

Please sign in to comment.