独家

Reveal Once <mv-reveal-once>

只能显示一次的密钥的完整交付步骤(API 密钥、个人访问令牌、webhook 签名密钥、2FA 恢复码、临时密码、钱包助记词),没有计时器:值会一直保留到用户不再需要为止,但用户必须确认已保存才能继续。

文化出处

《工作与时日》(潘多拉之罐的神话),赫西俄德(约公元前 700 年,神话)。罐子一旦打开,跑出来的东西就再也无法放回:打开是不可逆的行为,值得事先想一想,事后只留下一丝痕迹。在 UI 中,一次性密钥只有在明确警告之后才会显示,未确认已保存就无法离开,之后只保留它的指纹和替换它的方法。

工作原理

只能显示一次的密钥的完整交付步骤(API 密钥、个人访问令牌、webhook 签名密钥、2FA 恢复码、临时密码、钱包助记词),没有计时器:值会一直保留到用户不再需要为止,但用户在确认已保存之前无法继续。显示之前,DOM 中没有任何机密内容:一个与值的形状完全一致的点状占位符,一句明确说明它只会显示一次的提示,一个“Have ready”清单(密码管理器、环境变量的访问权限),以及一个 Reveal 按钮,或带填充进度条的长按操作(键盘上按住空格键,屏幕阅读器则需激活两次)。显示之后,值以等宽字体分块呈现(prc_live_ 这样的前缀单独分开,从末尾起每 4 个字符一组,数字和符号着色以免混淆 0/O 和 1/l,屏幕阅读器会逐字符朗读),并提供 Copy(确认提示,可选自动清空剪贴板)、针对恢复码的 Download .txt 和 Print,以及 Hide 切换。一道关卡会锁住 Continue,直到勾选复选框,或在高风险模式下,在值隐藏的状态下重新输入最后 4 个字符(或一个随机代码或单词)。在此期间离开会受到 beforeunload、可取消的 mv-leave 以及应用内导航时内联的“Leave without saving?”拦截。之后,值会从 DOM 和内存中清除,只保留永久的指纹(“prc_live_…9f3a · Created Sep 24 by you”,最后一组字符滑入到位),“Lost it? Rotate”会经过一次确认和可取消的 mv-rotate,其 waitUntil 可以返回新密钥,再显示一次。

分类数据展示
类型Web Component(<mv-reveal-once>)
状态稳定版
套件安全处理破坏性操作和机密信息
同时安装button, 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

安装

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

使用 Marvelous UI MCP 服务器的 AI 智能体:install_components({ slugs: ["reveal-once"], target_dir: "<absolute path>/src/marvelous", framework: "react" })。

复制的文件(含依赖):tokens/tokens.css, core/base.css, components/button/button.css, components/checkbox/checkbox.css, components/input/input.css, core/dom.js, core/element.js, core/motion.js, components/reveal-once/reveal-once.js, components/reveal-once/reveal-once.css。

用法

快速开始,最小可运行标记:

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

标准标记,可在此基础上通过属性、data-* 和 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>

API

Attributes

Name类型DefaultDescription
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

Name类型Description
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.

本页面由 AI 翻译。报告翻译问题