import { queryOptions } from '@tanstack/react-query' import { oauthAppsKeys } from './keys' import { getOAuthApprovals } from './oauth-apps-approvals-query' import { getOAuthAppMemberGrants } from './oauth-apps-member-grants-query' import { getOAuthDatabaseTokenAccess } from './types' import type { StudioError } from '@/lib/errors/studio-errors' export type OAuthProjectDatabaseAccessVariables = { slug?: string; projectRef?: string } export type OAuthProjectDatabaseAccessError = StudioError function getNextCursor(next: string | null | undefined) { if (!next) return undefined return new URL(next, 'http://localhost').searchParams.get('page[after]') ?? undefined } async function fetchAllPages( fetchPage: (cursor?: string) => Promise<{ data: T[]; links: { next?: string | null } }> ) { const items: T[] = [] let cursor: string | undefined do { const page = await fetchPage(cursor) items.push(...page.data) cursor = getNextCursor(page.links.next) } while (cursor) return items } async function getOAuthProjectDatabaseAccess( { slug, projectRef }: OAuthProjectDatabaseAccessVariables, signal?: AbortSignal ) { if (!slug || !projectRef) throw new Error('Organization slug and project reference are required') const apps: { id: string; name: string; icon: string | null; access: 'read' | 'write' }[] = [] for (const approval of await fetchAllPages((cursor) => getOAuthApprovals({ slug, cursor }, signal) )) { const orgGrant = approval.attributes.org_grant const access = getOAuthDatabaseTokenAccess(orgGrant?.approved_scopes) if (!orgGrant || !access) continue let hasMatchedGrant = false for (const { id, attributes } of await fetchAllPages((cursor) => getOAuthAppMemberGrants({ slug, appId: approval.id, cursor }, signal) )) { if (id !== orgGrant.grant_id || attributes.kind !== 'organization_bound') continue if (getOAuthDatabaseTokenAccess(attributes.approved_scopes) !== access) { throw new Error('App access changed while loading. Retry to check the current grants.') } hasMatchedGrant = true const coversProject = attributes.projects === null || attributes.projects.some(({ ref }) => ref === projectRef) if (coversProject) apps.push({ id: approval.id, ...approval.attributes.app, access }) } if (!hasMatchedGrant) { throw new Error( 'Could not verify an app’s project access. Retry to check the current grants.' ) } } return apps } export type OAuthProjectDatabaseAccessData = Awaited< ReturnType > export const oauthProjectDatabaseAccessQueryOptions = ({ slug, projectRef, }: OAuthProjectDatabaseAccessVariables) => queryOptions({ queryKey: oauthAppsKeys.projectDatabaseAccess(slug, projectRef), queryFn: ({ signal }) => getOAuthProjectDatabaseAccess({ slug, projectRef }, signal), retry: false, })