Skip to content

Commit 908e07b

Browse files
committed
[lenny] merge: integrate upstream block/main 82656ff into product/main (3 commits: block#7489 block#7495 block#7493 npub identity follow-ups)
Signed-off-by: Michael Feth <[email protected]> # Conflicts: # desktop/src/features/agents/ui/RespondToField.tsx
2 parents ee2988c + 82656ff commit 908e07b

138 files changed

Lines changed: 3187 additions & 498 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎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/app/useTrayMenu.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
useManagedAgentsQuery,
1111
useRelayAgentsQuery,
1212
} from "@/features/agents/hooks";
13-
import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey";
13+
import { normalizePubkey, truncateNpub } from "@/shared/lib/pubkey";
1414
import { useNow } from "@/shared/lib/useNow";
1515
import { formatElapsed } from "@/features/agents/ui/agentSessionUtils";
1616
import type { Channel } from "@/shared/api/types";
@@ -72,7 +72,7 @@ export function useTrayMenu({
7272
activityId: `${channelTurn.channelId}:${normalizePubkey(pubkey)}`,
7373
agentName:
7474
agentNames.get(normalizePubkey(pubkey)) ??
75-
`Agent ${truncatePubkey(pubkey)}`,
75+
`Agent ${truncateNpub(pubkey)}`,
7676
channelId: channelTurn.channelId,
7777
channelName:
7878
channelNames.get(channelTurn.channelId) ?? "Unknown channel",

‎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: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,15 @@
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";
16+
import { normalizePubkey } from "@/shared/lib/pubkey";
1117

1218
export type ParsedAllowlist = {
1319
/** Successfully parsed entries — lowercase hex, deduplicated, in order. */
@@ -22,9 +28,9 @@ export type ParsedAllowlist = {
2228
* pattern used by `ChannelMemberInviteCard` so users have one mental model.
2329
*
2430
* - Splits on `/[\s,]+/`.
25-
* - Trims and lowercases each entry.
26-
* - Validates each entry is exactly 64 hex chars.
27-
* - Deduplicates while preserving insertion order.
31+
* - Accepts 64-char hex (any case) or `npub1…` bech32 per piece, normalizing
32+
* to the canonical lowercase hex pubkey.
33+
* - Deduplicates the canonical form while preserving insertion order.
2834
*/
2935
export function parsePubkeyInput(raw: string): ParsedAllowlist {
3036
const seen = new Set<string>();
@@ -33,31 +39,35 @@ export function parsePubkeyInput(raw: string): ParsedAllowlist {
3339
for (const piece of raw.split(/[\s,]+/)) {
3440
const trimmed = piece.trim();
3541
if (trimmed.length === 0) continue;
36-
if (!HEX_64.test(trimmed)) {
42+
const canonical = parseCanonicalPubkey(trimmed);
43+
if (canonical === null) {
3744
invalid.push(trimmed);
3845
continue;
3946
}
40-
const lower = trimmed.toLowerCase();
41-
if (!seen.has(lower)) {
42-
seen.add(lower);
43-
valid.push(lower);
47+
if (!seen.has(canonical)) {
48+
seen.add(canonical);
49+
valid.push(canonical);
4450
}
4551
}
4652
return { valid, invalid };
4753
}
4854

4955
/**
5056
* Merge an existing allowlist with newly-added pubkeys, normalizing and
51-
* deduplicating without reordering existing entries.
57+
* deduplicating without reordering existing entries. Both hex and npub
58+
* spellings normalize to the canonical hex, so the same key cannot enter
59+
* twice regardless of the form it was added in.
5260
*/
5361
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())];
62+
const normalize = (pubkey: string): string =>
63+
parseCanonicalPubkey(pubkey) ?? normalizePubkey(pubkey);
64+
const out = existing.map(normalize);
65+
const seen = new Set(out);
5666
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);
67+
const canonical = parseCanonicalPubkey(candidate);
68+
if (canonical === null || seen.has(canonical)) continue;
69+
seen.add(canonical);
70+
out.push(canonical);
6171
}
6272
return out;
6373
}

‎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/PersonaShareRecipients.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar";
1515
import { SelectedRecipientChip } from "@/features/profile/ui/SelectedRecipientChip";
1616
import { useIdentityQuery } from "@/shared/api/hooks";
1717
import type { UserSearchResult } from "@/shared/api/types";
18-
import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey";
18+
import { normalizePubkey, truncateNpub } from "@/shared/lib/pubkey";
1919
import { Popover, PopoverAnchor, PopoverContent } from "@/shared/ui/popover";
2020
import { Skeleton } from "@/shared/ui/skeleton";
2121

@@ -25,7 +25,7 @@ export function formatShareRecipientName(user: UserSearchResult) {
2525
return (
2626
user.displayName?.trim() ||
2727
user.nip05Handle?.trim() ||
28-
truncatePubkey(user.pubkey)
28+
truncateNpub(user.pubkey)
2929
);
3030
}
3131

‎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 { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey";
7+
import { parsePubkeyInput as parseCanonicalPubkey } from "@/shared/lib/nostrUtils";
8+
import { normalizePubkey, 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">

‎desktop/src/features/channels/lib/memberUtils.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { ChannelMember } from "@/shared/api/types";
2-
import { truncatePubkey } from "@/shared/lib/pubkey";
2+
import { truncateNpub } from "@/shared/lib/pubkey";
33

44
export const roleOrder: Record<ChannelMember["role"], number> = {
55
owner: 0,
@@ -17,7 +17,7 @@ export function formatMemberName(
1717
return "You";
1818
}
1919

20-
return member.displayName ?? truncatePubkey(member.pubkey);
20+
return member.displayName ?? truncateNpub(member.pubkey);
2121
}
2222

2323
export function compareMembersByRole(

0 commit comments

Comments
 (0)