Ir al contenido

SecretReveal

Un secreto se muestra una vez, cuando se crea, y nunca más. El diálogo que lo muestra no se cierra por accidente, y «Listo» espera hasta que la persona dice que lo guardó.

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

En esta página
  1. En un computador
  2. En un celular
  3. Cuando no se puede crear la llave
  4. Cuándo usarlo
  5. Para todos
  6. Props

En un computador

Pulsa «Crear una llave»: el diálogo se abre al instante con sus palabras mientras la llave espera en su propia caja, y luego llega la llave. Intenta cerrarlo antes de marcar la casilla.

Llaves de API

Dónde se usará, para distinguir las llaves: «servidor de pagos».

Código
import { useState } from 'react';
import {
  Alert, Button, Callout, Checkbox, CopyField, Dialog, Field, Input, Notice, Panel, SkeletonOf, Snippet, Stack, Toaster, toast, useSypnia,
} from '@sypnia/ui/react';

// A secret is shown once, at the moment it is made, and never again: only its first characters stay visible. The
// dialog cannot be closed by accident while the secret is on screen, and «Done» waits until the person says they saved it.
const en = {
  panel: 'API keys', create: 'Create a key', name: 'Name of the key', nameHint: 'Where it will be used, so you can tell keys apart: «checkout server».',
  title: 'Save your new key', lead: 'Copy it now and keep it somewhere safe, like your password manager or your server’s environment.',
  once: 'This is the only time the whole key is shown. If you lose it, create a new one and delete this one.', keyLabel: 'Secret key',
  env: 'Use it as an environment variable', saved: 'I saved the key somewhere safe', done: 'Done', creating: 'Creating…',
  noName: 'Give the key a name first.', failed: 'The key could not be created', failedBody: 'Nothing was made, so nothing needs cleaning up. Try again.', retry: 'Try again',
  made: (n: string) => `The key «${n}» is ready`, after: (n: string, p: string) => `«${n}» now shows only as ${p}… in your list.`,
};
const es: typeof en = {
  panel: 'Llaves de API', create: 'Crear una llave', name: 'Nombre de la llave', nameHint: 'Dónde se usará, para distinguir las llaves: «servidor de pagos».',
  title: 'Guarda tu llave nueva', lead: 'Cópiala ahora y guárdala en un lugar seguro, como tu gestor de contraseñas o el entorno de tu servidor.',
  once: 'Esta es la única vez que se muestra la llave completa. Si la pierdes, crea una nueva y borra esta.', keyLabel: 'Llave secreta',
  env: 'Úsala como variable de entorno', saved: 'Guardé la llave en un lugar seguro', done: 'Listo', creating: 'Creando…',
  noName: 'Primero ponle un nombre a la llave.', failed: 'No se pudo crear la llave', failedBody: 'No se creó nada, así que no hay nada que limpiar. Intenta de nuevo.', retry: 'Intentar de nuevo',
  made: (n: string) => `La llave «${n}» está lista`, after: (n: string, p: string) => `«${n}» ahora se ve solo como ${p}… en tu lista.`,
};
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const sample = `sk_live_${'x'.repeat(32)}`; // as long as a real key
const newKey = () => `sk_live_${Array.from({ length: 32 }, () => 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'[Math.floor(Math.random() * 56)]).join('')}`;

export default function SecretReveal({ state = 'ready' }: { state?: 'ready' | 'error' }) {
  const { locale } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [name, setName] = useState('checkout server');
  const [nameError, setNameError] = useState<string>();
  const [busy, setBusy] = useState(false);
  const [failed, setFailed] = useState(state === 'error');
  const [secret, setSecret] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [saved, setSaved] = useState(false);
  const [last, setLast] = useState<string>();
  const create = async () => {
    if (!name.trim()) { setNameError(c.noName); return; }
    setBusy(true); setFailed(false); setSaved(false);
    await wait(500);
    if (state === 'error') { setBusy(false); setFailed(true); return; }
    setOpen(true); // the dialog opens at once; its body is a skeleton until the key arrives
    await wait(1200);
    setBusy(false); setSecret(newKey());
  };
  const close = () => {
    toast(c.made(name), { tone: 'ok' });
    setLast(c.after(name, secret!.slice(0, 12))); setOpen(false); setSecret(null);
  };
  return (
    <>
      <Panel title={c.panel}>
        <Stack gap={4}>
          {failed && <Alert tone="fail" title={c.failed} actions={<Button size="sm" icon="refresh" onClick={create}>{c.retry}</Button>}>{c.failedBody}</Alert>}
          <Field label={c.name} hint={c.nameHint} error={nameError}><Input value={name} onChange={(e) => { setName(e.target.value); setNameError(undefined); }} /></Field>
          <div><Button variant="primary" icon="key" busy={busy} onClick={create}>{busy ? c.creating : c.create}</Button></div>
          {last && <Notice tone="ok">{last}</Notice>}
        </Stack>
      </Panel>
      {/* The dialog opens at once with its real words; until the key arrives, the key, the command and the box wait in
          their own boxes (a key of the same length), so nothing moves when it comes. */}
      <Dialog open={open} onClose={() => saved && close()} dismissable={false} dirty={!saved} title={c.title}
        footer={<Button variant="primary" disabled={!saved} onClick={close}>{c.done}</Button>}>
        <Stack gap={4}>
          <p>{c.lead}</p>
          <Field label={c.keyLabel}>{secret ? <CopyField value={secret} label={c.keyLabel} secret /> : <SkeletonOf><CopyField value={sample} label={c.keyLabel} secret /></SkeletonOf>}</Field>
          <Callout kind="warn">{c.once}</Callout>
          <Stack gap={2}><strong>{c.env}</strong>{secret ? <Snippet code={`export SYPNIA_KEY=${secret}`} label={c.env} /> : <SkeletonOf><Snippet code={`export SYPNIA_KEY=${sample}`} label={c.env} /></SkeletonOf>}</Stack>
          {secret ? <Checkbox label={c.saved} checked={saved} onChange={(e) => setSaved(e.target.checked)} /> : <Checkbox label={c.saved} disabled />}
        </Stack>
      </Dialog>
      <Toaster />
    </>
  );
}

En un celular

En un celular el diálogo ocupa la pantalla y los botones se quedan abajo.

Cuando no se puede crear la llave

No se creó nada, así que no hay nada que limpiar: dilo, y ofrece intentar de nuevo.

Llaves de API

Dónde se usará, para distinguir las llaves: «servidor de pagos».

Cuándo usarlo

Úsalo cuando

  • Llaves de API, secretos de firma, códigos de recuperación, contraseñas de bases de datos: todo lo que el servidor guarda solo como hash.
  • Mostrar cómo usar el secreto ahí mismo: la variable de entorno, lista para copiar.

No lo uses cuando

  • Mostrar el secreto de nuevo más tarde: guarda solo sus primeros caracteres y ofrece crear uno nuevo.
  • Cerrar con un clic afuera: la persona perdería un secreto que no podrá volver a ver.

Para todos

  • El diálogo toma el foco y lo conserva; Escape y un clic afuera no lo cierran mientras el secreto no esté guardado.
  • Copiar dice «Copiado» a los lectores de pantalla; el valor oculto tiene un botón para mostrarlo, con su estado.
  • «Listo» está deshabilitado, no oculto, hasta marcar la casilla, así la persona sabe qué falta.

Props

CopyFieldTipoPor defecto
valueobligatorio string
label string
once boolean
secret boolean
DialogTipoPor defecto
onCloseobligatorio () => void
titleobligatorio ReactNode
dirty

The form inside has changes that are not saved. A press outside or Escape then does not close it and does not lose them: the panel nudges and says to save or cancel. Only the buttons close it.

boolean
dismissable

Whether a press on the backdrop (outside the panel) closes it. On by default; Escape always closes it too. Set false for a form that must be finished or cancelled with its buttons.

boolean
footer

Buttons at the bottom, inside <Actions>.

ReactNode
lines

How many lines of skeleton the body shows while loading.

number
loading

What it shows is on its way: the title and the buttons stay, the body is lines of skeleton.

boolean
open

Whether it is open. It can also simply be mounted and unmounted: it is open while mounted.

boolean
size "sm" | "md" | "lg" | "xl" md
  1. En un computador
  2. En un celular
  3. Cuando no se puede crear la llave
  4. Cuándo usarlo
  5. Para todos
  6. Props

    Busca páginas, secciones y términos