DisplayApiSettings.utils.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import dayjs from 'dayjs'
  2. import { useRef } from 'react'
  3. import useLogsQuery from '@/hooks/analytics/useLogsQuery'
  4. export function useLastUsedAPIKeysLogQuery({
  5. projectRef,
  6. enabled,
  7. }: {
  8. projectRef: string
  9. enabled?: boolean
  10. }) {
  11. const now = useRef(new Date()).current
  12. return useLogsQuery(
  13. projectRef,
  14. {
  15. iso_timestamp_start: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
  16. iso_timestamp_end: now.toISOString(),
  17. sql: "-- last-used-anon--service_role-api-keys\nSELECT unix_millis(max(timestamp)) as timestamp, payload.role, payload.signature_prefix FROM edge_logs cross join unnest(metadata) as m cross join unnest(m.request) as request cross join unnest(request.sb) as sb cross join unnest(sb.jwt) as jwt cross join unnest(jwt.apikey) as apikey cross join unnest(apikey.payload) as payload WHERE apikey.invalid is null and payload.issuer = 'briven' and payload.algorithm = 'HS256' and payload.role in ('anon', 'service_role') GROUP BY payload.role, payload.signature_prefix",
  18. },
  19. enabled
  20. )
  21. }
  22. export function getLastUsedAPIKeys(
  23. apiKeys: {
  24. tags: string
  25. api_key: string
  26. }[],
  27. logData:
  28. | {
  29. timestamp: number
  30. role?: 'anon' | 'service_role' | string
  31. signature_prefix?: string
  32. }[]
  33. | null
  34. ) {
  35. if (apiKeys.length < 1 || !logData || logData.length < 1) {
  36. return {}
  37. }
  38. const now = dayjs()
  39. return apiKeys.reduce(
  40. (a, i) => {
  41. const entry = logData?.find(
  42. ({ role, signature_prefix }) =>
  43. role &&
  44. signature_prefix &&
  45. i.tags.indexOf(role) >= 0 &&
  46. i.api_key.split('.')[2]?.startsWith(signature_prefix)
  47. )?.timestamp
  48. if (entry) {
  49. a[i.api_key] = dayjs.duration(now.diff(dayjs(entry))).humanize(false)
  50. }
  51. return a
  52. },
  53. {} as { [apikey: string]: string }
  54. )
  55. }