backfill_project_invites_token_hmac.mjs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { db, waitForDb } 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 '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 waitForDb()
  47. await addTokenHmacField(DRY_RUN)
  48. }
  49. export default main
  50. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  51. if (argv.help || argv._.length > 1) {
  52. console.error(`Usage: node scripts/backfill_project_invites_token_hmac.mjs
  53. Adds a "tokenHmac" field (which is a hashed version of the token) to each project invite record.
  54. Options:
  55. --dry-run finds invitations without HMAC token but does not do any updates
  56. `)
  57. process.exit(1)
  58. }
  59. try {
  60. await main(DRY_RUN)
  61. console.error('Done')
  62. process.exit(0)
  63. } catch (error) {
  64. console.error(error)
  65. process.exit(1)
  66. }
  67. }