backfill_project_invites_token_hmac.mjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { db } from '../app/src/infrastructure/mongodb.js'
  2. import BatchedUpdateModule from './helpers/batchedUpdate.mjs'
  3. import minimist from 'minimist'
  4. import CollaboratorsInviteHelper from '../app/src/Features/Collaborators/CollaboratorsInviteHelper.js'
  5. import { fileURLToPath } from 'node:url'
  6. const { batchedUpdate } = BatchedUpdateModule
  7. const argv = minimist(process.argv.slice(2), {
  8. boolean: ['dry-run', 'help'],
  9. default: {
  10. 'dry-run': true,
  11. },
  12. })
  13. const DRY_RUN = argv['dry-run']
  14. async function addTokenHmacField(DRY_RUN) {
  15. const query = { tokenHmac: { $exists: false } }
  16. await batchedUpdate(
  17. 'projectInvites',
  18. query,
  19. async invites => {
  20. for (const invite of invites) {
  21. console.log(
  22. `=> Missing "tokenHmac" token in invitation: ${invite._id.toString()}`
  23. )
  24. if (DRY_RUN) {
  25. console.log(
  26. `=> DRY RUN - would add "tokenHmac" token to invitation ${invite._id.toString()}`
  27. )
  28. continue
  29. }
  30. const tokenHmac = CollaboratorsInviteHelper.hashInviteToken(
  31. invite.token
  32. )
  33. await db.projectInvites.updateOne(
  34. { _id: invite._id },
  35. { $set: { tokenHmac } }
  36. )
  37. console.log(
  38. `=> Added "tokenHmac" token to invitation ${invite._id.toString()}`
  39. )
  40. }
  41. },
  42. { token: 1 }
  43. )
  44. }
  45. async function main(DRY_RUN) {
  46. await addTokenHmacField(DRY_RUN)
  47. }
  48. export default main
  49. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  50. if (argv.help || argv._.length > 1) {
  51. console.error(`Usage: node scripts/backfill_project_invites_token_hmac.mjs
  52. Adds a "tokenHmac" field (which is a hashed version of the token) to each project invite record.
  53. Options:
  54. --dry-run finds invitations without HMAC token but does not do any updates
  55. `)
  56. process.exit(1)
  57. }
  58. try {
  59. await main(DRY_RUN)
  60. console.error('Done')
  61. process.exit(0)
  62. } catch (error) {
  63. console.error(error)
  64. process.exit(1)
  65. }
  66. }