Newer
Older
gnexus-book / ui / src / pages / KeysPage.vue
<script setup>
import { onMounted, reactive, ref } from "vue";
import {
  GnAlert,
  GnBadge,
  GnButton,
  GnCard,
  GnConfirmDialog,
  GnEmptyState,
  GnInput,
  GnPageHeader,
  useToast
} from "gnexus-ui-kit/vue";

import { apiGet, apiSend } from "../lib/api.js";
import { formatDate } from "../lib/format.js";
import { isAdmin, session } from "../lib/session.js";
import { t } from "../i18n/index.js";

const toast = useToast();
const keys = ref([]);
const showAll = ref(false);
const loading = ref(false);
const error = ref("");
const issuedToken = ref("");
const issuedKey = ref(null);
const form = reactive({ consumer: "claude-code", name: "" });
const confirmState = reactive({
  open: false,
  title: "",
  message: "",
  confirmText: "",
  variant: "warning",
  action: null
});

async function loadKeys() {
  if (!session.user) return;
  loading.value = true;
  error.value = "";
  try {
    const data = await apiGet(`/mcp-keys${showAll.value ? "?all=true" : ""}`);
    keys.value = data.items || [];
  } catch (err) {
    error.value = err instanceof Error ? err.message : t("errors.loadFailed");
  } finally {
    loading.value = false;
  }
}

async function createKey() {
  if (!form.consumer.trim()) {
    toast.warning({ title: t("common.error"), text: t("keys.consumer") });
    return;
  }
  loading.value = true;
  error.value = "";
  try {
    const data = await apiSend("/mcp-keys", "POST", {
      consumer: form.consumer.trim(),
      name: form.name.trim()
    });
    issuedToken.value = data.token;
    issuedKey.value = data;
    form.name = "";
    toast.success({ title: t("keys.issuedTitle") });
    await loadKeys();
  } catch (err) {
    error.value = err instanceof Error ? err.message : t("errors.actionFailed");
  } finally {
    loading.value = false;
  }
}

function rotateKey(key) {
  askConfirm({
    title: t("keys.rotate"),
    message: t("keys.issuedText"),
    confirmText: t("keys.rotate"),
    variant: "warning",
    action: async () => {
      try {
        const data = await apiSend(`/mcp-keys/${encodeURIComponent(key.key_id)}/rotate`, "POST");
        issuedToken.value = data.token;
        issuedKey.value = data;
        toast.success({ title: t("keys.rotated") });
        await loadKeys();
      } catch (err) {
        toast.danger({
          title: t("errors.actionFailed"),
          text: err instanceof Error ? err.message : t("errors.actionFailed")
        });
      }
    }
  });
}

function revokeKey(key) {
  askConfirm({
    title: t("keys.revokeConfirm"),
    message: t("keys.revokeConfirmText"),
    confirmText: t("keys.revoke"),
    variant: "danger",
    action: async () => {
      try {
        await apiSend(`/mcp-keys/${encodeURIComponent(key.key_id)}`, "DELETE");
        toast.success({ title: t("keys.revoked") });
        await loadKeys();
      } catch (err) {
        toast.danger({
          title: t("errors.actionFailed"),
          text: err instanceof Error ? err.message : t("errors.actionFailed")
        });
      }
    }
  });
}

function askConfirm({ title, message, confirmText, variant, action }) {
  confirmState.title = title;
  confirmState.message = message;
  confirmState.confirmText = confirmText;
  confirmState.variant = variant || "warning";
  confirmState.action = action || null;
  confirmState.open = true;
}

function runConfirm() {
  const action = confirmState.action;
  confirmState.action = null;
  if (action) action();
}

async function copyToken() {
  try {
    await navigator.clipboard.writeText(issuedToken.value);
    toast.success({ title: t("common.copied") });
  } catch {
    toast.danger({ title: t("errors.actionFailed") });
  }
}

function dismissIssued() {
  issuedToken.value = "";
  issuedKey.value = null;
}

async function toggleAll() {
  if (!isAdmin.value) return;
  showAll.value = !showAll.value;
  await loadKeys();
}

onMounted(loadKeys);
</script>

<template>
  <div class="gnb-page">
    <GnPageHeader
      :title="t('keys.title')"
      :subtitle="t('keys.subtitle')"
      :kicker="t('app.kicker')"
      accent
    >
      <template #actions>
        <GnButton variant="secondary" icon="ph-arrow-clockwise" @click="loadKeys">
          {{ t("common.refresh") }}
        </GnButton>
      </template>
    </GnPageHeader>

    <GnAlert v-if="!session.authEnabled" variant="info">{{ t("keys.notConfigured") }}</GnAlert>
    <div v-else class="gnb-split">
      <GnCard :title="t('keys.createTitle')">
        <p class="gnb-muted">{{ t("keys.createMeta") }}</p>
        <div class="gnb-form">
          <GnInput v-model="form.consumer" :label="t('keys.consumer')" icon="ph-robot" placeholder="navi" />
          <GnInput v-model="form.name" :label="t('keys.name')" icon="ph-tag" />
          <div class="gnb-actions">
            <GnButton variant="success" icon="ph-key" :loading="loading" @click="createKey">
              {{ t("keys.create") }}
            </GnButton>
            <GnButton v-if="isAdmin" variant="secondary" @click="toggleAll">
              {{ showAll ? t("keys.own") : t("keys.showAll") }}
            </GnButton>
          </div>
        </div>
        <GnAlert v-if="issuedToken && issuedKey" variant="success">
          <strong>{{ t("keys.issuedTitle") }}</strong>
          <p>{{ t("keys.issuedText") }}</p>
          <p class="gnb-muted">{{ issuedKey.consumer }} · …{{ issuedKey.token_hint }}</p>
          <code class="gnb-token">{{ issuedToken }}</code>
          <div class="gnb-actions">
            <GnButton size="sm" icon="ph-copy" variant="secondary" @click="copyToken">
              {{ t("keys.copyToken") }}
            </GnButton>
            <GnButton size="sm" variant="secondary" @click="dismissIssued">
              {{ t("common.close") }}
            </GnButton>
          </div>
        </GnAlert>
        <GnAlert v-if="error" variant="danger">{{ error }}</GnAlert>
      </GnCard>

      <GnCard :title="showAll ? t('keys.showAll') : t('keys.own')">
        <GnEmptyState v-if="!keys.length" :title="t('keys.noKeys')" icon="ph-key" />
        <div v-else class="gnb-keys">
          <div v-for="key in keys" :key="key.key_id" class="gnb-key-row">
            <div class="gnb-key-copy">
              <strong>{{ key.name }}</strong>
              <span class="gnb-muted">
                {{ key.consumer }} · {{ key.role || t("common.unknown") }} ·
                {{ (key.scopes || []).join(", ") }} · …{{ key.token_hint }}
              </span>
              <span class="gnb-muted">
                {{ t("common.created") }}: {{ formatDate(key.created_at) }} ·
                {{ t("common.lastUsed") }}: {{ formatDate(key.last_used_at) }}
              </span>
              <div class="gnb-badges">
                <GnBadge v-if="key.revoked_at" variant="danger">{{ t("common.revoked") }}</GnBadge>
                <GnBadge v-if="key.stale_at" variant="warning">{{ t("common.stale") }}</GnBadge>
              </div>
            </div>
            <div class="gnb-actions">
              <GnButton v-if="!key.revoked_at" size="sm" variant="secondary" icon="ph-arrows-clockwise" @click="rotateKey(key)">
                {{ t("keys.rotate") }}
              </GnButton>
              <GnButton v-if="!key.revoked_at" size="sm" variant="danger" icon="ph-trash" @click="revokeKey(key)">
                {{ t("keys.revoke") }}
              </GnButton>
            </div>
          </div>
        </div>
      </GnCard>
    </div>

    <GnConfirmDialog
      v-model:open="confirmState.open"
      :title="confirmState.title"
      :message="confirmState.message"
      :confirm-text="confirmState.confirmText || t('common.confirm')"
      :cancel-text="t('common.cancel')"
      :confirm-variant="confirmState.variant"
      @confirm="runConfirm"
      @cancel="confirmState.action = null"
    />
  </div>
</template>