Exclusifbêta

Reveal Once <mv-reveal-once>

L’étape complète de remise d’un secret qui ne peut être affiché qu’une seule fois (clé d’API, jeton d’accès personnel, secret de signature de webhook, codes de récupération 2FA, mot de passe temporaire, phrase de récupération de portefeuille), sans minuteur : la valeur reste affichée aussi longtemps que nécessaire, mais l’utilisateur ne peut pas continuer sans confirmer qu’il l’a enregistrée. Avant, rien de secret n’est dans le DOM : un espace réservé en pointillés qui reprend la forme exacte de la valeur, une mention claire indiquant qu’elle ne sera affichée qu’une fois, une liste « À préparer » (gestionnaire de mots de passe, accès à vos variables d’environnement) et un bouton Révéler, ou un appui maintenu avec une barre qui se remplit (Espace maintenu au clavier, deux activations pour les lecteurs d’écran). Une fois révélée, la valeur s’affiche en police à chasse fixe, découpée en blocs (préfixe comme prc_live_ tenu à part, groupes de 4 comptés depuis la fin, chiffres et symboles teintés pour ne jamais confondre 0/O et 1/l, épelée caractère par caractère pour les lecteurs d’écran), avec Copier (confirmation, effacement automatique du presse-papiers facultatif), Télécharger en .txt et Imprimer pour les codes de récupération, et une bascule Masquer. Un verrou bloque Continuer jusqu’à ce qu’une case soit cochée ou, en mode à fort enjeu, jusqu’à ce que les 4 derniers caractères (ou un code ou un mot aléatoire) soient ressaisis, valeur masquée. Quitter entre-temps est protégé par beforeunload, un mv-leave annulable et un « Quitter sans enregistrer ? » inline pour la navigation interne à l’application. Après, la valeur est effacée du DOM et de la mémoire, et seule une empreinte permanente subsiste (« prc_live_…9f3a · Créé le 24 sept. par vous », le dernier groupe glissant en place), avec « Perdu ? Renouveler », qui passe par une confirmation et un mv-rotate annulable dont le waitUntil peut renvoyer le nouveau secret, à afficher une fois de plus.

CatégorieAffichage de données
TypeWeb Component (<mv-reveal-once>)
Statutbêta
KitActions destructives et secrets en sécurité
Installe aussibutton, checkbox, input
Keywordsexclusive, culture, secret, one-time, api-key, token, access-token, recovery-codes, backup-codes, seed-phrase, password, webhook-secret, reveal, copy, clipboard, download, print, fingerprint, rotate, acknowledge, confirmation, leave-guard, beforeunload, security, onboarding, hold-to-reveal

When to use

  • A freshly created API key or access token must be shown once, and users keep closing the page before saving it
  • Two-factor recovery codes or a seed phrase must be downloaded, printed or copied and acknowledged before setup can finish
  • A settings page lists existing keys by fingerprint only and offers to rotate one that was lost
  • Compliance requires proof that the user acknowledged storing a credential that will never be displayed again

Avoid when

  • The secret should disappear on its own after a short, timed read, even if the user walks away → use Self-Destruct instead
  • Sensitive data stays retrievable but every opening must leave an audited trace → use Tamper Seal instead
  • The value is not sensitive and should stay visible and copyable at any time → use Copy Button instead

Installation

node scripts/add.mjs reveal-once --out ./src/marvelous

Agent IA avec le serveur MCP Marvelous UI : install_components({ slugs: ["reveal-once"], target_dir: "<absolute path>/src/marvelous", framework: "react" }).

Fichiers copiés (dépendances comprises) : tokens/tokens.css, core/base.css, core/dom.js, core/element.js, core/motion.js, components/reveal-once/reveal-once.js, components/reveal-once/reveal-once.css, components/button/button.css, components/checkbox/checkbox.css, components/input/input.css.

Utilisation

Démarrage rapide, le balisage minimal qui fonctionne :

<mv-reveal-once label="Production API key">
  <template>prc_live_8f2c9a71d04be63c5e1a</template>
</mv-reveal-once>

Balisage de référence : partez de celui-ci et personnalisez-le avec les attributs, data-* et les variables CSS :

<div id="ro-demo" style="width:min(100%,66rem);margin-inline:auto">
  <style>
    #ro-demo { display:grid; gap:1.25rem }
    #ro-demo .ro-app { border:1px solid var(--mv-border); border-radius:var(--mv-radius-xl); background:var(--mv-bg-subtle); overflow:hidden }
    #ro-demo .ro-bar { display:flex; align-items:center; gap:.75rem; height:3.25rem; padding:0 1.125rem; border-bottom:1px solid var(--mv-border); background:var(--mv-surface) }
    #ro-demo .ro-brand { display:flex; align-items:center; gap:.5rem; font-weight:650; font-size:.9375rem; letter-spacing:-.01em }
    #ro-demo .ro-logo { display:grid; place-items:center; width:1.75rem; height:1.75rem; border-radius:var(--mv-radius-md); background:var(--mv-accent); color:var(--mv-fg-on-accent) }
    #ro-demo .ro-logo svg { width:1rem; height:1rem }
    #ro-demo .ro-crumbs { display:flex; gap:.375rem; color:var(--mv-fg-muted); font-size:.8125rem }
    #ro-demo .ro-crumbs b { color:var(--mv-fg); font-weight:500 }
    #ro-demo .ro-body { display:grid; grid-template-columns:minmax(0,1fr) 16rem; gap:1.25rem; padding:1.25rem }
    #ro-demo .ro-side { display:grid; gap:1rem; align-content:start }
    #ro-demo .ro-panel { display:grid; gap:.75rem; padding:1rem; border:1px solid var(--mv-border); border-radius:var(--mv-radius-lg); background:var(--mv-surface) }
    #ro-demo .ro-panel h4 { margin:0; font-size:.8125rem; font-weight:600 }
    #ro-demo .ro-panel p { margin:0; color:var(--mv-fg-muted); font-size:.75rem; line-height:1.5 }
    #ro-demo .ro-row { display:flex; align-items:center; justify-content:space-between; gap:.75rem; font-size:.8125rem }
    #ro-demo .ro-btns { display:flex; flex-wrap:wrap; gap:.5rem }
    #ro-demo .ro-log { display:grid; gap:.25rem; margin:0; padding:0; list-style:none; min-height:4.5rem; color:var(--mv-fg-muted); font:.6875rem/1.45 var(--mv-font-mono) }
    #ro-demo .ro-log li:first-child { color:var(--mv-fg) }
    #ro-demo .ro-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,22rem),1fr)); gap:1.25rem; align-items:start }
    #ro-demo .ro-cap { display:flex; align-items:center; gap:.5rem; margin:0 0 .5rem; color:var(--mv-fg-muted); font-size:.75rem; font-weight:500 }
    @media (max-width:46rem) { #ro-demo .ro-body { grid-template-columns:minmax(0,1fr) } }
  </style>

  <!-- 1 · A key was just created in developer settings: the “before” state -->
  <section class="ro-app" aria-label="Developer settings">
    <header class="ro-bar">
      <span class="ro-brand">
        <span class="ro-logo" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 8 12 3.5 20.5 8v8L12 20.5 3.5 16z"/><path d="M3.5 8 12 12.5 20.5 8M12 12.5v8"/></svg></span>
        Parcelo
      </span>
      <span class="ro-crumbs" aria-hidden="true">/ Developers / <b>API keys</b></span>
    </header>
    <div class="ro-body">
      <mv-reveal-once id="ro-key" label="Production API key" created-by="you"
        prepare="A password manager or secrets vault, Access to your server’s environment variables"></mv-reveal-once>

      <div class="ro-side">
        <div class="ro-panel">
          <h4>Options</h4>
          <label class="ro-row">Hold to reveal <input type="checkbox" role="switch" class="mv-switch" data-size="sm" id="ro-hold"></label>
          <label class="ro-row">Retype to confirm <input type="checkbox" role="switch" class="mv-switch" data-size="sm" id="ro-retype"></label>
          <div class="ro-btns">
            <button type="button" class="mv-button" data-variant="outline" data-size="sm" id="ro-leave">Leave page</button>
            <button type="button" class="mv-button" data-variant="ghost" data-size="sm" id="ro-new">New key</button>
          </div>
        </div>
        <div class="ro-panel">
          <h4>Events <span class="mv-badge" data-variant="secondary" data-size="sm">never the secret</span></h4>
          <ul class="ro-log" id="ro-log" aria-live="off"><li>Key created. Waiting for reveal.</li></ul>
        </div>
      </div>
    </div>
  </section>

  <div class="ro-grid">
    <!-- 2 · Two-factor recovery codes: revealed, download + print, retype one code to confirm -->
    <div>
      <p class="ro-cap"><span class="mv-badge" data-variant="warning" data-size="sm">During</span> Recovery codes, retype a code to confirm</p>
      <mv-reveal-once id="ro-codes" label="Recovery codes" confirm="retype" downloadable filename="parcelo-recovery-codes" printable clear-clipboard="60"></mv-reveal-once>
    </div>

    <!-- 3 · A webhook signing secret saved last month: only its fingerprint remains -->
    <div>
      <p class="ro-cap"><span class="mv-badge" data-variant="success" data-size="sm">After</span> Webhook signing secret, saved in August</p>
      <mv-reveal-once id="ro-hook" label="Webhook signing secret" fingerprint="whk_…c81d" created="2026-08-03T10:20:00" created-by="Priya Nair"></mv-reveal-once>
    </div>
  </div>

  <script type="module">
    const $ = (id) => document.getElementById(id);
    const key = $("ro-key"), codes = $("ro-codes"), hook = $("ro-hook"), log = $("ro-log");
    const ABC = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
    const rand = (n, set = ABC) => Array.from(crypto.getRandomValues(new Uint32Array(n)), (v) => set[v % set.length]).join("");
    const newKey = () => `prc_live_${rand(32)}`;
    const newCodes = () => Array.from({ length: 10 }, () => `${rand(4, "abcdefghjkmnpqrstuvwxyz23456789")}-${rand(4, "abcdefghjkmnpqrstuvwxyz23456789")}`);
    const time = () => new Date().toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", second: "2-digit" });
    const say = (text) => {
      log.prepend(Object.assign(document.createElement("li"), { textContent: `${time()} ${text}` }));
      while (log.children.length > 5) log.lastElementChild.remove();
    };

    await customElements.whenDefined("mv-reveal-once");
    // Secrets are set from JS (never server-rendered into the page).
    key.secret = newKey();
    codes.secret = newCodes();
    codes.reveal();

    // Event details carry facts, never the value.
    key.addEventListener("mv-reveal", () => say("mv-reveal"));
    key.addEventListener("mv-copy", (e) => say(`mv-copy · ${e.detail.method}`));
    key.addEventListener("mv-saved", (e) => say(`mv-saved · ${e.detail.method}${e.detail.copied ? " · copied" : ""} · ${e.detail.fingerprint}`));
    key.addEventListener("mv-leave", (e) => say(`mv-leave · ${e.detail.reason} (${e.detail.state})`));
    key.addEventListener("mv-rotate", (e) => {
      say(`mv-rotate · revoking ${e.detail.fingerprint}`);
      e.detail.waitUntil(new Promise((r) => setTimeout(() => r(newKey()), 700)));
    });

    $("ro-hold").addEventListener("change", (e) => { key.hold = e.target.checked; });
    $("ro-retype").addEventListener("change", (e) => { key.confirm = e.target.checked ? "retype" : "checkbox"; });
    $("ro-leave").addEventListener("click", async () => {
      const ok = await key.leave();
      say(ok ? "Navigation allowed" : "Stayed on the page");
    });
    $("ro-new").addEventListener("click", () => { key.secret = newKey(); say("New key created"); });

    // Rotation: the server issues a new secret; the component shows it once again.
    for (const el of [codes, hook]) {
      el.addEventListener("mv-rotate", (e) => {
        e.detail.waitUntil(new Promise((r) => setTimeout(() => r(el === codes ? newCodes() : `whk_${rand(32)}`), 700)));
      });
    }
  </script>
</div>

Référence culturelle

Les Travaux et les Jours (le mythe de la jarre de Pandore), Hésiode (v. 700 av. J.-C., mythe). Une fois la jarre ouverte, ce qui en sort ne peut plus y retourner : l’ouverture est un acte sans retour qui mérite d’abord un moment de réflexion, et il n’en reste qu’une trace. Dans l’interface, un secret à usage unique n’est révélé qu’après un avertissement clair, ne peut pas être abandonné sans confirmer qu’il a été enregistré, et ensuite il n’en reste que l’empreinte et un moyen de le remplacer.

API

Attributes

NameTypeDefaultDescription
labelstringSecretWhat the secret is (“Production API key”, “Recovery codes”): title, accessible name, and the noun used in every sentence (“I’ve saved this production API key somewhere safe”).
holdbooleanPress-and-hold to reveal: a bar fills the button for hold-duration; releasing early rewinds it. Keyboard: hold Space or Enter. A click with no press behind it (screen reader, switch access) arms the button and a second activation within 6 s reveals.
hold-durationnumber (ms)900How long the hold lasts (250-5000). The fill still runs under reduced motion because it carries the time left.
confirmcheckbox | retypecheckboxThe gate before Continue. checkbox: “I’ve saved this … somewhere safe”. retype (high stakes): type the last 4 characters of a key, or a random code / word (#n) of a list; focusing the field hides the value so it has to come from the saved copy. Case, spaces and dashes are ignored.
formatauto | key | list | wordsautoHow the value is shown. auto: an array or several lines is a numbered list (codes), 12+ lowercase words a seed phrase (words, never spelled out), anything else a key. Read when the secret is loaded.
groupnumber4Chunk size for keys and for list items longer than 8 characters, counted from the end so the last chunk is the fingerprint’s tail. 0 disables. Values that carry their own dashes or spaces (temporary passwords, dashed codes) keep them instead.
key-prefixstring | "none"Prefix kept apart and always visible (it is part of the fingerprint). Auto-detected when omitted: one or two lowercase segments ending with _ or - (prc_live_, ghp_, whk_).
tailnumber4Trailing characters kept in the fingerprint (0-8). Use 0 for passwords: the fingerprint then shows only the prefix and ••••.
downloadablebooleanShows Download .txt: a plain-text file with the label, creation line, the value (numbered for lists) and a safekeeping note.
filenamestringDownload file name (.txt added if missing). Default: the label in kebab-case.
printablebooleanShows Print: prints only the value, label and creation line from a hidden, throwaway frame (never the rest of the page).
clear-clipboardnumber (s)After a copy, overwrites the clipboard with an empty string after this many seconds if the last copy in this document was the secret, and says so under the tools. Best effort: browsers refuse clipboard writes when the page is not focused.
maskedbooleanReflects the Hide / Show toggle while revealed (set it to start hidden, e.g. while screen sharing). Masked, the characters leave the DOM and only dots of the same length remain; the prefix stays.
createdISO dateCreation date shown as “Created Sep 24 by you” (year added when not the current one). Default: the moment the secret is loaded. Removed by a rotation that returns a new secret.
created-bystringyouWho created it. Empty string: “Created Sep 24”.
preparecomma listA password manager or secrets vaultThe “Have ready” checklist shown before the reveal. Empty string hides it.
fingerprintstringServer-provided fingerprint (“whk_…c81d”). Without a secret, the component starts directly in the done state: a keys settings page listing fingerprints with Rotate. Also overrides the computed one.
no-guardbooleanDisables the beforeunload prompt (mv-leave is then not emitted on unload; leave() still works).
data-stateempty | ready | revealed | doneSet by the component. Also data-holding, data-copied, data-downloaded, data-confirmed, data-masked-view, data-unconfirmed (done without confirmation), data-alert, data-pending (rotation in flight).

Properties

NameTypeDescription
secretstring | string[]Write-only: loads a secret in the ready state (a string, a multi-line string or an array). Reading it always returns null. Preferred over a <template> child, which is in the page source. Can be set before the element is defined.
state"empty" | "ready" | "revealed" | "done"Current phase (read-only).
fingerprintstring | nullThe fingerprint kept after the wipe (the attribute when set, otherwise computed: prefix…last 4, “10 codes”, “24-word phrase”).
guardedbooleanTrue while leaving would lose a secret nobody confirmed as saved (ready or revealed).
confirmed / copied / downloadedbooleanGate satisfied, value copied (button or manual selection), file downloaded (read-only).
stringsPartial<Record<string, string>>Overrides for every visible text and announcement ({label} = noun inside a sentence, {Label} = at the start). English defaults, e.g. noteTitle, noteText, prepare, reveal, holdReveal, holdHint, confirmCheck, retypeKey, retypeItem, retypeWord, continue, gateHint, doneText, lost, rotate, rotateTitle, rotateText, leaveTitle, leaveText, fingerprintList, fingerprintWords, announceReveal, announceCopied, announceSaved.

Methods

NameDescription
reveal()Shows the secret (ready → revealed), focuses it and emits mv-reveal. Returns false unless ready.
copy()Copies the value (Clipboard API, textarea fallback; lists one per line, words space-separated). Resolves to true on success.
download() / print()Same as the buttons; work even when the attributes hide them. Return false unless revealed.
finish({ force? })Ends the step as Continue does (emits mv-saved). Requires the gate unless force is true (method "api").
leave({ reason? })Call before an in-app navigation or closing a dialog. Resolves true when nothing is at risk or the user chose “Leave anyway” (the secret is then wiped, state done with data-unconfirmed), false if they stayed or mv-leave was canceled.
rotate({ confirm? })Opens the rotate confirmation (done state), or rotates right away with { confirm: false }. Resolves true once mv-rotate went through.

Events

NameDescription
mv-revealThe value was revealed. detail: { kind: "key" | "list" | "words", count }.
mv-copyThe value was copied. detail: { method: "button" | "keyboard" | "api" }, never the value.
mv-download / mv-printThe file was downloaded (detail: { filename }) or the print dialog opened.
mv-clipboard-clearThe clipboard was overwritten by clear-clipboard.
mv-savedCancelable. The user confirmed and pressed Continue. detail: { method: "checkbox" | "retype" | "api", copied, downloaded, fingerprint }. Record the acknowledgement on your server; preventDefault() keeps the secret on screen.
mv-leaveCancelable. The user is leaving with the secret not confirmed as saved. detail: { reason: "unload" | "navigate" | string, state }. preventDefault() suppresses the built-in warning (the beforeunload prompt or the inline “Leave without saving?”) so you can show your own; leave() then resolves false.
mv-rotateCancelable. Rotation confirmed. detail: { fingerprint, waitUntil(promise) }. Pass your revoke-and-regenerate request to waitUntil: the button shows a busy state, a rejection shows an error, and a promise resolving to a string or array loads it as the new secret (ready state, created now).

Content structure

NameDescription
<template> childAlternative to the secret property, read once at mount then removed: text (lines = list items) or <li> elements. It is visible in the page source, so prefer the property.

CSS classes

NameDescription
mv-reveal-once-head / -icon / -title / -meta / -badgeHeader: state icon (key, shield when saved), label, creation line, “Shown once” / “Saved” / “Not confirmed” badge (data-tone).
mv-reveal-once-stageThe value box (data-kind): -placeholder and -cover with -reveal (-hold-fill) and -hint when ready, -value when revealed, -fingerprint (-fp-prefix, -fp-ellipsis, -fp-tail, -fp-label) when done.
mv-reveal-once-chunk / -glyphs / -list / -item / -num / -wordRendered value: chunks carry data-prefix, data-sep, data-tail; digits and symbols are spans with data-k="d" | "s".
mv-reveal-once-note / -prepareBefore the reveal: the once-only statement and the “Have ready” list.
mv-reveal-once-tools / -btn / -cliphintCopy, Download, Print and Hide / Show buttons (data-feedback="done" | "error" after an action).
mv-reveal-once-gate / -check / -retype / -gate-hint / -continueThe saved-confirmation gate; Continue has data-locked until it is satisfied.
mv-reveal-once-record / -rotateAfter: what is kept and the “Lost it? Rotate” action.
mv-reveal-once-alertInline confirmation (data-kind="leave" | "rotate").

CSS variables

NameDefaultDescription
--mv-reveal-once-accentvar(--mv-accent)Revealed box ring and the dotted underline of the tail chunk.
--mv-reveal-once-digitinfo mixed with fgColor of digits in the value.
--mv-reveal-once-symboldanger mixed with fgColor of symbols in the value.
--mv-reveal-once-okvar(--mv-success)Saved badge, copied feedback, retype match.
--mv-reveal-once-warnvar(--mv-warning)“Shown once” badge, leave warning, unconfirmed state.
--mv-reveal-once-font-size0.9375remSize of the monospace value.
--mv-reveal-once-radiusvar(--mv-radius-xl)Corner radius of the card.

Accessibility

The element is a role=group named by its label. Before the reveal it holds no character of the secret: the dotted placeholder is aria-hidden and the Reveal button is described by a hint (“Press and hold, or hold Space. Make sure nobody can see your screen.”). Hold mode works with pointer, touch (no callout, no scroll) and Space or Enter held (key repeat ignored, blur releases); since assistive technologies activate buttons with a plain click and cannot hold, a click with no press behind it arms the button (“Activate again to reveal”, announced) and a second activation reveals. After the reveal, focus moves to the value (a labelled group, tabindex=-1) and a polite role=status region says it is shown only once. Keys are read character by character: each chunk has visually hidden spelled text (“9 f 3 a,”) while the visible glyphs are aria-hidden; the spelled text is excluded from selection so a manual copy stays exact. Codes are an ordered list, seed-phrase words are read as words. Copy, downloads, hiding and clearing the clipboard are announced; digits and symbols are tinted but never only by color (monospace, slashed zero). The gate is a real checkbox or a labelled text field with aria-invalid and a linked error; Continue stays focusable and, while locked, explains why and moves focus to the gate instead of doing nothing. The inline Leave / Rotate confirmation is a labelled group that receives focus on the safe choice (Stay / Cancel), Escape closes it and focus returns where it was. After saving, focus moves to the fingerprint, read as “Production API key ending in 9 f 3 a”. Reduced motion (OS or data-motion="reduce"): no unveil, no sliding fingerprint, no height animation; the hold fill still runs because it is the time left. Forced colors: system borders and a Highlight fill. Security: the value never appears in event details, logs or storage, the secret getter returns null, masking removes the characters from the DOM, the wipe happens before any animation, the page leaving (pagehide, including the back-forward cache) or the element being removed wipes an unconfirmed secret, and JavaScript strings cannot be zeroed, so “removed from memory” means every reference is dropped.

Cette page a été traduite par IA. Signaler un problème de traduction