count_encrypted_access_tokens.mjs 1.8 KB

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