count_encrypted_access_tokens.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. import { scriptRunner } from './lib/ScriptRunner.mjs'
  9. if (!process.env.MONGO_SOCKET_TIMEOUT) {
  10. const TEN_MINUTES = 1000 * 60 * 10
  11. ensureMongoTimeout(TEN_MINUTES)
  12. }
  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. const STATS = {}
  53. for (const [collectionName, paths] of Object.entries(CASES)) {
  54. const stats = await count(collectionName, paths)
  55. Object.assign(STATS, stats)
  56. }
  57. formatTokenUsageStats(STATS)
  58. }
  59. try {
  60. await scriptRunner(main)
  61. process.exit(0)
  62. } catch (error) {
  63. console.error(error)
  64. process.exit(1)
  65. }