Files
buzz/desktop/src/features/gifs/relay.ts
klopez4212 8471049c43 feat(desktop): add KLIPY GIF search to composers (#5554)
## Summary

- Supersedes #1913 with a KLIPY-hosted URL implementation.
- Adds KLIPY GIF search and trending results to desktop message and
forum composers.
- Keeps selected GIFs hosted by KLIPY; Buzz stores only the external URL
and media metadata (no imeta tag, since relays only accept hash-backed
local `/media/` entries).
- Aligns the Emoji/GIF picker with Buzz's standard segmented control,
theme surfaces, and motion behavior.

## Relay-to-provider boundary

- The relay proxies KLIPY search/share so the `BUZZ_KLIPY_API_KEY` never
reaches the desktop; the key stays server-side behind a redacted `Debug`
impl.
- The dedicated GIF `reqwest` client sets `redirect::Policy::none()`.
Because the API key rides in the request path, following a provider
`3xx` could replay a key-bearing URL to an attacker-chosen host (an
SSRF/key-disclosure primitive). With redirects disabled, a `3xx` returns
as a non-success status that the handlers map to a generic `502`; the
`Location` target is never read or forwarded.
- Admission reuses the established NIP-98, membership, replay, and
per-pubkey rate-limit gates, with an upstream response-size cap and
allowlisting so KLIPY error bodies never cross the relay boundary.

## Accessibility

- Under `prefers-reduced-motion: reduce`, the picker grid renders a
static provider poster (a normalized `jpg` asset) instead of the
animated preview, or a named static placeholder when no poster is
available. It reacts to preference changes while mounted.
`no-preference` keeps the animated preview.
- Selected GIFs carry their title through `ImetaMedia`'s `displayLabel`,
so the composer thumbnail, preview dialog, editor, lightbox, and remove
control all derive one non-empty accessible name instead of an empty
`Attachment ` label. Ordinary hashed uploads keep their existing
hash-derived names.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Kenny Lopez <klopez4212@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Signed-off-by: Hayt <9e1c23a3fd83f61da34420e4e88ff1b16e45cafcc0cd9019eb07d4ecfa8ca9b0@buzz.block.builderlab.xyz>
Co-authored-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Hayt <9e1c23a3fd83f61da34420e4e88ff1b16e45cafcc0cd9019eb07d4ecfa8ca9b0@buzz.block.builderlab.xyz>
2026-08-25 19:09:55 -04:00

143 lines
4.1 KiB
TypeScript

import {
type KlipyGif,
type KlipyResponse,
normalizeKlipyGifs,
relayKlipyCapability,
type RelayKlipyCapability,
type RelayGifSearchInfo,
} from "@/features/gifs/api";
import { relayHttpFromWs } from "@/shared/api/inviteHelpers";
import { signRelayEvent } from "@/shared/api/tauri";
const KLIPY_CUSTOMER_ID_STORAGE_KEY_PREFIX = "buzz:klipy-customer-id:v1:";
const NIP98_KIND = 27235;
function customerId(relayUrl: string): string {
if (typeof window === "undefined") return globalThis.crypto.randomUUID();
try {
const storageKey = `${KLIPY_CUSTOMER_ID_STORAGE_KEY_PREFIX}${relayUrl}`;
const existing = window.localStorage.getItem(storageKey);
if (existing) return existing;
const created = globalThis.crypto.randomUUID();
window.localStorage.setItem(storageKey, created);
return created;
} catch {
// Storage can be unavailable in hardened webviews. Prefer an ephemeral ID
// over a process-wide fallback that would correlate unrelated relays.
return globalThis.crypto.randomUUID();
}
}
async function sha256Hex(text: string): Promise<string> {
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(text),
);
return Array.from(new Uint8Array(digest))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
async function nip98PostHeader(url: string, body: string): Promise<string> {
const authEvent = await signRelayEvent({
kind: NIP98_KIND,
content: "",
tags: [
["u", url],
["method", "POST"],
["payload", await sha256Hex(body)],
["nonce", crypto.randomUUID()],
],
});
return `Nostr ${btoa(JSON.stringify(authEvent))}`;
}
const FRIENDLY_GIF_ERRORS: Record<string, string> = {
relay_membership_required: "Join this community to search GIFs.",
};
function gifErrorMessage(error: string | undefined, status: number): string {
if (error && FRIENDLY_GIF_ERRORS[error]) return FRIENDLY_GIF_ERRORS[error];
return error || `GIF request failed (${status})`;
}
async function relayPost<T>(
relayUrl: string,
path: string,
payload: Record<string, unknown>,
signal?: AbortSignal,
): Promise<T> {
const url = `${relayHttpFromWs(relayUrl).replace(/\/+$/, "")}${path}`;
const body = JSON.stringify(payload);
const response = await fetch(url, {
body,
headers: {
Authorization: await nip98PostHeader(url, body),
"Content-Type": "application/json",
},
method: "POST",
signal,
});
if (!response.ok) {
const json = (await response.json().catch(() => ({}))) as {
error?: string;
};
throw new Error(gifErrorMessage(json.error, response.status));
}
if (response.status === 204) return undefined as T;
return (await response.json()) as T;
}
/** The selected relay's advertised KLIPY endpoints, when supported. */
export async function relayKlipyEndpoints(
relayUrl: string,
signal?: AbortSignal,
): Promise<RelayKlipyCapability | null> {
const url = `${relayHttpFromWs(relayUrl).replace(/\/+$/, "")}/info`;
const response = await fetch(url, {
headers: { Accept: "application/nostr+json" },
signal,
});
if (!response.ok)
throw new Error(`Could not read relay capabilities (${response.status})`);
const info = (await response.json()) as RelayGifSearchInfo;
return relayKlipyCapability(info);
}
/** Search KLIPY through the selected relay without exposing its provider key. */
export async function fetchKlipyGifs(
relayUrl: string,
searchPath: string,
query: string,
signal?: AbortSignal,
): Promise<KlipyGif[]> {
const response = await relayPost<KlipyResponse>(
relayUrl,
searchPath,
{
customer_id: customerId(relayUrl),
locale: navigator.language || "en-US",
query: query.trim(),
},
signal,
);
if (response.result === false) {
throw new Error("GIF search failed");
}
return normalizeKlipyGifs(response.data?.data ?? []);
}
/** Report a selected GIF so KLIPY can update the anonymous user's Recents. */
export async function reportKlipyShare(
relayUrl: string,
sharePath: string,
slug: string,
): Promise<void> {
await relayPost<void>(relayUrl, sharePath, {
customer_id: customerId(relayUrl),
slug,
});
}