DisplayApiSettings.utils.ts62 lines · main
1import dayjs from 'dayjs'
2import { useRef } from 'react'
3
4import useLogsQuery from '@/hooks/analytics/useLogsQuery'
5
6export function useLastUsedAPIKeysLogQuery({
7 projectRef,
8 enabled,
9}: {
10 projectRef: string
11 enabled?: boolean
12}) {
13 const now = useRef(new Date()).current
14 return useLogsQuery(
15 projectRef,
16 {
17 iso_timestamp_start: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
18 iso_timestamp_end: now.toISOString(),
19 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",
20 },
21 enabled
22 )
23}
24
25export function getLastUsedAPIKeys(
26 apiKeys: {
27 tags: string
28 api_key: string
29 }[],
30 logData:
31 | {
32 timestamp: number
33 role?: 'anon' | 'service_role' | string
34 signature_prefix?: string
35 }[]
36 | null
37) {
38 if (apiKeys.length < 1 || !logData || logData.length < 1) {
39 return {}
40 }
41
42 const now = dayjs()
43
44 return apiKeys.reduce(
45 (a, i) => {
46 const entry = logData?.find(
47 ({ role, signature_prefix }) =>
48 role &&
49 signature_prefix &&
50 i.tags.indexOf(role) >= 0 &&
51 i.api_key.split('.')[2]?.startsWith(signature_prefix)
52 )?.timestamp
53
54 if (entry) {
55 a[i.api_key] = dayjs.duration(now.diff(dayjs(entry))).humanize(false)
56 }
57
58 return a
59 },
60 {} as { [apikey: string]: string }
61 )
62}