mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-27 04:43:12 +03:00
3a7613a46e
- this utility existed twice in the ghost codebase: -f6fb823ce9/core/server/models/api-key.js (L24)
-f6fb823ce9/core/server/data/migrations/versions/4.0/22-solve-orphaned-webhooks.js (L7)
- We also potentially need it for a second migration use case - so moved it here, made it slightly more generic and also deprecated identifier.uid in favour of using this method as they do the same thing, but secret.create uses crypto properly
41 lines
1013 B
JavaScript
41 lines
1013 B
JavaScript
const crypto = require('crypto');
|
|
|
|
/*
|
|
* Uses birthday problem estimation to calculate chance of collision
|
|
* d = 16^26 // 26 char hex string
|
|
* n = 10,000,000 // 10 million
|
|
*
|
|
* (-n x (n-1)) / 2d
|
|
* 1 - e^
|
|
*
|
|
*
|
|
* 17
|
|
* ~= 4 x 10^
|
|
*
|
|
* ref: https://medium.freecodecamp.org/how-long-should-i-make-my-api-key-833ebf2dc26f
|
|
* ref: https://en.wikipedia.org/wiki/Birthday_problem#Approximations
|
|
*
|
|
* 26 char hex string = 13 bytes (content api)
|
|
* 64 char hex string JWT secret = 32 bytes (admin api / default)
|
|
*
|
|
* @param {String|Number} [typeOrLength=64]
|
|
* @returns
|
|
*/
|
|
module.exports.create = (typeOrLength) => {
|
|
let bytes;
|
|
let length;
|
|
|
|
if (Number.isInteger(typeOrLength)) {
|
|
bytes = Math.ceil(typeOrLength / 2);
|
|
length = typeOrLength;
|
|
} else if (typeOrLength === 'content') {
|
|
bytes = 13;
|
|
length = 26;
|
|
} else {
|
|
bytes = 32;
|
|
length = 64;
|
|
}
|
|
|
|
return crypto.randomBytes(bytes).toString('hex').slice(0, length);
|
|
};
|