hooks.utils.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { ident, safeSql, type SafeSqlFragment } from '@supabase/pg-meta/src/pg-format'
  2. import { Hook } from './hooks.constants'
  3. export const extractMethod = (
  4. uri: string,
  5. secret?: string
  6. ):
  7. | { type: 'postgres'; schema: string; functionName: string }
  8. | { type: 'https'; url: string; secret: string } => {
  9. if (uri.startsWith('https')) {
  10. return { type: 'https', url: uri, secret: secret || '' }
  11. } else {
  12. const [_proto, _x, _db, schema, functionName] = (uri || '').split('/')
  13. return {
  14. type: 'postgres',
  15. schema: schema || '',
  16. functionName: functionName || '',
  17. }
  18. }
  19. }
  20. export const isValidHook = (h: Hook) => {
  21. return (
  22. (h.method.type === 'postgres' &&
  23. h.method.schema.length > 0 &&
  24. h.method.functionName.length > 0) ||
  25. (h.method.type === 'https' && h.method.url.startsWith('https') && h.method.secret.length > 0)
  26. )
  27. }
  28. /**
  29. *
  30. * @param schema the schema that the function belongs to
  31. * @param functionName the function name associated with the hook
  32. * @returns an array of SQL statements to restore the original permissions to the function
  33. */
  34. export const getRevokePermissionStatements = (
  35. schema: string,
  36. functionName: string
  37. ): Array<SafeSqlFragment> => {
  38. return [
  39. safeSql`-- Revoke access to function from briven_auth_admin
  40. revoke execute on function ${ident(schema)}.${ident(functionName)} from briven_auth_admin;`,
  41. safeSql`-- Revoke access to schema from briven_auth_admin
  42. revoke usage on schema ${ident(schema)} from briven_auth_admin;`,
  43. safeSql`-- Restore function permissions to authenticated, anon and public
  44. grant execute on function ${ident(schema)}.${ident(functionName)} to authenticated, anon, public;`,
  45. ]
  46. }