diff --git a/popup/approve.css b/popup/approve.css index e0e0992..2f6adc8 100644 --- a/popup/approve.css +++ b/popup/approve.css @@ -6,14 +6,19 @@ */ body { - width: 380px; - min-height: 0; + width: 100%; + min-height: 100vh; } .approve { display: flex; flex-direction: column; - padding: 16px 16px 14px; + min-height: 100vh; +} + +.approve-body { + flex: 1 0 auto; + padding: 16px 16px 10px; } /* ---- Header ---- */ @@ -65,18 +70,18 @@ body { } .origin-eyebrow { - font-size: 10.5px; + font-size: 11px; font-weight: 700; text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--text-faint); + letter-spacing: 0.05em; + color: var(--text-muted); margin-bottom: 6px; } .origin-badge { display: block; font-family: var(--mono); - font-size: 14px; + font-size: 13.5px; font-weight: 600; line-height: 1.4; color: var(--text); @@ -115,54 +120,144 @@ body { /* ---- Preview ---- */ .preview-wrap { - margin-bottom: 12px; + margin-bottom: 10px; } .preview-label { - font-size: 10.5px; + font-size: 11px; font-weight: 700; text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--text-faint); + letter-spacing: 0.05em; + color: var(--text-muted); margin-bottom: 6px; } +.summary-list { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 8px 11px; + margin-bottom: 8px; +} + +.summary-row { + display: flex; + flex-direction: column; + gap: 2px; + padding: 5px 0; + border-top: 1px solid var(--border); +} + +.summary-row:first-child { + border-top: none; + padding-top: 0; +} + +.summary-row:last-child { + padding-bottom: 0; +} + +.summary-row dt { + font-size: 10.5px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--text-muted); +} + +.summary-row dd { + font-size: 12.5px; + color: var(--text); + overflow-wrap: anywhere; + white-space: pre-wrap; + max-height: 84px; + overflow-y: auto; +} + +.summary-row dd.mono { + font-family: var(--mono); + font-size: 11.5px; +} + +.raw-details { + font-size: 12px; + color: var(--text-muted); +} + +.raw-details summary { + cursor: pointer; + font-weight: 600; + padding: 3px 0; + color: var(--text-muted); +} + +.raw-details summary:focus-visible { + outline: none; + box-shadow: 0 0 0 3px var(--accent-ring); + border-radius: 4px; +} + .event-preview { + margin-top: 6px; background: var(--surface-inset); border: 1px solid var(--border); border-radius: var(--radius-sm); - padding: 11px 12px; + padding: 10px 11px; font-family: var(--mono); font-size: 11.5px; line-height: 1.5; color: var(--text-muted); - max-height: 150px; + max-height: 140px; overflow: auto; white-space: pre; word-break: normal; tab-size: 2; } -/* ---- Trust warning ---- */ -.trust-note { +/* ---- Sticky footer ---- */ +.approve-footer { + position: sticky; + bottom: 0; + padding: 12px 16px 14px; + background: var(--bg); + border-top: 1px solid var(--border); +} + +/* ---- Trust option ---- */ +.trust-toggle { display: flex; align-items: flex-start; - gap: 8px; - font-size: 11.5px; - line-height: 1.45; - color: var(--warn); - margin-bottom: 14px; + gap: 9px; padding: 9px 11px; - background: var(--warn-soft); - border: 1px solid var(--warn-border); + margin-bottom: 12px; + background: var(--surface); + border: 1px solid var(--border); border-radius: var(--radius-sm); + cursor: pointer; } -.trust-note svg { +.trust-toggle input { + margin-top: 2px; + accent-color: var(--accent); width: 15px; height: 15px; flex: none; - margin-top: 1px; + cursor: pointer; +} + +.trust-toggle-copy { + display: flex; + flex-direction: column; + gap: 2px; + font-size: 11.5px; + line-height: 1.4; + color: var(--text-muted); +} + +.trust-toggle-copy strong { + font-size: 12.5px; + font-weight: 600; + color: var(--text); } /* ---- Buttons ---- */ @@ -176,7 +271,7 @@ body { margin-bottom: 0; } -/* Deny = safe default: solid, visually settled, autofocused. */ +/* Deny = safe default: visually settled, autofocused. */ .btn-deny { background: var(--surface); color: var(--text); @@ -192,40 +287,40 @@ body { box-shadow: 0 0 0 3px var(--accent-ring); } -/* Approve = deliberate: outlined danger-tone, not pre-focused. */ +/* Approve = deliberate trust-blue primary, unlocked after brief grace delay. */ .btn-approve { - background: transparent; - color: var(--danger); - border: 1.5px solid var(--danger-border); + background: var(--accent-solid); + color: #fff; + border: 1px solid transparent; + box-shadow: var(--shadow-sm); } -.btn-approve:hover { - background: var(--danger-soft); - border-color: var(--danger); +.btn-approve:hover:not([disabled]) { + background: var(--accent-solid-hover); } .btn-approve:focus-visible { outline: none; - box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.3); + box-shadow: 0 0 0 3px var(--accent-ring); } /* ---- Countdown ---- */ .countdown { - margin-top: 12px; + margin-top: 10px; } .countdown-text { display: flex; align-items: center; justify-content: center; - gap: 6px; + gap: 4px; font-size: 11px; color: var(--text-muted); - margin-bottom: 7px; + margin-bottom: 6px; } .countdown-text strong { - color: var(--text-muted); + color: var(--text); font-variant-numeric: tabular-nums; font-weight: 700; } @@ -240,13 +335,18 @@ body { .timeout-bar-inner { height: 100%; width: 100%; - background: var(--text-faint); + background: var(--text-muted); border-radius: 999px; transform-origin: left center; - /* Width is driven from JS for an accurate, synced countdown. */ - transition: background 0.4s ease; + transition: width 0.25s linear, background 0.3s ease; } .timeout-bar-inner.urgent { background: var(--danger); } + +@media (prefers-reduced-motion: reduce) { + .timeout-bar-inner { + transition: none; + } +} diff --git a/popup/approve.html b/popup/approve.html index 0136260..45dc1a5 100644 --- a/popup/approve.html +++ b/popup/approve.html @@ -9,60 +9,66 @@
-
- -
-
Signing request
-
Review carefully before approving
+
+
+ +
+
Signing request
+
Review carefully before approving
+
-
-
-
Requested by
- -
+
+
Requested by
+ +
-
- - -
- -
-
Payload
-

-      
+
+ + +
-
- - Approving also trusts this site: from now on it can sign and read messages as you without asking. You can remove it under Trusted sites in Podkey. +
-
- - -
+
- + diff --git a/popup/approve.js b/popup/approve.js index 2c8f5ab..50775fd 100644 --- a/popup/approve.js +++ b/popup/approve.js @@ -2,18 +2,22 @@ * Podkey - Signing Approval Popup * Presents signing requests to the user for explicit approval/denial. * - * Security contract (must stay byte-equivalent in effect): + * Security contract: * - Read requestId/origin/action/preview from the query string. * - On a choice: chrome.runtime.sendMessage( - * { type: 'APPROVE_SIGNING', requestId, approved: }). - * - Closing the popup (beforeunload) sends approved:false (closing = deny). + * { type: 'APPROVE_SIGNING', requestId, approved: , trust: }). + * - Closing the popup (beforeunload) or pressing Escape sends approved:false. * - A 60-second auto-deny countdown denies if the user does nothing. + * - A brief anti-clickjacking grace delay keeps Approve disabled on initial paint. * - * The displayed origin and payload come from web pages and are treated as - * hostile strings: only ever written via textContent, never innerHTML. + * All origin and payload strings come from web pages and are written strictly + * via textContent, never innerHTML. */ +import { summarizePreview } from '../src/event-preview.js'; + const APPROVAL_TIMEOUT_MS = 60_000; +const APPROVE_GRACE_MS = 350; const params = new URLSearchParams(window.location.search); const requestId = params.get('id'); @@ -22,16 +26,17 @@ const action = params.get('action') || 'sign'; const preview = params.get('preview') || ''; // One-shot guard: the decision is sent exactly once, whichever path fires -// first (button click, auto-deny timeout, or window close). +// first (button click, Escape, auto-deny timeout, or window close). let decisionSent = false; -function sendDecision(approved) { +function sendDecision (approved, trust = false) { if (decisionSent) return; decisionSent = true; chrome.runtime.sendMessage({ type: 'APPROVE_SIGNING', requestId, - approved + approved, + trust: approved ? Boolean(trust) : false }); } @@ -40,44 +45,91 @@ function sendDecision(approved) { document.getElementById('origin').textContent = origin; document.getElementById('action').textContent = action; -const previewEl = document.getElementById('preview'); +const summary = summarizePreview(preview); const previewWrap = document.getElementById('previewWrap'); -if (preview) { - try { - // Pretty-print JSON payloads for readability; fall back to raw text. - const parsed = JSON.parse(preview); - previewEl.textContent = JSON.stringify(parsed, null, 2); - } catch { - previewEl.textContent = preview; +const summaryList = document.getElementById('summaryList'); +const previewEl = document.getElementById('preview'); +const rawDetails = document.getElementById('rawDetails'); + +if (summary) { + previewWrap.hidden = false; + previewEl.textContent = summary.rawText; + + if (summary.rows.length > 0) { + summaryList.hidden = false; + summaryList.replaceChildren(); + for (const row of summary.rows) { + const wrap = document.createElement('div'); + wrap.className = 'summary-row'; + const dt = document.createElement('dt'); + dt.textContent = row.label; + const dd = document.createElement('dd'); + dd.textContent = row.value; + if (row.mono) dd.className = 'mono'; + wrap.append(dt, dd); + summaryList.appendChild(wrap); + } + } else { + summaryList.hidden = true; + rawDetails.open = true; } -} else { - previewWrap.style.display = 'none'; } -// ---- Buttons ---- +// ---- Trust checkbox & dynamic Approve label ---- + +const trustCheckbox = document.getElementById('trustSite'); +const trustDesc = document.getElementById('trustDesc'); +const approveBtn = document.getElementById('approve'); +const denyBtn = document.getElementById('deny'); + +function syncApproveLabel () { + const willTrust = trustCheckbox.checked; + approveBtn.textContent = willTrust ? 'Approve & trust' : 'Approve once'; + trustDesc.textContent = willTrust + ? 'Future requests from this site will be signed automatically. You can revoke it anytime under Sites in Podkey.' + : 'Only this single request will be allowed. Podkey will ask again next time.'; +} + +trustCheckbox.addEventListener('change', syncApproveLabel); +syncApproveLabel(); -document.getElementById('approve').addEventListener('click', () => { - sendDecision(true); +// Brief anti-clickjacking grace period before Approve can be clicked. +setTimeout(() => { + if (!decisionSent) approveBtn.disabled = false; +}, APPROVE_GRACE_MS); + +// ---- Buttons & keyboard ---- + +approveBtn.addEventListener('click', () => { + sendDecision(true, trustCheckbox.checked); window.close(); }); -document.getElementById('deny').addEventListener('click', () => { - sendDecision(false); +denyBtn.addEventListener('click', () => { + sendDecision(false, false); window.close(); }); +window.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + e.preventDefault(); + sendDecision(false, false); + window.close(); + } +}); + // Closing the popup without choosing is a denial. window.addEventListener('beforeunload', () => { - sendDecision(false); + sendDecision(false, false); }); -// ---- 60-second auto-deny countdown ---- +// ---- 60-second auto-deny countdown (lightweight 250ms tick) ---- const countdownEl = document.getElementById('countdown'); const barEl = document.getElementById('timeoutBar'); const startedAt = Date.now(); -function tickCountdown() { +function tickCountdown () { if (decisionSent) return; const elapsed = Date.now() - startedAt; @@ -90,13 +142,12 @@ function tickCountdown() { barEl.classList.toggle('urgent', remainingSec <= 10); if (remainingMs <= 0) { - // Time is up: deny and close. - sendDecision(false); + sendDecision(false, false); window.close(); return; } - requestAnimationFrame(tickCountdown); + setTimeout(tickCountdown, 250); } -requestAnimationFrame(tickCountdown); +tickCountdown(); diff --git a/popup/spend.css b/popup/spend.css index bf17be5..00fdccb 100644 --- a/popup/spend.css +++ b/popup/spend.css @@ -6,7 +6,12 @@ */ body { - width: 440px; + width: 100%; + min-height: 100vh; +} + +.spend { + padding: 16px 16px 14px; } .spend [hidden] { @@ -65,7 +70,7 @@ body { position: relative; padding: 5px 0 5px 24px; font-size: 13px; - color: var(--text-faint); + color: var(--text-muted); } .step::before { diff --git a/popup/spend.html b/popup/spend.html index 24cc8c5..d9876a4 100644 --- a/popup/spend.html +++ b/popup/spend.html @@ -135,6 +135,9 @@
diff --git a/popup/spend.js b/popup/spend.js index 24c59a7..0e4cf52 100644 --- a/popup/spend.js +++ b/popup/spend.js @@ -42,7 +42,7 @@ const keepalive = setInterval(() => send({ type: 'SIDESTR_KEEPALIVE', id }).catc // ---- small formatters ----------------------------------------------------- -const sats = (n) => `${n.toLocaleString('en-GB')} sat${n === 1 ? '' : 's'}`; +const sats = (n) => `${n.toLocaleString()} sat${n === 1 ? '' : 's'}`; const short = (s, head = 12, tail = 6) => (s.length > head + tail + 1 ? `${s.slice(0, head)}…${s.slice(-tail)}` : s); const assetText = (a) => `${core.formatAsset(a.amount, a.decimals)} ${a.ticker}`; function el (tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } @@ -121,8 +121,8 @@ function render ({ req, opened, reviewed, pinned, lib }) { const blocks = ex.tip().height + 1; const resumed = opened.fromCache; $('chainCheck').textContent = resumed == null - ? `✓ ${blocks.toLocaleString('en-GB')} blocks checked by Podkey · ${mirrorNote}` - : `✓ ${(blocks - resumed - 1).toLocaleString('en-GB')} new blocks checked by Podkey, ${(resumed + 1).toLocaleString('en-GB')} from your last visit · ${mirrorNote}`; + ? `✓ ${blocks.toLocaleString()} blocks checked by Podkey · ${mirrorNote}` + : `✓ ${(blocks - resumed - 1).toLocaleString()} new blocks checked by Podkey, ${(resumed + 1).toLocaleString()} from your last visit · ${mirrorNote}`; $('signer').textContent = short(signer, 8, 8); $('signer').title = signer; const pin = $('signerPin'); @@ -165,11 +165,11 @@ function render ({ req, opened, reviewed, pinned, lib }) { // back to you const change = reviewed.outputs.filter((o) => o.kind === 'change'); + $('backCard').hidden = change.length === 0; if (change.length) { const back = change.reduce((s, o) => s + o.value, 0); const assetsBack = sumAssets(change.map((o) => o.assets)); $('back').textContent = [sats(back), ...assetsBack.map(assetText)].join(' + '); - $('backCard').hidden = false; } // fee and total @@ -178,8 +178,9 @@ function render ({ req, opened, reviewed, pinned, lib }) { const leavingAssets = sumAssets([...others.map((o) => o.assets), reviewed.destroyed.map((d) => ({ ...d, ...labelOf(reviewed, d.asset) }))]); $('total').textContent = [...leavingAssets.map(assetText), sats(leavingSats)].join(' + '); - if (reviewed.inputs.some((i) => i.carries.length) || others.some((o) => o.assets.length)) { - $('assetNote').hidden = false; + const hasAssets = reviewed.inputs.some((i) => i.carries.length) || others.some((o) => o.assets.length); + $('assetNote').hidden = !hasAssets; + if (hasAssets) { $('assetNote').textContent = reviewed.assetMode === 'rule' ? `${ex.chain.id} enforces its assets: every node checks these amounts.` : `Assets on ${ex.chain.id} are kept by their holders' records; the chain itself does not enforce them. Podkey read them from every block.`; @@ -187,10 +188,13 @@ function render ({ req, opened, reviewed, pinned, lib }) { // warnings: anything that destroys or burns needs an explicit tick const severe = reviewed.warnings.filter((w) => ['destroys', 'breaks', 'burn', 'pegout'].includes(w.kind)); + $('warnings').hidden = reviewed.warnings.length === 0; + $('ackRow').hidden = severe.length === 0; + $('ack').checked = false; if (reviewed.warnings.length) { - $('warnings').hidden = false; $('warningList').replaceChildren(...reviewed.warnings.map((w) => el('li', null, w.text))); - $('ackRow').hidden = !severe.length; + } else { + $('warningList').replaceChildren(); } // details @@ -201,9 +205,12 @@ function render ({ req, opened, reviewed, pinned, lib }) { $('mirror').textContent = mirror; const sign = $('sign'); + sign.textContent = 'Sign'; + $('reject').disabled = false; const ready = () => { sign.disabled = severe.length > 0 && !$('ack').checked; }; - $('ack').addEventListener('change', ready); ready(); - sign.addEventListener('click', () => doSign({ req, opened, reviewed, pinned, lib })); + $('ack').onchange = ready; + ready(); + sign.onclick = () => doSign({ req, opened, reviewed, pinned, lib }); } function labelOf (reviewed, asset) { @@ -259,6 +266,25 @@ $('reject').addEventListener('click', () => { window.close(); }); +$('signedClose').addEventListener('click', () => window.close()); + +window.addEventListener('keydown', (e) => { + if (e.key !== 'Escape') return; + if (!$('optIn').hidden) { + e.preventDefault(); + $('optInNo').click(); + } else if (!$('review').hidden && !$('reject').disabled) { + e.preventDefault(); + $('reject').click(); + } else if (!$('failure').hidden) { + e.preventDefault(); + $('close').click(); + } else if (!$('signed').hidden) { + e.preventDefault(); + window.close(); + } +}); + // ---- opt-in --------------------------------------------------------------- // Spends are off until the person turns them on. A site that asks while they diff --git a/src/background.js b/src/background.js index 54a27df..d9b3727 100644 --- a/src/background.js +++ b/src/background.js @@ -23,6 +23,7 @@ import { } from './storage.js'; import { createVault, unlockVault, hasVault } from './vault.js'; import { normalizeSecretKeyToHex } from './keyformat.js'; +import { buildEventPreviewPayload } from './event-preview.js'; import { sha256 } from '@noble/hashes/sha256'; import { bytesToHex } from '@noble/hashes/utils'; @@ -44,17 +45,20 @@ chrome.runtime.onInstalled.addListener(async () => { } }); -// Pending signing approval promises: requestId -> resolve function +// Pending signing approval entries: requestId -> { resolve, windowId } const pendingApprovals = new Map(); // Handle messages from content scripts and popup chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { // Handle signing approval responses from the approve popup if (message.type === 'APPROVE_SIGNING') { - const resolve = pendingApprovals.get(message.requestId); - if (resolve) { + const entry = pendingApprovals.get(message.requestId); + if (entry) { pendingApprovals.delete(message.requestId); - resolve(message.approved === true); + const approved = message.approved === true; + // Backward-compatible default: if trust is omitted, approving trusts the origin. + const trust = approved && message.trust !== false; + entry.resolve({ approved, trust }); } return; // synchronous, no sendResponse needed } @@ -207,8 +211,17 @@ const spends = createSpends({ }) }); -// Closing the spend window rejects the spend. (Guarded: the unit tests' chrome stub has no windows API.) -chrome.windows?.onRemoved?.addListener((windowId) => spends.windowClosed(windowId)); +// Closing a spend or approval window rejects its pending request immediately. +// (Guarded: some unit tests' chrome stubs have no windows.onRemoved API.) +chrome.windows?.onRemoved?.addListener((windowId) => { + spends.windowClosed(windowId); + for (const [requestId, entry] of pendingApprovals) { + if (entry.windowId !== null && entry.windowId === windowId) { + pendingApprovals.delete(requestId); + entry.resolve({ approved: false, trust: false }); + } + } +}); // The origin shown for a spend is the one Chrome reports for the sending // frame, not anything the page wrote into the message. @@ -317,14 +330,16 @@ async function handleGetPublicKey (origin, _sender) { if (!trusted) { // Show permission prompt - const allowed = await showPermissionPrompt(origin, 'read your public key'); + const { approved, trust } = await showPermissionPrompt(origin, 'read your public key'); - if (!allowed) { + if (!approved) { throw new Error('User denied permission'); } - // Trust this origin - await addTrustedOrigin(origin); + // Trust this origin unless the user chose "Approve once" + if (trust) { + await addTrustedOrigin(origin); + } } // Get and return public key (ensure it's a string) @@ -358,21 +373,17 @@ async function handleSignEvent (event, origin, _sender) { let shouldSign = trusted; if (!shouldSign) { - // Show signing prompt with event preview + // Show signing prompt with structured event preview (kind, content, key tags) const actionLabel = isSolidAuth ? 'sign a Solid authentication event' : `sign an event (kind ${event.kind})`; - const previewData = JSON.stringify({ - kind: event.kind, - content: (event.content || '').substring(0, 200), - tags: (event.tags || []).length - }); - const allowed = await showPermissionPrompt(origin, actionLabel, previewData); + const previewData = buildEventPreviewPayload(event); + const { approved, trust } = await showPermissionPrompt(origin, actionLabel, previewData); - if (!allowed) { + if (!approved) { throw new Error('User denied signing'); } - // Trust this origin if not already trusted - if (!trusted) { + // Trust this origin unless the user chose "Approve once" + if (!trusted && trust) { await addTrustedOrigin(origin); } } @@ -409,11 +420,13 @@ async function resolveKeypairForEncryption (origin, action) { const trusted = await isTrustedOrigin(origin); if (!trusted) { - const allowed = await showPermissionPrompt(origin, action); - if (!allowed) { + const { approved, trust } = await showPermissionPrompt(origin, action); + if (!approved) { throw new Error('User denied permission'); } - await addTrustedOrigin(origin); + if (trust) { + await addTrustedOrigin(origin); + } } const keypair = await getKeypair(); @@ -608,23 +621,23 @@ async function showPermissionPrompt (origin, action, eventPreview) { const requestId = crypto.randomUUID(); return new Promise((resolve) => { - pendingApprovals.set(requestId, resolve); - // Auto-deny after 60 seconds if no response const timeout = setTimeout(() => { if (pendingApprovals.has(requestId)) { pendingApprovals.delete(requestId); console.log(`[Podkey] Signing request ${requestId} timed out, auto-denying`); - resolve(false); + resolve({ approved: false, trust: false }); } }, 60000); - // Clean up timeout when resolved normally - const originalResolve = resolve; - pendingApprovals.set(requestId, (approved) => { - clearTimeout(timeout); - originalResolve(approved); - }); + const entry = { + windowId: null, + resolve: (decision) => { + clearTimeout(timeout); + resolve(decision); + } + }; + pendingApprovals.set(requestId, entry); const params = new URLSearchParams({ id: requestId, @@ -633,13 +646,18 @@ async function showPermissionPrompt (origin, action, eventPreview) { preview: eventPreview || '' }); - chrome.windows.create({ + const created = chrome.windows.create({ url: `popup/approve.html?${params.toString()}`, type: 'popup', width: 420, - height: 470, // room for the trust note without scrolling + height: 540, focused: true }); + if (created && typeof created.then === 'function') { + created.then((win) => { + if (pendingApprovals.has(requestId)) entry.windowId = win?.id ?? null; + }).catch(() => {}); + } }); } diff --git a/src/event-preview.js b/src/event-preview.js new file mode 100644 index 0000000..18b89d7 --- /dev/null +++ b/src/event-preview.js @@ -0,0 +1,134 @@ +/** + * Human-readable Nostr event preview formatting for the signing approval prompt. + * Pure module (no DOM or chrome.*) so Node tests can verify it directly. + */ + +const KIND_LABELS = { + 0: 'Profile metadata', + 1: 'Public note', + 3: 'Follow list', + 4: 'Encrypted direct message (legacy)', + 5: 'Deletion request', + 6: 'Repost', + 7: 'Reaction', + 13: 'Sealed message (NIP-59)', + 14: 'Direct message', + 1059: 'Gift-wrapped message (NIP-59)', + 9734: 'Zap request', + 10002: 'Relay list', + 22242: 'Relay authentication', + 24242: 'Media upload authorization', + 27235: 'HTTP / Solid authentication', + 30023: 'Long-form article' +}; + +const MAX_CONTENT_CHARS = 400; +const MAX_PREVIEW_TAGS = 10; +const MAX_TAG_VALUE_CHARS = 120; + +/** + * Return a plain-English label for a Nostr event kind. + * @param {number} kind + * @returns {string} + */ +export function describeEventKind (kind) { + if (typeof kind !== 'number' || !Number.isFinite(kind)) return 'Nostr event'; + return KIND_LABELS[kind] || `Event kind ${kind}`; +} + +/** + * Build a compact, URL-safe JSON preview string for an unsigned Nostr event. + * Keeps key tags visible (unlike a bare tag count) while bounding size so the + * approval popup query string stays small. + * @param {object} event + * @returns {string} + */ +export function buildEventPreviewPayload (event) { + const kind = Number(event?.kind); + const rawContent = typeof event?.content === 'string' ? event.content : ''; + const content = rawContent.length > MAX_CONTENT_CHARS + ? `${rawContent.slice(0, MAX_CONTENT_CHARS)}…` + : rawContent; + + const rawTags = Array.isArray(event?.tags) ? event.tags : []; + const tags = rawTags.slice(0, MAX_PREVIEW_TAGS).map((tag) => { + if (!Array.isArray(tag)) return []; + return tag.slice(0, 4).map((part) => { + const str = String(part ?? ''); + return str.length > MAX_TAG_VALUE_CHARS ? `${str.slice(0, MAX_TAG_VALUE_CHARS)}…` : str; + }); + }); + + return JSON.stringify({ + kind, + content, + tags, + tagCount: rawTags.length + }); +} + +/** + * Parse a preview string from the approval URL into structured summary rows + * plus pretty-printed raw JSON for inspection. + * @param {string} rawPreview + * @returns {{ rows: Array<{label: string, value: string, mono?: boolean}>, rawText: string } | null} + */ +export function summarizePreview (rawPreview) { + if (typeof rawPreview !== 'string' || !rawPreview.trim()) return null; + + let parsed; + try { + parsed = JSON.parse(rawPreview); + } catch { + return { rows: [], rawText: rawPreview }; + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { rows: [], rawText: JSON.stringify(parsed, null, 2) }; + } + + const rows = []; + if (typeof parsed.kind === 'number') { + const label = KIND_LABELS[parsed.kind]; + rows.push({ + label: 'Event type', + value: label ? `${label} (kind ${parsed.kind})` : `Kind ${parsed.kind}` + }); + } + + const tags = Array.isArray(parsed.tags) ? parsed.tags : []; + const findTag = (name) => tags.find((t) => Array.isArray(t) && t[0] === name && t[1]); + + const urlTag = findTag('u'); + const methodTag = findTag('method'); + const relayTag = findTag('relay'); + if (methodTag) rows.push({ label: 'HTTP method', value: String(methodTag[1]), mono: true }); + if (urlTag) rows.push({ label: 'Target URL', value: String(urlTag[1]), mono: true }); + if (relayTag) rows.push({ label: 'Relay', value: String(relayTag[1]), mono: true }); + + if (typeof parsed.content === 'string' && parsed.content.length > 0) { + rows.push({ label: 'Content', value: parsed.content }); + } + + const tagCount = typeof parsed.tagCount === 'number' + ? parsed.tagCount + : typeof parsed.tags === 'number' + ? parsed.tags + : tags.length; + + if (tagCount > 0) { + const extraTags = tags + .filter((t) => Array.isArray(t) && t.length > 0 && !['u', 'method', 'relay'].includes(t[0])) + .slice(0, 4) + .map((t) => t.join(': ')); + const tagSummary = extraTags.length + ? `${tagCount} total (${extraTags.join(', ')}${tagCount > extraTags.length ? ', …' : ''})` + : `${tagCount} tag${tagCount === 1 ? '' : 's'}`; + rows.push({ label: 'Tags', value: tagSummary, mono: extraTags.length > 0 }); + } + + return { + rows, + rawText: JSON.stringify(parsed, null, 2) + }; +} diff --git a/test/consent-approval.test.js b/test/consent-approval.test.js index a931f02..c12ad4c 100644 --- a/test/consent-approval.test.js +++ b/test/consent-approval.test.js @@ -42,7 +42,7 @@ function makeArea (store) { const stores = { local: {}, session: {} }; const windowsCreated = []; -const captured = { onMessage: null }; +const captured = { onMessage: null, onWindowRemoved: null }; global.chrome = { runtime: { @@ -51,7 +51,8 @@ global.chrome = { lastError: null }, windows: { - create: (opts) => { windowsCreated.push(opts); return Promise.resolve({ id: windowsCreated.length }); } + create: (opts) => { windowsCreated.push(opts); return Promise.resolve({ id: windowsCreated.length }); }, + onRemoved: { addListener: (fn) => { captured.onWindowRemoved = fn; } } }, storage: { local: makeArea(stores.local), @@ -88,8 +89,10 @@ function lastRequestId () { } /** Resolve a pending prompt by sending the popup's APPROVE_SIGNING message. */ -function respond (requestId, approved) { - onMessage({ type: 'APPROVE_SIGNING', requestId, approved }, {}, () => {}); +function respond (requestId, approved, trust) { + const msg = { type: 'APPROVE_SIGNING', requestId, approved }; + if (trust !== undefined) msg.trust = trust; + onMessage(msg, {}, () => {}); } const SOLID_EVENT = { kind: 27235, created_at: 1700000000, tags: [['u', 'https://pod.test/']], content: '' }; @@ -243,4 +246,31 @@ describe('trusted-origin auto-path (general signer)', () => { assert.equal(windowsCreated.length, 1, 'origin became trusted; no second popup'); assert.equal(second.kind, 1); }); + + it('approving once (trust: false) signs without trusting future requests', async () => { + const first = send({ type: 'SIGN_EVENT', event: SOLID_EVENT, origin: 'https://once.test' }); + await flush(); + assert.equal(windowsCreated.length, 1); + const params = new URL('https://x/' + windowsCreated[0].url).searchParams; + const preview = JSON.parse(params.get('preview')); + assert.deepEqual(preview.tags, [['u', 'https://pod.test/']]); + respond(lastRequestId(), true, false); + const signed = await first; + assert.equal(signed.kind, 27235); + + // Next request must prompt again because trust was false. + const second = send({ type: 'SIGN_EVENT', event: NOTE_EVENT, origin: 'https://once.test' }); + await flush(); + assert.equal(windowsCreated.length, 2, 'approve once must not persist origin trust'); + respond(lastRequestId(), false, false); + assert.deepEqual(await second, { error: 'User denied signing' }); + }); + + it('closing the approval window via chrome.windows.onRemoved immediately denies', async () => { + const pending = send({ type: 'GET_PUBLIC_KEY', origin: 'https://closed.test' }); + await flush(); + assert.equal(windowsCreated.length, 1); + captured.onWindowRemoved(1); + assert.deepEqual(await pending, { error: 'User denied permission' }); + }); }); diff --git a/test/event-preview.test.js b/test/event-preview.test.js new file mode 100644 index 0000000..1be51fb --- /dev/null +++ b/test/event-preview.test.js @@ -0,0 +1,60 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { + buildEventPreviewPayload, + describeEventKind, + summarizePreview +} from '../src/event-preview.js'; + +describe('describeEventKind', () => { + it('labels well-known Nostr event kinds', () => { + assert.equal(describeEventKind(0), 'Profile metadata'); + assert.equal(describeEventKind(1), 'Public note'); + assert.equal(describeEventKind(22242), 'Relay authentication'); + assert.equal(describeEventKind(27235), 'HTTP / Solid authentication'); + }); + + it('falls back gracefully for unknown kinds', () => { + assert.equal(describeEventKind(99999), 'Event kind 99999'); + assert.equal(describeEventKind(NaN), 'Nostr event'); + }); +}); + +describe('buildEventPreviewPayload & summarizePreview', () => { + it('preserves key tags (URL, method, relay) for structured approval review', () => { + const raw = buildEventPreviewPayload({ + kind: 27235, + content: '', + tags: [ + ['u', 'https://alice.solid.social/private/notes.ttl'], + ['method', 'PUT'], + ['payload', 'abcd'.repeat(16)] + ] + }); + const summary = summarizePreview(raw); + assert.ok(summary); + const byLabel = Object.fromEntries(summary.rows.map((r) => [r.label, r.value])); + assert.equal(byLabel['Event type'], 'HTTP / Solid authentication (kind 27235)'); + assert.equal(byLabel['HTTP method'], 'PUT'); + assert.equal(byLabel['Target URL'], 'https://alice.solid.social/private/notes.ttl'); + assert.match(byLabel.Tags, /3 total/); + }); + + it('bounds long content and large tag lists in the preview payload', () => { + const raw = buildEventPreviewPayload({ + kind: 1, + content: 'a'.repeat(1000), + tags: Array.from({ length: 25 }, (_, i) => ['t', `tag-${i}`]) + }); + const parsed = JSON.parse(raw); + assert.equal(parsed.content.length, 401); + assert.equal(parsed.tags.length, 10); + assert.equal(parsed.tagCount, 25); + }); + + it('handles non-JSON preview strings gracefully without throwing', () => { + const summary = summarizePreview('plain text preview'); + assert.deepEqual(summary, { rows: [], rawText: 'plain text preview' }); + assert.equal(summarizePreview(''), null); + }); +});