upgrade_token_scopes.mjs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import minimist from 'minimist'
  2. import { db } from '../../app/src/infrastructure/mongodb.js'
  3. const OPTS = parseArgs()
  4. function parseArgs() {
  5. const args = minimist(process.argv.slice(2), {
  6. boolean: ['help', 'commit'],
  7. })
  8. if (args.help) {
  9. usage()
  10. process.exit(0)
  11. }
  12. if (args._.length === 0) {
  13. usage()
  14. process.exit(1)
  15. }
  16. return {
  17. appIds: args._,
  18. commit: args.commit,
  19. }
  20. }
  21. function usage() {
  22. console.error(`Usage: updgrade_token_scopes.mjs [--commit] APP_ID ...
  23. This script will upgrade all existing OAuth tokens for the given app(s) so
  24. that their scope matches the scope configured on the app.
  25. USE WITH CAUTION: any token with limited scope previously issued will be
  26. upgraded to support all scopes available to the app.
  27. `)
  28. }
  29. async function main() {
  30. for (const appId of OPTS.appIds) {
  31. const app = await db.oauthApplications.findOne({ id: appId })
  32. if (app == null) {
  33. console.error(`App "${appId}" not found. Skipping.`)
  34. continue
  35. }
  36. const expectedScope = (app.scopes ?? []).join(' ')
  37. const filter = {
  38. oauthApplication_id: app._id,
  39. scope: { $ne: expectedScope },
  40. }
  41. if (OPTS.commit) {
  42. const result = await db.oauthAccessTokens.updateMany(filter, {
  43. $set: { scope: expectedScope },
  44. })
  45. console.error(
  46. `App "${appId}": upgraded ${result.modifiedCount} access tokens`
  47. )
  48. } else {
  49. const count = await db.oauthAccessTokens.count(filter)
  50. console.error(`App "${appId}": would upgrade ${count} access tokens`)
  51. }
  52. }
  53. if (!OPTS.commit) {
  54. console.error('This was a dry run. Re-run with --commit to apply changes')
  55. }
  56. }
  57. try {
  58. await main()
  59. process.exit(0)
  60. } catch (error) {
  61. console.error(error)
  62. process.exit(1)
  63. }