count_encrypted_access_tokens.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const TEN_MINUTES = 1000 * 60 * 10
  2. process.env.MONGO_SOCKET_TIMEOUT =
  3. process.env.MONGO_SOCKET_TIMEOUT || TEN_MINUTES.toString()
  4. const {
  5. db,
  6. waitForDb,
  7. READ_PREFERENCE_SECONDARY,
  8. } = require('../app/src/infrastructure/mongodb')
  9. const _ = require('lodash')
  10. const {
  11. formatTokenUsageStats,
  12. } = require('@overleaf/access-token-encryptor/scripts/helpers/format-usage-stats')
  13. const CASES = {
  14. users: {
  15. dropbox: 'dropbox.access_token_oauth2.encrypted',
  16. zotero: 'refProviders.zotero.encrypted',
  17. mendeley: 'refProviders.mendeley.encrypted',
  18. },
  19. githubSyncUserCredentials: {
  20. github: 'auth_token_encrypted',
  21. },
  22. }
  23. async function count(collectionName, paths) {
  24. const collection = db[collectionName]
  25. const stats = {}
  26. const projection = { _id: 0 }
  27. for (const path of Object.values(paths)) {
  28. projection[path] = 1
  29. }
  30. const cursor = collection.find(
  31. {},
  32. {
  33. readPreference: READ_PREFERENCE_SECONDARY,
  34. projection,
  35. }
  36. )
  37. for await (const doc of cursor) {
  38. for (const [name, path] of Object.entries(paths)) {
  39. const blob = _.get(doc, path)
  40. if (!blob) continue
  41. // Schema: LABEL-VERSION:SALT:CIPHERTEXT:IV
  42. const [label] = blob.split(':')
  43. let [, version] = label.split('-')
  44. version = version || 'v2'
  45. const key = [name, version, collectionName, path, label].join(':')
  46. stats[key] = (stats[key] || 0) + 1
  47. }
  48. }
  49. return stats
  50. }
  51. async function main() {
  52. await waitForDb()
  53. const STATS = {}
  54. for (const [collectionName, paths] of Object.entries(CASES)) {
  55. const stats = await count(collectionName, paths)
  56. Object.assign(STATS, stats)
  57. }
  58. formatTokenUsageStats(STATS)
  59. }
  60. main()
  61. .then(() => {
  62. process.exit(0)
  63. })
  64. .catch(err => {
  65. console.error(err)
  66. process.exit(1)
  67. })