Skip to content

Commit 2226b6f

Browse files
loganjLarry
andauthored
fix(desktop): npub identity controls across profile, agents, and workflows (#7489)
🤖 ## Summary Building on #7488's npub foundation, this PR finishes the identity display change for the controls where you actually manage people and keys: profile, settings, agent access, and workflows. Everywhere in these surfaces, an identity key shows — and copies — as its canonical npub (npub is the human-readable encoding of a Nostr public key: the compact `npub1j57...fjmv` form where space is tight, the full npub where the whole key matters), and accepts npub as input. After this change: - Profile panel: the public-key row and the managed-by / declared-owner copies show the full npub. If a key can't be encoded, you see "Unavailable" with no copy button — never a raw or partial key. - Settings: the identity card shows and copies the npub. The hosted-communities account identity derives from the bound key (`pubkey_hex`) — the same authority as the mismatch gate and hosted operations — so the display can never disagree with what the app acts on; an unusable hex falls back to a neutral label instead of rendering the unverified server npub. The connected claim and a community's Connect action require that same usable bound key to match the local one — with no usable binding the card cannot claim connected or start Connect, while the community list, linking, and delete/rebind recovery stay available. - Hosted create/onboarding: the account and device identity rows in the create flow and owner onboarding derive from the same authoritative fields (bound key / local key), with the same neutral fallback; readiness requires a usable bound key that matches the local one. - Respond-to allowlist (controls who may respond to an agent): entries can be typed or pasted as hex or npub; both spellings of the same key are recognized as one entry and dedupe. Search results, chips, and remove buttons use the compact npub. - Workflow key fields: to/from keys display as npubs in the form and save back as canonical hex. Templates like `{{trigger.author}}`, roles, and free text pass through untouched; placeholders accept both spellings. - Recipient and agent dialogs: the verify popover is npub-only (the raw-hex line is gone); denied-membership screens never show a raw key. - The Rust-side truncated display name (used for native surfaces) shows the same compact npub, so those surfaces match the web UI. Internal representation is unchanged: keys are still stored, sent, and matched as canonical 64-character hex — npub is a display and input spelling, normalized to hex at the boundary, so existing data and integrations keep working. Bound-key usability and comparison use one normalized form (trimmed, lowercased, 64 hex characters; npub rejected), so padded or mixed-case spellings of the same key match. Display names, private keys, and event IDs are untouched. ## Details - `respondToAllowlist` / `RespondToField`: npub entries normalize to canonical hex; cross-form dedupe; compact npub in rows and chips; direct-add accepts npub and stores canonical hex. - `workflowFormTypes` / `WorkflowStepCard`: hex → npub for display, npub → canonical hex on save; templates, roles, and free text pass through in both directions (roundtrip-tested). - `UserProfilePanelFields`, `ProfileSettingsCard`, `HostedCommunitiesSettingsCard`, `MembershipDenied`, `SelectedRecipientChip`, `AddAgentToChannelDialog`: npub display and copy; invalid keys → "Unavailable" with no copy; hosted identity rows derive from the bound `pubkey_hex` (create/onboarding rows from the bound and local keys), never the unverified server npub; connected/readiness/Connect gates use the same usable-bound-key predicate, and the settings Connect invocation callback re-checks it before starting. - `src-tauri/src/commands/identity.rs`: `truncated_display_name` compacts to the first 8 + last 4 characters of the npub (above a 12-char threshold), mirroring `truncateNpub`. - e2e: profile key rows and clipboard polls assert npub forms and raw-hex suppression; the display-screenshots spec pins the npub-only popover; hosted specs drive the real settings card, create flow, and onboarding rows through their real providers, and the unlinked/npub-only identity cases assert no connected claim and no Connect action. ### Related issue - Fixes: N/A. No separate issue; the related work is the stack below. - Stack: builds on #7488 (shared npub foundation), now merged; this PR is rebased onto main and stands on its own. ### Testing At head `303c90ffa` (base: main `bfc38485`; 24 files, +1125/−146): - Focused unit suites (respondToAllowlist, workflowFormTypes, hostedCommunityApi bound-key helpers) green; mutation-checked — dropping allowlist canonicalization fails the dedupe case, and dropping bound-key normalization fails the npub-in-hex and padded same-key cases. - Full desktop unit suite 6,477/6,477, `desktop-typecheck`, `desktop-check` (formatting fixed narrowly with `biome check --write` on the touched files only), and a fresh E2E build at the current head; the add-community + hosted-communities-settings specs 18/18 and onboarding integration 69/69 on a fresh dedicated port, with focused new-case runs 4+4 covering padded same-key (ready, Connect kept — no false rebind) and npub-in-hex (neutral label, recovery, no Connect) across the settings card, create flow, and first-community onboarding, plus the unlinked-account settings regression asserting Connect cannot occur. - `cargo fmt`/clippy (both feature sets) and `cargo test identity` (71 pass) passed at the earlier full-change head; since then, the only production changes in this PR's delta are the hosted identity display authority and its fail-closed bound-key gating/normalization above (base-side fixes carry #7488's receipts) — every other change is test-only. ### 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 ad2a841 commit 2226b6f

24 files changed

Lines changed: 1125 additions & 146 deletions

‎desktop/scripts/check-pubkey-truncation.mjs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
66
const projectRoot = path.resolve(__dirname, "..");
77

88
// Truncated pubkey prefixes are forgeable (vanity grinding), so all display
9-
// truncation goes through the canonical `truncatePubkey` / `<PubKey>` — this
10-
// guard keeps ad-hoc `pubkey.slice(0, N)` forms from fragmenting again.
9+
// truncation goes through the canonical `truncateNpub` (identity keys —
10+
// compact npub), `truncatePubkey` (generic hex identifiers such as event and
11+
// blob IDs), or `<PubKey>` — this guard keeps ad-hoc `pubkey.slice(0, N)`
12+
// forms from fragmenting again.
1113
const rules = [
1214
{
1315
root: "src",

‎desktop/src-tauri/src/commands/identity.rs‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,46 @@ use crate::{
1111
relay::{self, relay_api_base_url_with_override, relay_ws_url_with_override},
1212
};
1313

14-
/// Encode `pubkey` as npub bech32 and truncate it for display: first 10 chars
15-
/// + "…" + last 4 chars. Returns the full bech32 when it is 16 chars or fewer.
14+
/// Encode `pubkey` as npub bech32 and truncate it for display: first 8
15+
/// chars, an ellipsis, then the last 4 chars, mirroring the frontend
16+
/// `truncateNpub` compact policy (`first8…last4` of the whole npub string).
17+
/// Returns the full bech32 when it is 12 chars or fewer, mirroring
18+
/// `truncatePubkey`'s short-string threshold.
1619
fn truncated_display_name(pubkey: &PublicKey) -> Result<String, String> {
1720
let bech32 = pubkey
1821
.to_bech32()
1922
.map_err(|error| format!("bech32 encode failed: {error}"))?;
20-
Ok(if bech32.len() > 16 {
21-
format!("{}…{}", &bech32[..10], &bech32[bech32.len() - 4..])
23+
Ok(if bech32.len() > 12 {
24+
format!("{}…{}", &bech32[..8], &bech32[bech32.len() - 4..])
2225
} else {
2326
bech32
2427
})
2528
}
2629

30+
#[cfg(test)]
31+
mod truncated_display_name_tests {
32+
use super::truncated_display_name;
33+
use nostr::{PublicKey, ToBech32};
34+
35+
#[test]
36+
fn compacts_to_first_8_and_last_4_of_the_npub() {
37+
// Vector shared with the frontend `truncateNpub` tests; the expected
38+
// form is derived from the encoded npub, not hardcoded, so the test
39+
// asserts the compaction policy rather than one key's string.
40+
let hex = "ea9b4d7a7a78a3e3729e5568b14d764d4962be0e1f20f749bcf8d9dbbf9a9328";
41+
let pubkey = PublicKey::from_hex(hex).unwrap();
42+
let npub = pubkey.to_bech32().unwrap();
43+
let expected = format!("{}…{}", &npub[..8], &npub[npub.len() - 4..]);
44+
assert_eq!(truncated_display_name(&pubkey).unwrap(), expected);
45+
// 13 characters, matching the frontend compact form (the ellipsis is
46+
// one char but three UTF-8 bytes, so count chars, not bytes).
47+
assert_eq!(expected.chars().count(), 13);
48+
assert!(expected.starts_with("npub1"));
49+
// The compact form must not carry the raw hex key.
50+
assert!(!expected.contains(hex));
51+
}
52+
}
53+
2754
#[tauri::command]
2855
pub fn get_identity(state: State<'_, AppState>) -> Result<IdentityInfo, String> {
2956
let keys = state.keys.lock().map_err(|error| error.to_string())?;

‎desktop/src/features/agents/lib/respondToAllowlist.test.mjs‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ import { mergeAllowlist, parsePubkeyInput } from "./respondToAllowlist.ts";
66
const HEX_A = "a".repeat(64);
77
const HEX_B = "b".repeat(64);
88
const HEX_A_UPPER = "A".repeat(64);
9+
// Handoff vector, round-trip verified with nostr-tools nip19.
10+
const HEX = "ea9b4d7a7a78a3e3729e5568b14d764d4962be0e1f20f749bcf8d9dbbf9a9328";
11+
const HEX_NPUB =
12+
"npub1a2d567n60z37xu57245tzntkf4yk90swrus0wjdulrvah0u6jv5qusyp60";
913

1014
test("parsePubkeyInput splits on commas, whitespace, and newlines", () => {
1115
const input = `${HEX_A}, ${HEX_B}\n${HEX_A_UPPER}`;
@@ -25,11 +29,15 @@ test("parsePubkeyInput surfaces invalid entries separately", () => {
2529
assert.deepEqual(result.invalid, ["notgood", "z".repeat(64)]);
2630
});
2731

28-
test("parsePubkeyInput rejects npub-style strings (hex only)", () => {
29-
const npub = `npub1${"a".repeat(59)}`;
30-
const result = parsePubkeyInput(npub);
31-
assert.deepEqual(result.valid, []);
32-
assert.deepEqual(result.invalid, [npub]);
32+
test("parsePubkeyInput accepts npub entries, normalizes to hex, and dedupes across spellings", () => {
33+
// One invalid npub-shaped token proves classification at this seam; the
34+
// full codec negative matrix lives at the shared parser (nostrUtils).
35+
const corrupt = `${HEX_NPUB.slice(0, -2)}qq`;
36+
const result = parsePubkeyInput(
37+
`${HEX_NPUB} ${HEX} ${HEX.toUpperCase()} ${corrupt}`,
38+
);
39+
assert.deepEqual(result.valid, [HEX]);
40+
assert.deepEqual(result.invalid, [corrupt]);
3341
});
3442

3543
test("parsePubkeyInput rejects wrong-length entries", () => {
@@ -60,3 +68,8 @@ test("mergeAllowlist skips invalid additions silently", () => {
6068
const merged = mergeAllowlist([HEX_A], ["not-hex", HEX_B]);
6169
assert.deepEqual(merged, [HEX_A, HEX_B]);
6270
});
71+
72+
test("mergeAllowlist normalizes npub additions to canonical hex and dedupes", () => {
73+
assert.deepEqual(mergeAllowlist([HEX_A], [HEX_NPUB]), [HEX_A, HEX]);
74+
assert.deepEqual(mergeAllowlist([HEX], [HEX_NPUB]), [HEX]);
75+
});

‎desktop/src/features/agents/lib/respondToAllowlist.ts‎

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,14 @@
55
* `desktop/src-tauri/src/managed_agents/types.rs::validate_respond_to_allowlist`).
66
* These helpers exist to give the UI immediate, inline feedback before the
77
* round-trip, and to normalize input so the Rust validator sees clean data.
8+
*
9+
* Entry pieces may be 64-char hex pubkeys or bech32 `npub1…` strings; both are
10+
* normalized to the canonical lowercase hex via the shared
11+
* `parsePubkeyInput`, so npub and hex spellings of the same key dedupe to one
12+
* entry (users copy npubs from profile/verify surfaces elsewhere in the app).
813
*/
914

10-
const HEX_64 = /^[0-9a-f]{64}$/i;
15+
import { parsePubkeyInput as parseCanonicalPubkey } from "@/shared/lib/nostrUtils";
1116

1217
export type ParsedAllowlist = {
1318
/** Successfully parsed entries — lowercase hex, deduplicated, in order. */
@@ -22,9 +27,9 @@ export type ParsedAllowlist = {
2227
* pattern used by `ChannelMemberInviteCard` so users have one mental model.
2328
*
2429
* - Splits on `/[\s,]+/`.
25-
* - Trims and lowercases each entry.
26-
* - Validates each entry is exactly 64 hex chars.
27-
* - Deduplicates while preserving insertion order.
30+
* - Accepts 64-char hex (any case) or `npub1…` bech32 per piece, normalizing
31+
* to the canonical lowercase hex pubkey.
32+
* - Deduplicates the canonical form while preserving insertion order.
2833
*/
2934
export function parsePubkeyInput(raw: string): ParsedAllowlist {
3035
const seen = new Set<string>();
@@ -33,31 +38,35 @@ export function parsePubkeyInput(raw: string): ParsedAllowlist {
3338
for (const piece of raw.split(/[\s,]+/)) {
3439
const trimmed = piece.trim();
3540
if (trimmed.length === 0) continue;
36-
if (!HEX_64.test(trimmed)) {
41+
const canonical = parseCanonicalPubkey(trimmed);
42+
if (canonical === null) {
3743
invalid.push(trimmed);
3844
continue;
3945
}
40-
const lower = trimmed.toLowerCase();
41-
if (!seen.has(lower)) {
42-
seen.add(lower);
43-
valid.push(lower);
46+
if (!seen.has(canonical)) {
47+
seen.add(canonical);
48+
valid.push(canonical);
4449
}
4550
}
4651
return { valid, invalid };
4752
}
4853

4954
/**
5055
* Merge an existing allowlist with newly-added pubkeys, normalizing and
51-
* deduplicating without reordering existing entries.
56+
* deduplicating without reordering existing entries. Both hex and npub
57+
* spellings normalize to the canonical hex, so the same key cannot enter
58+
* twice regardless of the form it was added in.
5259
*/
5360
export function mergeAllowlist(existing: string[], add: string[]): string[] {
54-
const seen = new Set(existing.map((p) => p.toLowerCase()));
55-
const out = [...existing.map((p) => p.toLowerCase())];
61+
const normalize = (pubkey: string): string =>
62+
parseCanonicalPubkey(pubkey) ?? pubkey.toLowerCase();
63+
const out = existing.map(normalize);
64+
const seen = new Set(out);
5665
for (const candidate of add) {
57-
const lower = candidate.toLowerCase();
58-
if (!HEX_64.test(lower) || seen.has(lower)) continue;
59-
seen.add(lower);
60-
out.push(lower);
66+
const canonical = parseCanonicalPubkey(candidate);
67+
if (canonical === null || seen.has(canonical)) continue;
68+
seen.add(canonical);
69+
out.push(canonical);
6170
}
6271
return out;
6372
}

‎desktop/src/features/agents/ui/AddAgentToChannelDialog.tsx‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ import {
99
useChannelsQuery,
1010
} from "@/features/channels/hooks";
1111
import type { Channel, ChannelRole, ManagedAgent } from "@/shared/api/types";
12-
import { normalizePubkey } from "@/shared/lib/pubkey";
12+
import {
13+
canonicalNpub,
14+
normalizePubkey,
15+
UNAVAILABLE_KEY_LABEL,
16+
} from "@/shared/lib/pubkey";
1317
import { Button } from "@/shared/ui/button";
1418
import {
1519
Dialog,
@@ -87,6 +91,10 @@ export function AddAgentToChannelDialog({
8791
);
8892
}, [agent?.pubkey, membersQuery.data]);
8993

94+
// The agent's public key displays as its full canonical npub; an
95+
// unencodable key renders the neutral label and is not copyable.
96+
const agentNpub = agent?.pubkey ? canonicalNpub(agent.pubkey) : null;
97+
9098
const selectedChannel =
9199
channels.find((channel) => channel.id === channelId) ?? null;
92100

@@ -186,10 +194,12 @@ export function AddAgentToChannelDialog({
186194
</p>
187195
<div className="mt-3 flex items-center justify-between gap-3">
188196
<code className="min-w-0 flex-1 break-all rounded-xl border border-border/70 bg-background/80 px-3 py-2 text-xs">
189-
{agent?.pubkey ?? "No agent selected"}
197+
{agent
198+
? (agentNpub ?? UNAVAILABLE_KEY_LABEL)
199+
: "No agent selected"}
190200
</code>
191-
{agent ? (
192-
<CopyButton label="Copy pubkey" value={agent.pubkey} />
201+
{agent && agentNpub ? (
202+
<CopyButton label="Copy pubkey" value={agentNpub} />
193203
) : null}
194204
</div>
195205
</div>

‎desktop/src/features/agents/ui/RespondToField.tsx‎

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import {
44
mergeAllowlist,
55
parsePubkeyInput,
66
} from "@/features/agents/lib/respondToAllowlist";
7-
import { truncatePubkey } from "@/shared/lib/pubkey";
7+
import { parsePubkeyInput as parseCanonicalPubkey } from "@/shared/lib/nostrUtils";
8+
import { truncateNpub } from "@/shared/lib/pubkey";
89
import { PubKey } from "@/shared/ui/PubKey";
910
import { useIsArchivedPredicate } from "@/features/identity-archive/hooks";
1011
import { useUserSearchQuery } from "@/features/profile/hooks";
@@ -59,7 +60,7 @@ function formatSearchUserName(user: UserSearchResult) {
5960
return (
6061
user.displayName?.trim() ||
6162
user.nip05Handle?.trim() ||
62-
truncatePubkey(user.pubkey)
63+
truncateNpub(user.pubkey)
6364
);
6465
}
6566

@@ -69,7 +70,7 @@ function formatSearchUserSecondary(user: UserSearchResult) {
6970
if (displayName && nip05Handle) {
7071
return nip05Handle;
7172
}
72-
return truncatePubkey(user.pubkey);
73+
return truncateNpub(user.pubkey);
7374
}
7475

7576
const RESPOND_TO_OPTIONS: PersonaDropdownOption[] = [
@@ -278,8 +279,6 @@ export function CreateAgentRespondToField({
278279
);
279280
}
280281

281-
const HEX_64_RE = /^[0-9a-f]{64}$/i;
282-
283282
function AllowlistPicker({
284283
allowlist,
285284
deferredQuery,
@@ -325,10 +324,12 @@ function AllowlistPicker({
325324
}) {
326325
const isPersona = variant === "persona";
327326

328-
// Detect if the query is a valid hex pubkey that's not already in the list.
329-
const queryIsHexPubkey =
330-
HEX_64_RE.test(deferredQuery) &&
331-
!allowlist.some((p) => p.toLowerCase() === deferredQuery.toLowerCase());
327+
// Detect if the query is a pubkey (npub or hex) not already in the list;
328+
// direct entry offers the canonical hex for storage.
329+
const queryPubkey = parseCanonicalPubkey(deferredQuery);
330+
const queryIsDirectPubkey =
331+
queryPubkey !== null &&
332+
!allowlist.some((p) => p.toLowerCase() === queryPubkey);
332333

333334
return (
334335
<div
@@ -382,12 +383,12 @@ function AllowlistPicker({
382383
>
383384
<UserAvatar
384385
avatarUrl={null}
385-
displayName={truncatePubkey(pubkey)}
386+
displayName={truncateNpub(pubkey)}
386387
size="xs"
387388
/>
388389
<PubKey pubkey={pubkey} />
389390
<button
390-
aria-label={`Remove ${truncatePubkey(pubkey)}`}
391+
aria-label={`Remove ${truncateNpub(pubkey)}`}
391392
className="text-muted-foreground transition-colors hover:text-foreground"
392393
disabled={disabled}
393394
onClick={() => onRemove(pubkey)}
@@ -435,22 +436,22 @@ function AllowlistPicker({
435436
</button>
436437
))}
437438
</div>
438-
) : queryIsHexPubkey ? (
439+
) : queryIsDirectPubkey ? (
439440
<button
440441
className="flex w-full items-center justify-between rounded-md px-2.5 py-1.5 text-left transition-colors hover:bg-accent hover:text-accent-foreground"
441442
data-testid="agent-respond-to-add-raw-pubkey"
442-
onClick={() => onAddRawPubkey(deferredQuery.toLowerCase())}
443+
onClick={() => onAddRawPubkey(queryPubkey)}
443444
type="button"
444445
>
445446
<div className="flex items-center gap-2 min-w-0">
446447
<UserAvatar
447448
avatarUrl={null}
448-
displayName={truncatePubkey(deferredQuery)}
449+
displayName={truncateNpub(queryPubkey)}
449450
size="xs"
450451
/>
451452
<div className="min-w-0">
452453
<p className="truncate text-sm font-medium leading-5">
453-
{truncatePubkey(deferredQuery)}
454+
{truncateNpub(queryPubkey)}
454455
</p>
455456
<p className="truncate text-xs text-muted-foreground">
456457
Add pubkey directly
@@ -494,22 +495,22 @@ function AllowlistPicker({
494495
id="agent-respond-to-direct-panel"
495496
>
496497
<p className="text-xs text-muted-foreground">
497-
One per line, or comma/space-separated. 64-char lowercase hex
498-
only — npub decoding is not yet supported here.
498+
One per line, or comma/space-separated. Each entry is an npub
499+
(npub1…) or a 64-char hex public key.
499500
</p>
500501
<Textarea
501502
className="min-h-20 font-mono text-xs"
502503
data-testid="agent-respond-to-paste"
503504
disabled={disabled}
504505
onChange={(event) => onPasteTextChange(event.target.value)}
505-
placeholder="abcdef0123…"
506+
placeholder="npub1… or abcdef0123…"
506507
value={pasteText}
507508
/>
508509
{pasteInvalid.length > 0 ? (
509510
<p className="text-xs text-destructive">
510511
{pasteInvalid.length} entr
511-
{pasteInvalid.length === 1 ? "y is" : "ies are"} not 64-char
512-
hex and will be ignored.
512+
{pasteInvalid.length === 1 ? "y is" : "ies are"} not a valid
513+
npub or 64-char hex public key and will be ignored.
513514
</p>
514515
) : null}
515516
<div className="flex items-center justify-between gap-2">

0 commit comments

Comments
 (0)