Skip to content

Commit bfc3848

Browse files
loganjLarry
andauthored
fix(desktop): shared npub identity foundation (canonicalNpub, PubKey gate, strict parser) (#7488)
🤖 ## Summary Identity keys in the desktop app are displayed as raw 64-character hex. A person's key shows up as something like `953d3363…` — unreadable, impossible to recognize as the same identity on another screen, and a hazard when copied by hand. Nostr (the protocol Buzz runs on) has a human-readable spelling for identity keys — the `npub1…` form — but the desktop app did not use it consistently. This is the foundation of the desktop npub changes: it adds the shared pieces every identity surface builds on, and two follow-up slices stack directly on this branch — #7489 converts the identity controls (profile, settings, allowlist, workflow key fields) and #7495 converts the everyday display surfaces (mentions, member lists, sidebar, and other name fallbacks). After this change: - The shared identity widget shows the compact npub form — `npub1j57...fjmv` — instead of a hex prefix, everywhere it renders (for example the owned-agent public-key row on a profile). Copying it puts the full npub on the clipboard. - Copy is a real interaction, verified end-to-end: both popover variants put the exact canonical npub on the actual clipboard — never the raw hex the popover also lists, never a truncation — and a portaled popover's clicks no longer steal focus from the new-DM To-field mid-copy. Pointer copy, a natural Space-then-Enter path, and inner/outer Escape are covered. - Anything that isn't a valid identity key fails neutrally: short or corrupt values — including degenerate values that technically encode to a checksum-valid npub but aren't real identity keys — show "Unavailable" with no copy button, instead of a misleading value. - Both valid npub spellings display: all-lowercase `npub1…` and all-uppercase `NPUB1…` (Bech32, npub's encoding, permits either casing) both render the same canonical lowercase npub. Mixed case is rejected by the display path as written — `canonicalNpub` and the widget don't case-normalize input — while input parsing (`parsePubkeyInput`) keeps its trim-and-lowercase normalization and accepts mixed-case npubs; both paths require the decoded payload to be exactly a 64-character identity key. - Identity-key input is strict on payload: an npub whose decoded payload isn't exactly a 64-character identity key is rejected, matching the validation the app's Rust side already applies to agent allowlists. Intentional scope boundary: only surfaces that render through the shared widget change here. Outer profile copy, settings identity cards, the respond-to allowlist, and workflow key fields still show hex — they move to npub in the controls follow-up (#7489). Nothing else changes identity representation: display names, private keys, event IDs, and the hex the app stores, sends, and matches internally are untouched; only the user-facing spelling of an identity key changes. ## Details - `desktop/src/shared/lib/pubkey.ts` — `canonicalNpub()`: strict canonical full-npub helper (64-char hex in any case, or a checksum-validated npub, returns the canonical npub; anything else returns `null`); `truncateNpub()`: the compact display form; existing exports unchanged. - `desktop/src/shared/ui/PubKey.tsx` — the shared widget's identity gate validates through `canonicalNpub`; the popover copies the npub only. - `desktop/src/shared/lib/nostrUtils.ts` — `parsePubkeyInput` rejects npubs whose payload is not exactly a 64-character identity key. - `desktop/src/features/messages/ui/NewMessageScreen.tsx` — the To-field focuses its search input only for clicks that land inside the field itself, so portaled recipient popovers keep their focus while open (a popover click previously dismissed it mid-copy). - Unit suites cover the helper, widget, and parser (including the degenerate-encode and uppercase regressions); the e2e specs that render these rows assert the npub display. ### Related issue - Fixes: N/A. Searched existing issues/PRs for npub identity display — no existing match. - Stack: #7489 is based on this branch and builds on these primitives; it does not stand alone on main. ### Testing At head `b3310c248` (base: main `44316ff72`; 12 files, +440/−39): - Focused unit suites (pubkey, PubKey, parsePubkeyInput): 20/20 green; mutation-checked — removing the decoded-length predicate fails the short/empty checksum-valid-npub assertions in `canonicalNpub` and the widget, and a wrong-identity clipboard value fails the new copy assertions. - `pnpm typecheck` and `pnpm check`: pass; full desktop unit suite 6459/6459 at this exact head. - Targeted e2e at this exact head: 8/8 across the two specs that own the clipboard flows — `agent-access-warning.spec.ts` (compact variant, agent-access owner hint) and `pubkey-display-screenshots.spec.ts` (full variant, new-DM recipient verification: pointer copy, popover surviving the copy, inner/outer Escape, Space-then-Enter). - No Rust-side or build files change in this PR, so those results are unaffected. ### Task provenance Buzz channel: `1f0e4a3d-7e01-4efe-bb16-843b357f85c9` Task: buzz://message?channel=1f0e4a3d-7e01-4efe-bb16-843b357f85c9&id=86b34eb4bd84a1472419e9af22636c011c0fe273e3c196f967d7a36996e149b6 --------- Signed-off-by: Logan Johnson <[email protected]> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
1 parent 93761e4 commit bfc3848

12 files changed

Lines changed: 440 additions & 39 deletions

‎desktop/src/features/messages/ui/NewMessageScreen.tsx‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,22 @@ export function NewMessageScreen() {
328328
<div
329329
className="group/to-field flex min-h-9 min-w-0 flex-1 cursor-text flex-wrap items-center gap-1.5 py-1"
330330
data-testid="new-message-to-field"
331-
onClick={() => {
331+
onClick={(event) => {
332+
// Portaled popovers (recipient inspection and its nested key
333+
// copy) still bubble through React's tree to this handler,
334+
// but their event targets are not DOM descendants of the
335+
// field. Those clicks belong to the popover's own controls
336+
// — they must not steal focus into the search input (which
337+
// dismisses the popover via focus-outside) or reopen the
338+
// picker. Only clicks physically within the recipient field
339+
// focus its input.
340+
const { currentTarget, target } = event;
341+
if (
342+
!(target instanceof Node) ||
343+
!currentTarget.contains(target)
344+
) {
345+
return;
346+
}
332347
setIsRecipientPickerOpen(true);
333348
searchInputRef.current?.focus({ preventScroll: true });
334349
}}

‎desktop/src/shared/lib/nostrUtils.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,13 @@ const HEX_PUBKEY_REGEX = /^[0-9a-f]{64}$/;
3131
* anything else (does NOT throw — intended for live form validation).
3232
*
3333
* The input is trimmed first; surrounding whitespace from copy-paste is
34-
* tolerated.
34+
* tolerated. It is also case-normalized before matching and decoding —
35+
* preexisting behavior — so a hex key in any casing resolves, and a
36+
* mixed-case npub (invalid Bech32 as written) is accepted via its
37+
* lowercased form. The identity payload itself stays strict: it must
38+
* decode to exactly a 64-char hex identity key, because `npubEncode` also
39+
* encodes degenerate short payloads (even `""`), which are never valid
40+
* identities.
3541
*/
3642
export function parsePubkeyInput(input: string): string | null {
3743
const trimmed = input.trim().toLowerCase();
@@ -41,7 +47,7 @@ export function parsePubkeyInput(input: string): string | null {
4147
if (trimmed.startsWith("npub1")) {
4248
try {
4349
const decoded = decode(trimmed);
44-
if (decoded.type === "npub") {
50+
if (decoded.type === "npub" && HEX_PUBKEY_REGEX.test(decoded.data)) {
4551
return decoded.data;
4652
}
4753
} catch {

‎desktop/src/shared/lib/parsePubkeyInput.test.mjs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,16 @@ describe("parsePubkeyInput", () => {
1919
assert.equal(parsePubkeyInput(NPUB), HEX);
2020
});
2121

22+
it("normalizes a mixed-case npub to its canonical hex", () => {
23+
// Preexisting behavior: user input is lowercased before decoding, so a
24+
// mixed-case npub — invalid Bech32 as written — still resolves to the
25+
// identity. canonicalNpub is the strict counterpart (see ../lib/pubkey.ts).
26+
assert.equal(
27+
parsePubkeyInput(`${NPUB.slice(0, 10)}${NPUB.slice(10).toUpperCase()}`),
28+
HEX,
29+
);
30+
});
31+
2232
it("tolerates surrounding whitespace from copy-paste", () => {
2333
assert.equal(parsePubkeyInput(` ${NPUB}\n`), HEX);
2434
assert.equal(parsePubkeyInput(` ${HEX} `), HEX);
@@ -42,6 +52,13 @@ describe("parsePubkeyInput", () => {
4252
assert.equal(parsePubkeyInput(`${HEX}0`), null);
4353
});
4454

55+
it("rejects degenerate npubs whose payload is not a 64-char identity", () => {
56+
// `npubEncode` happily encodes short payloads with valid checksums —
57+
// those are not identity keys and must never bind as one.
58+
assert.equal(parsePubkeyInput("npub1m6kmamcvty5gd"), null);
59+
assert.equal(parsePubkeyInput("npub106246s"), null);
60+
});
61+
4562
it("rejects non-hex non-npub input", () => {
4663
assert.equal(parsePubkeyInput(""), null);
4764
assert.equal(parsePubkeyInput("alice"), null);

‎desktop/src/shared/lib/pubkey.test.mjs‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,20 @@
11
import assert from "node:assert/strict";
22
import test from "node:test";
33

4-
import { normalizePubkey, truncatePubkey } from "./pubkey.ts";
4+
import {
5+
canonicalNpub,
6+
normalizePubkey,
7+
truncateNpub,
8+
truncatePubkey,
9+
} from "./pubkey.ts";
510

611
const PUBKEY =
712
"44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435";
13+
const PUBKEY_NPUB =
14+
"npub1gjuws2a2dc8z2nszprtg7v6u9q7ffeah3hgl5yx45jwn7y7aqs6s5e9xj6";
15+
const HEX = "ea9b4d7a7a78a3e3729e5568b14d764d4962be0e1f20f749bcf8d9dbbf9a9328";
16+
const HEX_NPUB =
17+
"npub1a2d567n60z37xu57245tzntkf4yk90swrus0wjdulrvah0u6jv5qusyp60";
818

919
test("truncates to the canonical 8+4 form with unicode ellipsis", () => {
1020
assert.equal(truncatePubkey(PUBKEY), "44b8e82b…0435");
@@ -18,3 +28,60 @@ test("returns short strings unchanged", () => {
1828
test("normalizePubkey trims and lowercases", () => {
1929
assert.equal(normalizePubkey(" ABCDEF "), "abcdef");
2030
});
31+
32+
test("truncateNpub compacts the hex pubkey's npub, not its hex form", () => {
33+
assert.equal(truncateNpub(PUBKEY), "npub1gju…9xj6");
34+
assert.equal(truncateNpub(HEX), "npub1a2d…yp60");
35+
assert.equal(truncateNpub(HEX.toUpperCase()), "npub1a2d…yp60");
36+
});
37+
38+
test("truncateNpub accepts already-npub strings", () => {
39+
assert.equal(truncateNpub(PUBKEY_NPUB), "npub1gju…9xj6");
40+
assert.equal(truncateNpub(` ${HEX_NPUB} `), "npub1a2d…yp60");
41+
// All-uppercase Bech32 is a valid identity per the parser; render the
42+
// canonical form, never the neutral label.
43+
assert.equal(truncateNpub(HEX_NPUB.toUpperCase()), "npub1a2d…yp60");
44+
});
45+
46+
test("truncateNpub renders the neutral label for invalid identities", () => {
47+
// Never the raw hex/input fallback: a wrong-length or non-hex string is not
48+
// a displayable identity.
49+
assert.equal(truncateNpub(""), "Unavailable");
50+
assert.equal(truncateNpub("not a pubkey"), "Unavailable");
51+
assert.equal(truncateNpub(`${HEX.slice(0, 63)}`), "Unavailable");
52+
assert.equal(truncateNpub(`z${HEX.slice(1)}`), "Unavailable");
53+
// Corrupted npub checksum is not a valid identity either.
54+
assert.equal(truncateNpub(`${HEX_NPUB.slice(0, -1)}q`), "Unavailable");
55+
// Other bech32 entities are not pubkeys.
56+
assert.equal(
57+
truncateNpub(
58+
"nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5",
59+
),
60+
"Unavailable",
61+
);
62+
});
63+
64+
test("canonicalNpub returns the full npub for valid identities only", () => {
65+
assert.equal(canonicalNpub(HEX), HEX_NPUB);
66+
assert.equal(canonicalNpub(HEX.toUpperCase()), HEX_NPUB);
67+
assert.equal(canonicalNpub(HEX_NPUB), HEX_NPUB);
68+
// All-uppercase Bech32 is valid and returns the canonical lowercase npub
69+
// (parser agreement); a mixed-case npub is invalid Bech32.
70+
assert.equal(canonicalNpub(HEX_NPUB.toUpperCase()), HEX_NPUB);
71+
assert.equal(
72+
canonicalNpub(
73+
`${HEX_NPUB.slice(0, 10)}${HEX_NPUB.slice(10).toUpperCase()}`,
74+
),
75+
null,
76+
);
77+
// Strict identity keys only — short/degenerate payloads never encode.
78+
assert.equal(canonicalNpub(""), null);
79+
assert.equal(canonicalNpub("deadbeef"), null);
80+
assert.equal(canonicalNpub(`${HEX.slice(0, 63)}`), null);
81+
// Checksum-valid short npubs are degenerate payloads too (8-char and
82+
// empty) — `npubEncode` would happily re-encode them, so never bind them.
83+
assert.equal(canonicalNpub("npub1m6kmamcvty5gd"), null);
84+
assert.equal(canonicalNpub("npub106246s"), null);
85+
// Corrupted checksum never binds as the identity it resembles.
86+
assert.equal(canonicalNpub(`${HEX_NPUB.slice(0, -2)}qq`), null);
87+
});

‎desktop/src/shared/lib/pubkey.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import { decode, npubEncode } from "nostr-tools/nip19";
2+
3+
import { safeNpub } from "./nostrUtils";
4+
15
/**
26
* Canonical pubkey normalisation.
37
*
@@ -8,18 +12,74 @@ export function normalizePubkey(pubkey: string): string {
812
return pubkey.trim().toLowerCase();
913
}
1014

15+
/** Neutral identity label for keys that cannot be encoded for display. */
16+
export const UNAVAILABLE_KEY_LABEL = "Unavailable";
17+
18+
const HEX_64_REGEX = /^[0-9a-f]{64}$/;
19+
1120
/**
12-
* The ONE canonical compact display form for a pubkey: `abcd1234…wxyz`.
21+
* The ONE canonical compact display form for a hex string: `abcd1234…wxyz`.
1322
*
1423
* A truncated pubkey is a recognition aid, never an identity proof — vanity
1524
* grinders forge short prefixes cheaply. Surfaces where the user makes a
1625
* trust decision must show the full npub (see `<PubKey variant="full">`).
1726
* Do not hand-roll `pubkey.slice(…)` display forms; `check-pubkey-truncation`
1827
* fails the build if one sneaks in outside this module.
28+
*
29+
* Identity (pubkey) surfaces should use `truncateNpub` instead; this hex form
30+
* remains canonical for non-identity identifiers — event and blob IDs.
1931
*/
2032
export function truncatePubkey(pubkey: string): string {
2133
if (pubkey.length <= 12) {
2234
return pubkey;
2335
}
2436
return `${pubkey.slice(0, 8)}…${pubkey.slice(-4)}`;
2537
}
38+
39+
/**
40+
* Canonical full npub for an identity key: a 64-char hex pubkey (any
41+
* case) or an already-npub string (checksum-validated) returns the
42+
* canonical npub; anything else returns null. Strict 64-char identity keys
43+
* only — `npubEncode` happily encodes short/degenerate payloads (even `""`),
44+
* which are not displayable identities.
45+
*
46+
* Bech32 casing is strict on the input as written: a lowercase `npub1…`
47+
* or an all-uppercase `NPUB1…` (both valid Bech32) returns the canonical
48+
* lowercase npub, while a mixed-case npub is invalid Bech32 and returns
49+
* null — `decode` enforces the all-lower/all-upper rule. This is
50+
* intentionally stricter than the parser (`parsePubkeyInput`), which
51+
* normalizes user input before decoding and so also accepts mixed-case
52+
* npubs; the two agree that the payload must be a 64-hex identity key and
53+
* that both valid casings above are acceptable input.
54+
*/
55+
export function canonicalNpub(pubkey: string): string | null {
56+
const trimmed = pubkey.trim();
57+
if (trimmed.startsWith("npub1") || trimmed.startsWith("NPUB1")) {
58+
try {
59+
const decoded = decode(trimmed);
60+
if (decoded.type !== "npub" || !HEX_64_REGEX.test(decoded.data)) {
61+
return null;
62+
}
63+
return npubEncode(decoded.data);
64+
} catch {
65+
return null;
66+
}
67+
}
68+
const normalized = normalizePubkey(trimmed);
69+
return HEX_64_REGEX.test(normalized) ? safeNpub(normalized) : null;
70+
}
71+
72+
/**
73+
* The ONE canonical compact identity display for a pubkey: `npub1abcd…wxyz`
74+
* (first 8 + last 4 of the FULL npub).
75+
*
76+
* Identity surfaces render this form so a displayed prefix is always npub-
77+
* shaped; the underlying hex never leaks as the identity display. A
78+
* truncated key is a recognition aid, never an identity proof — trust
79+
* decisions use `<PubKey variant="full">` or the full npub directly. Invalid
80+
* keys render `UNAVAILABLE_KEY_LABEL`, never raw hex or raw input.
81+
*/
82+
export function truncateNpub(pubkey: string): string {
83+
const npub = canonicalNpub(pubkey);
84+
return npub === null ? UNAVAILABLE_KEY_LABEL : truncatePubkey(npub);
85+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
/**
2+
* Widget-boundary coverage for the shared <PubKey> identity gate.
3+
*
4+
* Codec vectors and the exact compact/neutral strings live in
5+
* ../lib/pubkey.test.mjs. This suite pins what static rendering shows: the
6+
* rendered text per variant, and that an unencodable identity — including
7+
* degenerate-length hex and short-payload npubs whose npubEncode outputs
8+
* carry valid checksums — renders the neutral label with no copy affordance,
9+
* never a fake npub. The clipboard write behind the copy affordance and the
10+
* popover the widget opens are real-bridge interactions owned by the E2E
11+
* regressions: the full variant's copy is pinned by the new-DM recipient
12+
* verification flow (tests/e2e/pubkey-display-screenshots.spec.ts) and the
13+
* compact variant's by the agent-access owner hint
14+
* (tests/e2e/agent-access-warning.spec.ts); both drive CopyRow through the
15+
* mock bridge into the actual browser clipboard.
16+
*/
17+
import assert from "node:assert/strict";
18+
import { after, afterEach, before, test } from "node:test";
19+
20+
import { JSDOM } from "jsdom";
21+
22+
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
23+
url: "http://localhost",
24+
});
25+
26+
before(() => {
27+
Object.assign(globalThis, {
28+
document: dom.window.document,
29+
getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
30+
HTMLElement: dom.window.HTMLElement,
31+
IS_REACT_ACT_ENVIRONMENT: true,
32+
Node: dom.window.Node,
33+
ResizeObserver: class {
34+
disconnect() {}
35+
observe() {}
36+
unobserve() {}
37+
},
38+
window: dom.window,
39+
});
40+
});
41+
42+
afterEach(async () => {
43+
const { cleanup } = await import("@testing-library/react");
44+
cleanup();
45+
});
46+
47+
after(() => dom.window.close());
48+
49+
const HEX = "ea9b4d7a7a78a3e3729e5568b14d764d4962be0e1f20f749bcf8d9dbbf9a9328";
50+
const NPUB = "npub1a2d567n60z37xu57245tzntkf4yk90swrus0wjdulrvah0u6jv5qusyp60";
51+
const COMPACT_NPUB = "npub1a2d…yp60";
52+
53+
async function renderPubKey(props) {
54+
const React = await import("react");
55+
const { render, within } = await import("@testing-library/react");
56+
const { PubKey } = await import("./PubKey.tsx");
57+
const view = render(React.createElement(PubKey, props));
58+
// render()'s bound queries search the whole body; scope to this render so
59+
// earlier mounts (cleaned up only per test) stay invisible.
60+
return { ...within(view.container), container: view.container };
61+
}
62+
63+
test("compact PubKey renders the truncated npub, never the hex", async () => {
64+
const trigger = await renderPubKey({ pubkey: HEX });
65+
assert.equal(
66+
trigger.getByRole("button", { name: "Show full public key" }).textContent,
67+
COMPACT_NPUB,
68+
);
69+
assert.equal(trigger.queryByText(HEX), null);
70+
71+
// A parent row that owns the interaction gets the same text, not a button.
72+
const text = await renderPubKey({ interactive: false, pubkey: HEX });
73+
assert.equal(text.getByText(COMPACT_NPUB).tagName, "SPAN");
74+
assert.equal(text.queryByRole("button"), null);
75+
assert.equal(text.queryByText(HEX), null);
76+
77+
// An all-uppercase Bech32 npub is a valid identity (parsePubkeyInput
78+
// accepts it); the gate must render its canonical compact form, not the
79+
// neutral label.
80+
const upper = await renderPubKey({ pubkey: NPUB.toUpperCase() });
81+
assert.equal(
82+
upper.getByRole("button", { name: "Show full public key" }).textContent,
83+
COMPACT_NPUB,
84+
);
85+
assert.equal(upper.queryByText("Unavailable"), null);
86+
});
87+
88+
test("full PubKey renders the complete npub with a copy affordance", async () => {
89+
const view = await renderPubKey({ pubkey: HEX, variant: "full" });
90+
assert.equal(view.getByText(NPUB).textContent, NPUB);
91+
assert.equal(
92+
view.getByRole("button", { name: "Copy public key" }).tagName,
93+
"BUTTON",
94+
);
95+
assert.equal(view.queryByText(HEX), null);
96+
});
97+
98+
test("unencodable keys render Unavailable with no copy affordance", async () => {
99+
// "zz" cannot decode; "deadbeef" is a degenerate-length hex that npubEncode
100+
// would happily turn into a checksum-valid fake npub; npub1m6kmamcvty5gd
101+
// and npub106246s decode fine but are checksum-valid short-payload npubs
102+
// (8-char and empty identity payloads). All four would masquerade as
103+
// displayable identities — the gate refuses every one.
104+
for (const pubkey of [
105+
"zz",
106+
"deadbeef",
107+
"npub1m6kmamcvty5gd",
108+
"npub106246s",
109+
]) {
110+
for (const variant of [undefined, "full"]) {
111+
const view = await renderPubKey({ pubkey, variant });
112+
const label = `${pubkey} ${variant ?? "compact"}`;
113+
assert.equal(view.getByText("Unavailable").tagName, "SPAN", label);
114+
assert.equal(view.queryByRole("button"), null, label);
115+
assert.equal(view.container.textContent?.includes("npub1"), false, label);
116+
}
117+
}
118+
});

0 commit comments

Comments
 (0)