backfill_hashed_secrets.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const {
  2. db,
  3. waitForDb,
  4. READ_PREFERENCE_SECONDARY,
  5. } = require('../../app/src/infrastructure/mongodb')
  6. const {
  7. hashSecret,
  8. } = require('../../modules/oauth2-server/app/src/SecretsHelper')
  9. async function main() {
  10. await waitForDb()
  11. console.log('Hashing client secrets...')
  12. await hashSecrets(db.oauthApplications, 'clientSecret')
  13. console.log('Hashing access tokens...')
  14. await hashSecrets(db.oauthAccessTokens, 'accessToken')
  15. console.log('Hashing refresh tokens...')
  16. await hashSecrets(db.oauthAccessTokens, 'refreshToken')
  17. console.log('Hashing authorization codes...')
  18. await hashSecrets(db.oauthAuthorizationCodes, 'authorizationCode')
  19. }
  20. async function hashSecrets(collection, field) {
  21. const cursor = collection.find(
  22. {
  23. [field]: /^(?!v1\.)/,
  24. },
  25. {
  26. projection: { _id: 1, [field]: 1 },
  27. readPreference: READ_PREFERENCE_SECONDARY,
  28. }
  29. )
  30. let hashedCount = 0
  31. for await (const doc of cursor) {
  32. const hash = hashSecret(doc[field])
  33. await collection.updateOne({ _id: doc._id }, { $set: { [field]: hash } })
  34. hashedCount++
  35. }
  36. console.log(`${hashedCount} secrets hashed`)
  37. }
  38. main()
  39. .then(() => {
  40. process.exit(0)
  41. })
  42. .catch(err => {
  43. console.error(err)
  44. process.exit(1)
  45. })