count_encrypted_access_tokens.js 1.8 KB

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