AccessToken.constants.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { permissions } from '@supabase/shared-types'
  2. import { components } from 'api-types'
  3. export type ScopedAccessTokenPermission =
  4. components['schemas']['CreateScopedAccessTokenBody']['permissions'][number]
  5. export const NON_EXPIRING_TOKEN_VALUE = 'never'
  6. export const CUSTOM_EXPIRY_VALUE = 'custom'
  7. export const EXPIRES_AT_OPTIONS = {
  8. hour: { value: 'hour', label: '1 hour' },
  9. day: { value: 'day', label: '1 day' },
  10. week: { value: 'week', label: '7 days' },
  11. month: { value: 'month', label: '30 days' },
  12. never: { value: NON_EXPIRING_TOKEN_VALUE, label: 'Never' },
  13. custom: { value: CUSTOM_EXPIRY_VALUE, label: 'Custom' },
  14. } as const
  15. const FGA = permissions.FgaPermissions
  16. const getAction = (key: string): string => {
  17. if (key.endsWith('_READ')) return 'read'
  18. if (key.endsWith('_WRITE')) return 'write'
  19. if (key.endsWith('_CREATE')) return 'create'
  20. if (key.endsWith('_DELETE')) return 'delete'
  21. return 'read'
  22. }
  23. const getResource = (key: string): string => {
  24. return key.replace(/_(READ|WRITE|CREATE|DELETE)$/, '').toLowerCase()
  25. }
  26. const buildPermissionList = () => {
  27. const list: Array<{
  28. scope: string
  29. resource: string
  30. action: string
  31. id: string
  32. title: string
  33. }> = []
  34. for (const [scope, scopePerms] of Object.entries(FGA)) {
  35. for (const [key, perm] of Object.entries(scopePerms)) {
  36. list.push({
  37. scope: scope.toLowerCase(),
  38. resource: getResource(key),
  39. action: getAction(key),
  40. id: perm.id,
  41. title: perm.title,
  42. })
  43. }
  44. }
  45. return list
  46. }
  47. export const PERMISSION_LIST = buildPermissionList()
  48. export const ACCESS_TOKEN_RESOURCES = (() => {
  49. const resourceMap = new Map<string, { resource: string; title: string; actions: string[] }>()
  50. for (const p of PERMISSION_LIST) {
  51. const key = `${p.scope}:${p.resource}`
  52. if (!resourceMap.has(key)) {
  53. const cleanTitle = p.title.replace(/^(Read|Manage|Create|Delete)\s+/i, '')
  54. resourceMap.set(key, { resource: key, title: cleanTitle, actions: [] })
  55. }
  56. const entry = resourceMap.get(key)!
  57. if (!entry.actions.includes(p.action)) {
  58. entry.actions.push(p.action)
  59. }
  60. }
  61. return Array.from(resourceMap.values())
  62. })()