Skip to content

Commit 2c68ddd

Browse files
loganjLarry
andcommitted
fix(desktop): shared npub identity foundation (canonicalNpub, PubKey gate, strict parser)
PR-D1a foundation slice for the npub identity display standardization: the shared primitives every identity surface builds on, split out so the descendant slice can focus on the surfaces themselves (profile/settings controls, agents, workflows, Rust display name, guard hints). ## Summary - shared/lib/pubkey.ts: export canonicalNpub(pubkey) — strict canonical full-npub helper (64-char hex any case, or checksum-validated npub → canonical npub; degenerate/short/corrupt → null), alongside the truncateNpub compact display + UNAVAILABLE_KEY_LABEL foundation. Base exports (normalizePubkey, truncatePubkey) unchanged. - shared/ui/PubKey.tsx: the widget's identity gate validates through canonicalNpub — a degenerate-length hex (npubEncode("deadbeef") produces a checksum-valid fake npub) renders Unavailable with no copy affordance in every variant; popover copy is npub-only. - shared/lib/nostrUtils.ts: parsePubkeyInput rejects npubs whose payload is not exactly a 64-char identity key, matching the Rust validate_respond_to_allowlist contract; regression tests pin the degenerate vectors (npub1m6kmamcvty5gd, npub106246s). - Tests: pubkey.test.mjs covers canonicalNpub/truncateNpub/label and the degenerate-encode edge; new PubKey.test.mjs (JSDOM harness per MentionAutocomplete pattern) covers compact/non-interactive/full-popover rendering, npub-only copy, and invalid-key suppression; parsePubkeyInput.test.mjs pins the strict parser vectors. - e2e (shared-widget boundary only): profile.spec.ts owned-agent public key row asserts the npub prefix (the row renders through the shared <PubKey> widget); pubkey-display-screenshots.spec.ts asserts the shared widget popover text is npub-only while the chip's legacy raw-hex popover line still documents the D1a boundary. The remaining profile/settings clipboard assertions and the chip raw-hex line removal land with their surfaces in the descendant slice. Validation: pnpm install (hermit); pnpm check; pnpm typecheck; full desktop unit suite; Playwright pubkey-display (smoke, 4) and profile key-row/ingress (integration) mockbridge assertions. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Signed-off-by: Logan Johnson <[email protected]>
1 parent 44316ff commit 2c68ddd

8 files changed

Lines changed: 368 additions & 36 deletions

File tree

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ 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. The npub payload must decode to exactly a 64-char hex identity
35+
* key: `npubEncode` also encodes degenerate short payloads (even `""`), which
36+
* are never valid identities.
3537
*/
3638
export function parsePubkeyInput(input: string): string | null {
3739
const trimmed = input.trim().toLowerCase();
@@ -41,7 +43,7 @@ export function parsePubkeyInput(input: string): string | null {
4143
if (trimmed.startsWith("npub1")) {
4244
try {
4345
const decoded = decode(trimmed);
44-
if (decoded.type === "npub") {
46+
if (decoded.type === "npub" && HEX_PUBKEY_REGEX.test(decoded.data)) {
4547
return decoded.data;
4648
}
4749
} catch {

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,13 @@ describe("parsePubkeyInput", () => {
4242
assert.equal(parsePubkeyInput(`${HEX}0`), null);
4343
});
4444

45+
it("rejects degenerate npubs whose payload is not a 64-char identity", () => {
46+
// `npubEncode` happily encodes short payloads with valid checksums —
47+
// those are not identity keys and must never bind as one.
48+
assert.equal(parsePubkeyInput("npub1m6kmamcvty5gd"), null);
49+
assert.equal(parsePubkeyInput("npub106246s"), null);
50+
});
51+
4552
it("rejects non-hex non-npub input", () => {
4653
assert.equal(parsePubkeyInput(""), null);
4754
assert.equal(parsePubkeyInput("alice"), null);

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

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
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+
UNAVAILABLE_KEY_LABEL,
10+
} from "./pubkey.ts";
511

612
const PUBKEY =
713
"44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435";
14+
const PUBKEY_NPUB =
15+
"npub1gjuws2a2dc8z2nszprtg7v6u9q7ffeah3hgl5yx45jwn7y7aqs6s5e9xj6";
16+
const HEX = "ea9b4d7a7a78a3e3729e5568b14d764d4962be0e1f20f749bcf8d9dbbf9a9328";
17+
const HEX_NPUB =
18+
"npub1a2d567n60z37xu57245tzntkf4yk90swrus0wjdulrvah0u6jv5qusyp60";
819

920
test("truncates to the canonical 8+4 form with unicode ellipsis", () => {
1021
assert.equal(truncatePubkey(PUBKEY), "44b8e82b…0435");
@@ -18,3 +29,54 @@ test("returns short strings unchanged", () => {
1829
test("normalizePubkey trims and lowercases", () => {
1930
assert.equal(normalizePubkey(" ABCDEF "), "abcdef");
2031
});
32+
33+
test("truncateNpub compacts the hex pubkey's npub, not its hex form", () => {
34+
assert.equal(truncateNpub(PUBKEY), "npub1gju…9xj6");
35+
assert.equal(truncateNpub(HEX), "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+
});
42+
43+
test("truncateNpub accepts uppercase hex", () => {
44+
assert.equal(truncateNpub(HEX.toUpperCase()), "npub1a2d…yp60");
45+
});
46+
47+
test("truncateNpub renders the neutral label for invalid identities", () => {
48+
// Never the raw hex/input fallback: a wrong-length or non-hex string is not
49+
// a displayable identity.
50+
assert.equal(truncateNpub(""), UNAVAILABLE_KEY_LABEL);
51+
assert.equal(truncateNpub("not a pubkey"), UNAVAILABLE_KEY_LABEL);
52+
assert.equal(truncateNpub(`${HEX.slice(0, 63)}`), UNAVAILABLE_KEY_LABEL);
53+
assert.equal(truncateNpub(`z${HEX.slice(1)}`), UNAVAILABLE_KEY_LABEL);
54+
// Corrupted npub checksum is not a valid identity either.
55+
assert.equal(
56+
truncateNpub(`${HEX_NPUB.slice(0, -1)}q`),
57+
UNAVAILABLE_KEY_LABEL,
58+
);
59+
// Other bech32 entities are not pubkeys.
60+
assert.equal(
61+
truncateNpub(
62+
"nsec1vl029mgpspedva04g90vltkh6fvh240zqtv9k0t9af8935ke9laqsnlfe5",
63+
),
64+
UNAVAILABLE_KEY_LABEL,
65+
);
66+
});
67+
68+
test("UNAVAILABLE_KEY_LABEL stays the existing neutral vocabulary", () => {
69+
assert.equal(UNAVAILABLE_KEY_LABEL, "Unavailable");
70+
});
71+
72+
test("canonicalNpub returns the full npub for valid identities only", () => {
73+
assert.equal(canonicalNpub(HEX), HEX_NPUB);
74+
assert.equal(canonicalNpub(HEX.toUpperCase()), HEX_NPUB);
75+
assert.equal(canonicalNpub(HEX_NPUB), HEX_NPUB);
76+
// Strict identity keys only — short/degenerate payloads never encode.
77+
assert.equal(canonicalNpub(""), null);
78+
assert.equal(canonicalNpub("deadbeef"), null);
79+
assert.equal(canonicalNpub(`${HEX.slice(0, 63)}`), null);
80+
// Corrupted checksum never binds as the identity it resembles.
81+
assert.equal(canonicalNpub(`${HEX_NPUB.slice(0, -2)}qq`), null);
82+
});

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

Lines changed: 52 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,65 @@ 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-`npub1…` 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+
export function canonicalNpub(pubkey: string): string | null {
47+
const trimmed = pubkey.trim();
48+
if (trimmed.startsWith("npub1")) {
49+
try {
50+
const decoded = decode(trimmed);
51+
if (decoded.type !== "npub" || !HEX_64_REGEX.test(decoded.data)) {
52+
return null;
53+
}
54+
return npubEncode(decoded.data);
55+
} catch {
56+
return null;
57+
}
58+
}
59+
const normalized = normalizePubkey(trimmed);
60+
return HEX_64_REGEX.test(normalized) ? safeNpub(normalized) : null;
61+
}
62+
63+
/**
64+
* The ONE canonical compact identity display for a pubkey: `npub1abcd…wxyz`
65+
* (first 8 + last 4 of the FULL npub).
66+
*
67+
* Identity surfaces render this form so a displayed prefix is always npub-
68+
* shaped; the underlying hex never leaks as the identity display. A
69+
* truncated key is a recognition aid, never an identity proof — trust
70+
* decisions use `<PubKey variant="full">` or the full npub directly. Invalid
71+
* keys render `UNAVAILABLE_KEY_LABEL`, never raw hex or raw input.
72+
*/
73+
export function truncateNpub(pubkey: string): string {
74+
const npub = canonicalNpub(pubkey);
75+
return npub === null ? UNAVAILABLE_KEY_LABEL : truncatePubkey(npub);
76+
}
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
import assert from "node:assert/strict";
2+
import { after, afterEach, before, test } from "node:test";
3+
4+
import { JSDOM } from "jsdom";
5+
6+
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
7+
url: "http://localhost",
8+
});
9+
10+
before(() => {
11+
Object.assign(globalThis, {
12+
CustomEvent: dom.window.CustomEvent,
13+
document: dom.window.document,
14+
Element: dom.window.Element,
15+
Event: dom.window.Event,
16+
getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
17+
HTMLElement: dom.window.HTMLElement,
18+
IS_REACT_ACT_ENVIRONMENT: true,
19+
Node: dom.window.Node,
20+
NodeFilter: dom.window.NodeFilter,
21+
ResizeObserver: class {
22+
disconnect() {}
23+
observe() {}
24+
unobserve() {}
25+
},
26+
window: dom.window,
27+
});
28+
// Copy remaining DOM-level globals that Radix Popover focus machinery
29+
// references without a `window.` prefix (NodeFilter, HTMLInputElement,
30+
// …). Bulk-copy follows the HarnessCatalogDialog.acpForcedGate test pattern
31+
// so new Radix internals cannot reintroduce per-global whack-a-mole.
32+
for (const key of Object.getOwnPropertyNames(dom.window)) {
33+
if (
34+
!(key in globalThis) &&
35+
(key.startsWith("HTML") ||
36+
key.startsWith("SVG") ||
37+
key.startsWith("CSS") ||
38+
[
39+
"Node",
40+
"NodeFilter",
41+
"NodeList",
42+
"NamedNodeMap",
43+
"Event",
44+
"CustomEvent",
45+
"MouseEvent",
46+
"KeyboardEvent",
47+
"FocusEvent",
48+
"InputEvent",
49+
"PointerEvent",
50+
"EventTarget",
51+
"Text",
52+
"DocumentFragment",
53+
"Range",
54+
"Selection",
55+
].includes(key))
56+
) {
57+
const val = dom.window[key];
58+
if (val !== undefined) globalThis[key] = val;
59+
}
60+
}
61+
});
62+
63+
afterEach(async () => {
64+
const { cleanup } = await import("@testing-library/react");
65+
cleanup();
66+
});
67+
68+
after(() => dom.window.close());
69+
70+
const HEX = "ea9b4d7a7a78a3e3729e5568b14d764d4962be0e1f20f749bcf8d9dbbf9a9328";
71+
const NPUB = "npub1a2d567n60z37xu57245tzntkf4yk90swrus0wjdulrvah0u6jv5qusyp60";
72+
const COMPACT_NPUB = "npub1a2d…yp60";
73+
74+
test("compact PubKey renders the truncated npub, never the hex", async () => {
75+
const React = await import("react");
76+
const { render } = await import("@testing-library/react");
77+
const { PubKey } = await import("./PubKey.tsx");
78+
79+
const view = render(React.createElement(PubKey, { pubkey: HEX }));
80+
81+
const trigger = view.getByRole("button", { name: "Show full public key" });
82+
assert.equal(trigger.textContent, COMPACT_NPUB);
83+
assert.equal(view.queryByText(HEX), null);
84+
});
85+
86+
test("non-interactive compact PubKey renders the truncated npub as text", async () => {
87+
const React = await import("react");
88+
const { render } = await import("@testing-library/react");
89+
const { PubKey } = await import("./PubKey.tsx");
90+
91+
const view = render(
92+
React.createElement(PubKey, { interactive: false, pubkey: HEX }),
93+
);
94+
95+
assert.equal(view.getByText(COMPACT_NPUB).tagName, "SPAN");
96+
assert.equal(view.queryByRole("button"), null);
97+
assert.equal(view.queryByText(HEX), null);
98+
});
99+
100+
test("full PubKey renders the complete npub with an npub-only copy popover", async () => {
101+
const React = await import("react");
102+
const { fireEvent, render, within } = await import("@testing-library/react");
103+
const { PubKey } = await import("./PubKey.tsx");
104+
105+
const view = render(
106+
React.createElement(PubKey, { pubkey: HEX, variant: "full" }),
107+
);
108+
109+
assert.equal(within(view.container).getByText(NPUB).textContent, NPUB);
110+
assert.equal(view.queryByText(HEX), null);
111+
112+
fireEvent.click(
113+
within(view.container).getByRole("button", { name: "Copy public key" }),
114+
);
115+
// The copy popover offers the full canonical npub only — no hex row.
116+
assert.equal(view.getAllByText(NPUB).length, 2);
117+
assert.equal(
118+
view.getByRole("button", { name: "Copy npub" }).tagName,
119+
"BUTTON",
120+
);
121+
assert.equal(view.queryByRole("button", { name: "Copy hex" }), null);
122+
assert.equal(view.queryByText("hex"), null);
123+
});
124+
125+
test("invalid keys render Unavailable with no copy affordance", async () => {
126+
const React = await import("react");
127+
const { render, within } = await import("@testing-library/react");
128+
const { PubKey } = await import("./PubKey.tsx");
129+
130+
const compact = render(React.createElement(PubKey, { pubkey: "zz" }));
131+
assert.equal(
132+
within(compact.container).getByText("Unavailable").tagName,
133+
"SPAN",
134+
);
135+
assert.equal(
136+
within(compact.container).queryByRole("button", {
137+
name: "Show full public key",
138+
}),
139+
null,
140+
);
141+
142+
const full = render(
143+
React.createElement(PubKey, { pubkey: "zz", variant: "full" }),
144+
);
145+
assert.equal(within(full.container).getByText("Unavailable").tagName, "SPAN");
146+
// No copy action for an identity that cannot be encoded.
147+
assert.equal(
148+
within(full.container).queryByRole("button", { name: "Copy public key" }),
149+
null,
150+
);
151+
});
152+
153+
test("degenerate-length hex keys render Unavailable, never a fake npub", async () => {
154+
const React = await import("react");
155+
const { render, within } = await import("@testing-library/react");
156+
const { PubKey } = await import("./PubKey.tsx");
157+
158+
// `npubEncode` happily encodes an 8-char hex into a valid-checksum npub —
159+
// that is not an identity key, so no surface may show or copy it.
160+
const short = render(React.createElement(PubKey, { pubkey: "deadbeef" }));
161+
assert.equal(
162+
within(short.container).getByText("Unavailable").tagName,
163+
"SPAN",
164+
);
165+
assert.equal(
166+
within(short.container).queryByRole("button", {
167+
name: "Show full public key",
168+
}),
169+
null,
170+
);
171+
172+
const shortFull = render(
173+
React.createElement(PubKey, { pubkey: "deadbeef", variant: "full" }),
174+
);
175+
assert.equal(
176+
within(shortFull.container).getByText("Unavailable").tagName,
177+
"SPAN",
178+
);
179+
assert.equal(
180+
within(shortFull.container).queryByRole("button", {
181+
name: "Copy public key",
182+
}),
183+
null,
184+
);
185+
assert.equal(shortFull.container.textContent?.includes("npub1"), false);
186+
});

0 commit comments

Comments
 (0)