All files / src/stores apiKeys.ts

90.54% Statements 67/74
76.92% Branches 30/39
100% Functions 10/10
90.27% Lines 65/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182                                                                5x 60x 60x 60x 60x 60x 60x     50x 1x     49x 49x 49x   49x 48x 48x 48x     49x 49x 49x 1x     49x         29x 1x     28x     28x               28x   19x 19x       19x     9x 8x   1x   9x 9x     3x     3x 3x 3x   3x   32x 31x                   3x 3x 3x 3x 3x 3x       1x       2x 1x     1x   1x 1x       1x 1x       2x 1x 1x 1x 1x   1x           2x 1x 1x     60x                              
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
 
export interface ApiKey {
  id: string
  flowId: string
  name: string
  keyHash: string
  roleIds: string[]
  expiresAt?: string
  status: 'active' | 'expired' | 'revoked'
  createdBy: string
  createdAt: string
  revokedAt?: string
  revokedBy?: string
  lastUsedAt?: string
}
 
export interface CreateApiKeyRequest {
  name: string
  roleIds: string[]
  expiresAt?: string
}
 
export interface CreateApiKeyResponse {
  apiKey: ApiKey // The API key object
  key: string // The plain key (only returned once!)
  message?: string
  warning?: string
}
 
export const useApiKeysStore = defineStore('apiKeys', () => {
  const apiKeys = ref<ApiKey[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const nextToken = ref<string | null>(null)
  const hasMore = ref(false)
  let latestFetchRequestId = 0
 
  async function fetchApiKeys(reset = true) {
    if (loading.value || (!reset && !hasMore.value)) {
      return
    }
 
    const requestId = ++latestFetchRequestId
    loading.value = true
    error.value = null
 
    if (reset) {
      apiKeys.value = []
      nextToken.value = null
      hasMore.value = true
    }
 
    try {
      const params: any = { limit: 30 }
      if (!reset && nextToken.value) {
        params.nextToken = nextToken.value
      }
 
      const response = await api.get('/v1/admin/api-keys', { params })
 
      // A newer fetch, or a local mutation (create/revoke/delete), has
      // superseded this request: discard the now-stale response instead of
      // clobbering more recent state.
      if (requestId !== latestFetchRequestId) {
        return
      }
 
      const data = response.data
 
      // Handle different response formats
      Iif (Array.isArray(data)) {
        // Direct array response
        if (reset) {
          apiKeys.value = data
        } else {
          apiKeys.value = [...apiKeys.value, ...data]
        }
        hasMore.value = false
      } else if (data.apiKeys) {
        // Backend returns { apiKeys: [...], count: n }
        if (reset) {
          apiKeys.value = data.apiKeys
        } else E{
          apiKeys.value = [...apiKeys.value, ...data.apiKeys]
        }
        hasMore.value = false
      } else {
        // Paginated response { items: [...], nextToken, hasMore }
        if (reset) {
          apiKeys.value = data.items
        } else {
          apiKeys.value = [...apiKeys.value, ...data.items]
        }
        nextToken.value = data.nextToken
        hasMore.value = data.hasMore
      }
    } catch (err: any) {
      Iif (requestId !== latestFetchRequestId) {
        return
      }
      error.value = err.response?.data?.error || err.message || 'Failed to fetch API keys'
      Eif (reset) {
        apiKeys.value = []
      }
      throw err
    } finally {
      if (requestId === latestFetchRequestId) {
        loading.value = false
      }
    }
  }
 
  /**
   * API keys belong to the active flow: drop the previous flow's on a flow
   * switch, and discard any fetch still in flight for it.
   */
  function reset() {
    latestFetchRequestId++
    apiKeys.value = []
    loading.value = false
    error.value = null
    nextToken.value = null
    hasMore.value = false
  }
 
  async function loadMoreApiKeys() {
    await fetchApiKeys(false)
  }
 
  async function createApiKey(data: CreateApiKeyRequest): Promise<CreateApiKeyResponse> {
    const response = await api.post('/v1/admin/api-keys', data)
    Iif (!Array.isArray(apiKeys.value)) {
      apiKeys.value = []
    }
    apiKeys.value.unshift(response.data.apiKey) // Add the API key object to beginning
    // Invalidate any in-flight fetchApiKeys() so its response can't overwrite this.
    latestFetchRequestId++
    return response.data
  }
 
  async function getApiKey(id: string): Promise<ApiKey> {
    const response = await api.get(`/v1/admin/api-keys/${id}`)
    return response.data
  }
 
  async function revokeApiKey(id: string) {
    await api.delete(`/v1/admin/api-keys/${id}`)
    const index = apiKeys.value.findIndex((k) => k.id === id)
    Eif (index !== -1 && apiKeys.value[index]) {
      apiKeys.value[index].status = 'revoked'
      apiKeys.value[index].revokedAt = new Date().toISOString()
    }
    latestFetchRequestId++
  }
 
  // Revoked/expired keys have no automatic cleanup: this hits the same DELETE
  // endpoint, which permanently removes the record instead of soft-revoking it.
  async function deleteApiKey(id: string) {
    await api.delete(`/v1/admin/api-keys/${id}`)
    apiKeys.value = apiKeys.value.filter((k) => k.id !== id)
    latestFetchRequestId++
  }
 
  return {
    apiKeys,
    loading,
    error,
    nextToken,
    hasMore,
    fetchApiKeys,
    reset,
    loadMoreApiKeys,
    createApiKey,
    getApiKey,
    revokeApiKey,
    deleteApiKey
  }
})