Ir al contenido

ApiKeys

Las llaves de un proyecto: la publicable, segura en un navegador, y las secretas, cada una con nombre, lo que puede hacer, cuándo se usó por última vez y cuándo vence. Una llave secreta nueva se muestra una vez; revocarla dice qué deja de funcionar.

import { CopyField, RowActions, ConfirmDialog } from '@sypnia/ui/react'

En esta página
  1. En un computador
  2. En un celular
  3. Aún no hay llaves secretas
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

En un computador

Crea una llave (un nombre ya usado se rechaza), guárdala, y luego revoca una.

Llaves de API

Cómo tus apps y servidores prueban que pueden usar northwind-shop.

Llave publicable

Segura en un navegador o una app móvil: solo hace lo que permite la seguridad por fila.

Llaves secretas

NombreAlcanceÚltimo usoVence
checkout serversk_live_7Hq2…
Lectura y escriturahace 4 minutos16 ene 2027
nightly exportsk_live_c9Lm…
Lecturahace 15 horasNo vence
migration scriptsk_live_Pw41…
AdministraciónNunca27 nov 2026
Código
import { useState } from 'react';
import {
  Badge, Button, Callout, Checkbox, ConfirmDialog, CopyField, Dialog, EmptyState, Field, Form, FormActions, InlineCode, Input, Page, PageHeader,
  Panel, RadioCards, RowActions, Select, SkeletonOf, SkeletonWords, Stack, Table, Tag, Text, Toaster, toast, useSypnia, type FormProblem,
} from '@sypnia/ui/react';

// The keys of a project: the publishable one, safe in a browser, and the secret ones, each with a name, what it may
// do, when it was last used and when it ends. A new secret key is shown once; revoking says what stops working.
type Key = { id: string; name: string; prefix: string; scope: 'read' | 'write' | 'admin'; created: number; used: number | null; expires: number | null };
const en = {
  title: 'API keys', lead: 'How your apps and servers prove they may use northwind-shop.', create: 'Create a secret key',
  publishable: 'Publishable key', publishableD: 'Safe in a browser or a mobile app: it can only do what row-level security allows.',
  secret: 'Secret keys', secretD: 'For servers only. Anyone with one can do what its scope allows.', name: 'Name', key: 'Key', scope: 'Scope', lastUsed: 'Last used', ends: 'Ends', never: 'Never', noEnd: 'Does not end',
  scopes: { read: 'Read', write: 'Read and write', admin: 'Admin' },
  scopeOptions: [
    { value: 'read', label: 'Read', description: 'Reads every table. Changes nothing.' },
    { value: 'write', label: 'Read and write', description: 'Reads and changes rows. Cannot change tables or settings.' },
    { value: 'admin', label: 'Admin', description: 'Everything, including tables, keys and settings.' },
  ],
  expiry: 'Ends after', days: (n: number) => `${n} days`, noExpiry: 'Never (not recommended)', nameHint: 'Where it will be used: «checkout server».', noName: 'Give the key a name.',
  taken: 'A key with this name exists. Names tell keys apart: choose another.', creating: 'Creating…',
  saveTitle: 'Save your new key', saveLead: 'Copy it now: this is the only time it is shown in full.', saved: 'I saved the key somewhere safe', done: 'Done',
  revoke: 'Revoke', revokeQ: (n: string) => `Revoke the key «${n}»?`, revokeBody: (n: string) => `Requests signed with «${n}» get 401 from now on. Apps that use it stop working until they get a new key. This cannot be undone.`,
  revoked: (n: string) => `«${n}» was revoked`, actions: (n: string) => `Actions for ${n}`, roll: 'Replace with a new key', rolled: (n: string) => `A new key replaced «${n}». The old one works for 24 more hours.`,
  emptyTitle: 'No secret keys yet', emptyBody: 'Your server needs one to write to northwind-shop. The publishable key above is enough for browsers.',
};
const es: typeof en = {
  title: 'Llaves de API', lead: 'Cómo tus apps y servidores prueban que pueden usar northwind-shop.', create: 'Crear una llave secreta',
  publishable: 'Llave publicable', publishableD: 'Segura en un navegador o una app móvil: solo hace lo que permite la seguridad por fila.',
  secret: 'Llaves secretas', secretD: 'Solo para servidores. Quien tenga una puede hacer lo que permite su alcance.', name: 'Nombre', key: 'Llave', scope: 'Alcance', lastUsed: 'Último uso', ends: 'Vence', never: 'Nunca', noEnd: 'No vence',
  scopes: { read: 'Lectura', write: 'Lectura y escritura', admin: 'Administración' },
  scopeOptions: [
    { value: 'read', label: 'Lectura', description: 'Lee todas las tablas. No cambia nada.' },
    { value: 'write', label: 'Lectura y escritura', description: 'Lee y cambia filas. No cambia tablas ni ajustes.' },
    { value: 'admin', label: 'Administración', description: 'Todo, incluidas tablas, llaves y ajustes.' },
  ],
  expiry: 'Vence después de', days: (n: number) => `${n} días`, noExpiry: 'Nunca (no recomendado)', nameHint: 'Dónde se usará: «servidor de pagos».', noName: 'Ponle un nombre a la llave.',
  taken: 'Ya hay una llave con este nombre. Los nombres distinguen las llaves: elige otro.', creating: 'Creando…',
  saveTitle: 'Guarda tu llave nueva', saveLead: 'Cópiala ahora: es la única vez que se muestra completa.', saved: 'Guardé la llave en un lugar seguro', done: 'Listo',
  revoke: 'Revocar', revokeQ: (n: string) => `¿Revocar la llave «${n}»?`, revokeBody: (n: string) => `Las solicitudes firmadas con «${n}» reciben 401 desde ahora. Las apps que la usan dejan de funcionar hasta que tengan una llave nueva. No se puede deshacer.`,
  revoked: (n: string) => `Se revocó «${n}»`, actions: (n: string) => `Acciones para ${n}`, roll: 'Reemplazar por una llave nueva', rolled: (n: string) => `Una llave nueva reemplazó a «${n}». La anterior funciona 24 horas más.`,
  emptyTitle: 'Aún no hay llaves secretas', emptyBody: 'Tu servidor necesita una para escribir en northwind-shop. Para navegadores basta la llave publicable de arriba.',
};
const day = 86400e3, now = Date.UTC(2026, 10, 17, 15);
const seed: Key[] = [
  { id: 'k1', name: 'checkout server', prefix: 'sk_live_7Hq2', scope: 'write', created: now - 120 * day, used: now - 4 * 60e3, expires: now + 60 * day },
  { id: 'k2', name: 'nightly export', prefix: 'sk_live_c9Lm', scope: 'read', created: now - 300 * day, used: now - 15 * 3600e3, expires: null },
  { id: 'k3', name: 'migration script', prefix: 'sk_live_Pw41', scope: 'admin', created: now - 20 * day, used: null, expires: now + 10 * day },
];
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const random = () => Array.from({ length: 32 }, () => 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'[Math.floor(Math.random() * 56)]).join('');

export default function ApiKeys({ state = 'ready' }: { state?: 'ready' | 'loading' | 'empty' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [keys, setKeys] = useState<Key[]>(state === 'empty' ? [] : seed);
  const [creating, setCreating] = useState(false);
  const [problems, setProblems] = useState<FormProblem[]>([]);
  const [secret, setSecret] = useState<string | null>(null);
  const [saved, setSaved] = useState(false);
  const [revoking, setRevoking] = useState<Key | null>(null);
  // Loading: the real page, with only the values as skeletons, as long as the values of the last visit (`seed` here).
  const loading = state === 'loading';
  const create = async (v: FormData) => {
    await wait(900);
    const name = String(v.get('name')).trim();
    if (keys.some((k) => k.name === name)) { setProblems([{ name: 'name', label: c.name, message: c.taken }]); return; }
    const value = `sk_live_${random()}`, days = Number(v.get('expiry'));
    setKeys((l) => [{ id: value, name, prefix: value.slice(0, 12), scope: String(v.get('scope')) as Key['scope'], created: now, used: null, expires: days ? now + days * day : null }, ...l]);
    setCreating(false); setSaved(false); setSecret(value);
  };
  const createButton = <Button variant="primary" icon="key" onClick={() => { setProblems([]); setCreating(true); }}>{c.create}</Button>;
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} actions={createButton} />
      <Panel title={c.publishable}>
        <Stack gap={3}><Text size="sm" tone="muted">{c.publishableD}</Text>{loading ? <SkeletonOf><CopyField value="pk_live_northwind_shop_4f9a2c7e1b" label={c.publishable} /></SkeletonOf> : <CopyField value="pk_live_northwind_shop_4f9a2c7e1b" label={c.publishable} />}</Stack>
      </Panel>
      <Panel title={c.secret} flush>
        <Table label={c.secret} rows={loading ? undefined : keys} rowKey={(k) => k.id} loading={loading} loadingRows={seed.length}
          empty={<EmptyState icon="key" compact title={c.emptyTitle} actions={createButton}>{c.emptyBody}</EmptyState>}
          columns={[
            { id: 'name', header: c.name, cell: (k) => <Stack gap={1}><b>{k.name}</b><InlineCode>{k.prefix}…</InlineCode></Stack>,
              skeleton: (i) => <Stack gap={1}><b><SkeletonWords>{seed[i].name}</SkeletonWords></b><SkeletonOf><InlineCode>{seed[i].prefix}…</InlineCode></SkeletonOf></Stack> },
            { id: 'scope', header: c.scope, cell: (k) => (k.scope === 'admin' ? <Badge tone="warn">{c.scopes.admin}</Badge> : <Tag>{c.scopes[k.scope]}</Tag>), skeleton: (i) => <SkeletonOf><Tag>{c.scopes[seed[i].scope]}</Tag></SkeletonOf> },
            { id: 'used', header: c.lastUsed, cell: (k) => (k.used ? format.relative(new Date(k.used), now) : c.never), skeleton: (i) => <SkeletonWords>{seed[i].used ? format.relative(new Date(seed[i].used!), now) : c.never}</SkeletonWords> },
            { id: 'ends', header: c.ends, cell: (k) => (k.expires ? format.date(new Date(k.expires)) : c.noEnd), skeleton: (i) => <SkeletonWords>{seed[i].expires ? format.date(new Date(seed[i].expires!)) : c.noEnd}</SkeletonWords> },
            { id: 'act', header: '', actions: true, skeleton: <SkeletonOf><RowActions label="" actions={[]} /></SkeletonOf>, cell: (k) => <RowActions label={c.actions(k.name)} actions={[
              { id: 'roll', label: c.roll, icon: 'refresh', onAction: () => toast(c.rolled(k.name), { tone: 'ok' }) },
              { id: 'revoke', label: c.revoke, icon: 'ban', danger: true, onAction: () => setRevoking(k) },
            ]} /> },
          ]} />
      </Panel>
      <Dialog open={creating} onClose={() => setCreating(false)} title={c.create}>
        <Form label={c.create} problems={problems} validate={(v) => (String(v.get('name') ?? '').trim() ? [] : [{ name: 'name', label: c.name, message: c.noName }])} onSubmit={create}>
          {({ errorFor }) => (
            <>
              <Field label={c.name} hint={c.nameHint} error={errorFor('name')}><Input name="name" onChange={() => setProblems([])} /></Field>
              <Field label={c.scope}><RadioCards name="scope" options={c.scopeOptions} defaultValue="write" /></Field>
              <Field label={c.expiry}><Select name="expiry" defaultValue="90" options={[...[30, 90, 365].map((n) => ({ value: String(n), label: c.days(n) })), { value: '0', label: c.noExpiry }]} /></Field>
              <FormActions submitLabel={c.create} busyLabel={c.creating} />
            </>
          )}
        </Form>
      </Dialog>
      <Dialog open={secret !== null} onClose={() => saved && setSecret(null)} dismissable={false} dirty={!saved} title={c.saveTitle}
        footer={<Button variant="primary" disabled={!saved} onClick={() => setSecret(null)}>{c.done}</Button>}>
        {secret && <Stack gap={4}><p>{c.saveLead}</p><CopyField value={secret} label={c.key} secret once /><Checkbox label={c.saved} checked={saved} onChange={(e) => setSaved(e.target.checked)} /></Stack>}
      </Dialog>
      <ConfirmDialog open={revoking !== null} title={revoking ? c.revokeQ(revoking.name) : ''} action={c.revoke} confirmWord={revoking?.name} onClose={() => setRevoking(null)}
        onConfirm={() => { setKeys((l) => l.filter((k) => k.id !== revoking!.id)); toast(c.revoked(revoking!.name), { tone: 'ok' }); setRevoking(null); }}>
        <Callout kind="danger">{revoking ? c.revokeBody(revoking.name) : ''}</Callout>
      </ConfirmDialog>
      <Toaster />
    </Page>
  );
}

En un celular

En un celular cada llave es una tarjeta con sus acciones en la esquina.

Aún no hay llaves secretas

Para qué sirve una llave secreta, y el botón para crearla.

Llaves de API

Cómo tus apps y servidores prueban que pueden usar northwind-shop.

Llave publicable

Segura en un navegador o una app móvil: solo hace lo que permite la seguridad por fila.

Llaves secretas

Aún no hay llaves secretas

Tu servidor necesita una para escribir en northwind-shop. Para navegadores basta la llave publicable de arriba.

Skeleton

La página real mientras cargan las llaves: la llave publicable espera en su caja, y la tabla conserva sus columnas con tantas filas como en la última visita, cada valor tan largo como uno real.

Llaves de API

Cómo tus apps y servidores prueban que pueden usar northwind-shop.

Llave publicable

Segura en un navegador o una app móvil: solo hace lo que permite la seguridad por fila.

Llaves secretas

NombreAlcanceÚltimo usoVence

Cuándo usarlo

Úsalo cuando

  • Todo proyecto al que llaman apps o servidores.
  • Mostrar el último uso de cada llave, para revocar las viejas con confianza.

No lo uses cuando

  • Mostrar una llave secreta de nuevo después de creada.
  • Llaves sin nombre o sin vencimiento: pide un nombre y sugiere un vencimiento.

Para todos

  • Las acciones de cada llave son un solo botón nombrado con la llave.
  • Revocar pide escribir el nombre de la llave y dice qué apps dejan de funcionar.
  • El diálogo de la llave nueva no se cierra hasta que la persona dice que la guardó.

Props

CopyFieldTipoPor defecto
valueobligatorio string
label string
once boolean
secret boolean
RowActionsTipoPor defecto
actionsobligatorio RowAction[]
label

The name of the button, saying which row it belongs to: «Actions for order 1042».

string
ConfirmDialogTipoPor defecto
actionobligatorio

The confirm button says exactly what it does: «Delete table», never «OK».

string
onCloseobligatorio () => void
onConfirmobligatorio () => void
titleobligatorio

The question, naming the thing: «Delete the table orders?»

ReactNode
busy boolean
children

What will happen, in plain words, and whether it can be undone.

ReactNode
confirmWord

For the most destructive actions: the person must type this word (usually the name of the thing) to enable the button.

string
open boolean true
tone

danger: it cannot be undone. primary: it can, but it matters.

"primary" | "danger" danger
  1. En un computador
  2. En un celular
  3. Aún no hay llaves secretas
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos