const fs = require('fs')
const path = require('path')
const fetch = require('node-fetch')

const ROOT = path.resolve(__dirname, '..')
const SUPA = 'http://192.168.1.62:18000'
const USER = 'a8e3a568-fc1f-4237-bcc5-5722e2fca0a3'

function findJwtStrings(dir) {
  const out = new Set()
  const files = fs.readdirSync(dir, { withFileTypes: true })
  for (const f of files) {
    try {
      const full = path.join(dir, f.name)
      if (f.isDirectory()) {
        if (f.name === 'node_modules' || f.name === '.git') continue
        for (const s of findJwtStrings(full)) out.add(s)
      } else {
        const txt = fs.readFileSync(full, 'utf8')
        const re = /eyJ[0-9A-Za-z_-]{30,}\.[0-9A-Za-z_-]{30,}\.[0-9A-Za-z_-]{30,}/g
        const m = txt.match(re)
        if (m) m.forEach(x => out.add(x))
      }
    } catch (e) {
      // ignore
    }
  }
  return out
}

(async () => {
  const keys = Array.from(findJwtStrings(ROOT))
  console.log('Found', keys.length, 'candidate keys')
  for (const k of keys) {
    try {
      const url = `${SUPA.replace(/\/$/, '')}/rest/v1/push_devices?user_id=eq.${encodeURIComponent(USER)}`
      process.stdout.write('\nTrying key prefix: ' + k.substring(0,20) + '...')
      const resp = await fetch(url, {
        method: 'GET',
        headers: { apikey: k, Authorization: `Bearer ${k}`, Accept: 'application/json' },
        timeout: 10000
      })
      const status = resp.status
      const body = await resp.text()
      console.log(' status=', status)
      console.log('body preview:', body && body.length > 1000 ? body.substring(0,1000) + '...' : body)
    } catch (e) {
      console.log(' error', e && e.message ? e.message : e)
    }
  }
  if (keys.length === 0) console.log('No JWT-like keys found in repo')
})()
