tauri-app: 8a review fixes

- fetchBlob cache keyed by (did, cid), not just cid.
  Security: future per-DID access control on getBlob would
  otherwise leak the first responder's bytes to subsequent
  viewers.
- EmbedImage: pass did to releaseBlob, release previous cid
  on cid change (no leaked URLs).
- ComposeBox: releaseBlob called with both did and cid.
- pds-server: rename test
  get_blob_after_upload_with_different_did ->
  get_blob_returns_404_for_cross_did_cid_lookup. The
  docstring was misleading — the test only verifies the
  (did,cid) PK on the PDS row, not auth. The renamed name
  matches what the test actually checks.
- vitest: update releaseBlob call sites to the new
  (did, cid) signature.
This commit is contained in:
tomdebone
2026-07-06 18:53:09 +02:00
parent 226cfdac5c
commit b912132a05
8 changed files with 795 additions and 17 deletions
+192
View File
@@ -0,0 +1,192 @@
// Unit tests for the image-blob fetch pipeline in `client.ts`.
// We mock `@tauri-apps/api/core` so we don't need a running Tauri
// shell for the test, and we mock `URL.createObjectURL` /
// `URL.revokeObjectURL` so the test doesn't depend on a browser
// implementation (vitest's jsdom doesn't always wire these up).
//
// The tests cover:
// * the happy path — a successful `fetch_blob` invoke produces an
// object URL and the cache is populated so a second call is a no-op;
// * the cached path — a second `fetchBlob` for the same CID does not
// call `invoke` again;
// * the empty-blob error path — an empty payload throws;
// * `releaseBlob` / `clearBlobCache` keep the cache honest.
//
// Run with:
// npm test
// (or `npx vitest run src/lib/api/client.test.ts`)
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invokeMock = vi.fn();
vi.mock("@tauri-apps/api/core", () => ({
invoke: (...args: unknown[]) => invokeMock(...args),
}));
// Capture object URLs so the test can assert the cache is wired up.
// `createObjectURL` returns a fresh URL per call; tests should rely
// on the spy to know what URL was returned.
const createdUrls: string[] = [];
let _urlCounter = 0;
beforeEach(() => {
invokeMock.mockReset();
createdUrls.length = 0;
_urlCounter = 0;
// `URL.createObjectURL` exists in jsdom (vitest default) but
// returns the empty string — stub it so the test sees real-ish
// URLs and we can spot leaks.
vi.stubGlobal(
"URL",
class {
static createObjectURL(_blob: Blob): string {
const u = `blob:mock/${++_urlCounter}`;
createdUrls.push(u);
return u;
}
static revokeObjectURL(url: string): void {
const i = createdUrls.indexOf(url);
if (i >= 0) createdUrls.splice(i, 1);
}
},
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("fetchBlob", () => {
it("invokes the fetch_blob Tauri command and returns an object URL", async () => {
const { fetchBlob, clearBlobCache } = await import("./client");
clearBlobCache();
const cid = "bafyreifake";
const fakeBytes = new Uint8Array([1, 2, 3, 4]);
invokeMock.mockResolvedValueOnce(Array.from(fakeBytes));
const url = await fetchBlob("did:plc:alice", cid);
expect(url).toMatch(/^blob:mock\/\d+$/);
expect(createdUrls).toContain(url);
expect(invokeMock).toHaveBeenCalledTimes(1);
expect(invokeMock).toHaveBeenCalledWith("fetch_blob", {
did: "did:plc:alice",
cid,
});
});
it("caches the object URL — second call for the same cid is a no-op", async () => {
const { fetchBlob, clearBlobCache } = await import("./client");
clearBlobCache();
const cid = "bafyreicached";
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([9, 9, 9])));
const first = await fetchBlob("did:plc:bob", cid);
const second = await fetchBlob("did:plc:bob", cid);
expect(second).toBe(first);
// Only the first call should have round-tripped through the
// Tauri shell; the cache hit short-circuits everything else.
expect(invokeMock).toHaveBeenCalledTimes(1);
});
it("rejects on an empty payload from the Tauri shell", async () => {
const { fetchBlob, clearBlobCache } = await import("./client");
clearBlobCache();
invokeMock.mockResolvedValueOnce([]);
await expect(
fetchBlob("did:plc:carol", "bafyreifake"),
).rejects.toThrow(/empty blob/);
});
it("propagates a Tauri-side error verbatim", async () => {
const { fetchBlob, clearBlobCache } = await import("./client");
clearBlobCache();
invokeMock.mockRejectedValueOnce(new Error("sync.getBlob failed: 400"));
await expect(
fetchBlob("did:plc:dave", "bafyreifake"),
).rejects.toThrow(/sync\.getBlob failed: 400/);
});
});
describe("releaseBlob / clearBlobCache", () => {
it("drops the cached URL on releaseBlob", async () => {
const { fetchBlob, releaseBlob, clearBlobCache } = await import("./client");
clearBlobCache();
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([1])));
const cid = "bafyreirel";
const url = await fetchBlob("did:plc:e", cid);
expect(createdUrls).toContain(url);
releaseBlob("did:plc:e", cid);
expect(createdUrls).not.toContain(url);
});
it("clearBlobCache evicts every cached URL", async () => {
const { fetchBlob, clearBlobCache } = await import("./client");
clearBlobCache();
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([1])));
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([2])));
await fetchBlob("did:plc:f", "bafyreia");
await fetchBlob("did:plc:f", "bafyreib");
expect(createdUrls).toHaveLength(2);
clearBlobCache();
expect(createdUrls).toHaveLength(0);
});
});
describe("makeImagesEmbed", () => {
it("wraps a blob reference in an app.bsky.embed.images embed", async () => {
const { makeImagesEmbed } = await import("./client");
const blob = { cid: "bafyreicid", mimeType: "image/png", size: 42 };
const e = makeImagesEmbed(blob) as any;
expect(e.$type).toBe("app.bsky.embed.images");
expect(e.images).toHaveLength(1);
expect(e.images[0].image.$type).toBe("blob");
expect(e.images[0].image.ref.$link).toBe("bafyreicid");
expect(e.images[0].image.mimeType).toBe("image/png");
expect(e.images[0].image.size).toBe(42);
});
});
describe("pickAndUploadImage", () => {
it("returns null when the user cancels the picker", async () => {
const { pickAndUploadImage } = await import("./client");
invokeMock.mockResolvedValueOnce(null);
const r = await pickAndUploadImage();
expect(r).toBeNull();
// `invoke` is called with the command name and an empty
// argument bag (the Tauri runtime serialises the JS-side
// options, and `pick_and_upload_image` takes none).
expect(invokeMock).toHaveBeenCalledTimes(1);
expect(invokeMock.mock.calls[0][0]).toBe("pick_and_upload_image");
});
it("returns the parsed {cid, mimeType, size} on success", async () => {
const { pickAndUploadImage } = await import("./client");
invokeMock.mockResolvedValueOnce({
blob: {
$type: "blob",
ref: { $link: "bafyblob" },
mimeType: "image/jpeg",
size: 1234,
},
});
const r = await pickAndUploadImage();
expect(r).toEqual({
cid: "bafyblob",
mimeType: "image/jpeg",
size: 1234,
});
});
});
+79 -11
View File
@@ -135,11 +135,71 @@ export type ThreadResponse = {
repost_count?: number;
};
export async function createPost(text: string): Promise<Post> {
export async function createPost(
text: string,
embed?: unknown | null,
): Promise<Post> {
// The Rust post_create command returns a different shape (uri+cid
// only), but we keep the call simple: it gives us the cid we need
// to show the "ok" toast.
return await invoke<any>("post_create", { text });
// `embed` is forwarded verbatim; the caller is responsible for
// shaping it as an `app.bsky.embed.images` / `.external` / etc.
// record. Pass `null` or `undefined` to omit.
return await invoke<any>("post_create", {
text,
embed: embed ?? null,
});
}
/// `com.atproto.uploadBlob` wrapped with a file picker. Opens a
/// native OS dialog (via `tauri-plugin-dialog`), uploads the chosen
/// file to the user's PDS, and returns the parsed blob reference.
///
/// Returns `null` when the user cancels the picker. The Tauri shell
/// enforces a 1 MiB cap (matching the PDS's `MAX_BLOB_SIZE`) and
/// surfaces other errors via the rejected promise.
export async function pickAndUploadImage(): Promise<{
cid: string;
mimeType: string;
size: number;
} | null> {
const r = await invoke<{
blob: {
$type: string;
ref: { $link: string };
mimeType: string;
size: number;
};
} | null>("pick_and_upload_image");
if (!r) return null;
return {
cid: r.blob.ref.$link,
mimeType: r.blob.mimeType,
size: r.blob.size,
};
}
/// Helper that builds the `app.bsky.embed.images` embed for a single
/// image blob, ready to drop into a post record.
export function makeImagesEmbed(blob: {
cid: string;
mimeType: string;
size: number;
}): Record<string, unknown> {
return {
$type: "app.bsky.embed.images",
images: [
{
alt: "",
image: {
$type: "blob",
ref: { $link: blob.cid },
mimeType: blob.mimeType,
size: blob.size,
},
},
],
};
}
export async function describeServer(): Promise<any> {
@@ -294,23 +354,31 @@ export async function listenNotification(
// frontend never has to know the PDS URL.
//
// We cache the *resolved object URL* (not the raw bytes) keyed
// by CID, because:
// * the blob bytes are addressed by content hash, so the same
// CID always resolves to the same bytes regardless of DID;
// by `(did, cid)`, NOT just `cid`:
// * the blob *bytes* are addressed by content hash, so the same
// CID *usually* resolves to the same bytes regardless of DID;
// * BUT in the atproto sync spec, `com.atproto.sync.getBlob` is
// intentionally unauthenticated and keyed by `(did, cid)` on
// the server. A future change to a per-DID access control
// model would make the bytes differ per DID — caching by CID
// alone would then leak the first responder's bytes to every
// subsequent viewer.
// * the `<img>` element takes an object URL, not raw bytes, so
// handing the URL straight back to the caller saves a
// Blob/URL.createObjectURL call per render.
const _blobUrlCache = new Map<string, string>();
const _blobKey = (did: string, cid: string) => `${did}/${cid}`;
/// Fetch the raw blob bytes for `cid` and return an object URL
/// suitable for `<img src={...}>`. Caches the URL in-process so
/// navigating the timeline doesn't re-download already-seen
/// images.
/// images. Keyed by `(did, cid)` for the security reason above.
export async function fetchBlob(
did: string,
cid: string,
): Promise<string> {
const cached = _blobUrlCache.get(cid);
const key = _blobKey(did, cid);
const cached = _blobUrlCache.get(key);
if (cached) return cached;
const bytes: number[] = await invoke<number[]>("fetch_blob", {
did,
@@ -322,7 +390,7 @@ export async function fetchBlob(
}
const blob = new Blob([u8]);
const url = URL.createObjectURL(blob);
_blobUrlCache.set(cid, url);
_blobUrlCache.set(key, url);
return url;
}
@@ -331,11 +399,11 @@ export async function fetchBlob(
/// underlying Blob. For a Tauri WebView with at most a few
/// dozen visible images the OS cleans up anyway, but explicit
/// revocation makes long sessions friendlier on memory.
export function releaseBlob(cid: string): void {
const url = _blobUrlCache.get(cid);
export function releaseBlob(did: string, cid: string): void {
const url = _blobUrlCache.get(_blobKey(did, cid));
if (url) {
URL.revokeObjectURL(url);
_blobUrlCache.delete(cid);
_blobUrlCache.delete(_blobKey(did, cid));
}
}
@@ -1,12 +1,41 @@
<script lang="ts">
import { createPost, type Post } from "../api/client";
import {
createPost,
fetchBlob,
pickAndUploadImage,
makeImagesEmbed,
showError,
releaseBlob,
session,
type Post,
} from "../api/client";
const MAX = 160;
let { onPosted }: { onPosted?: () => void } = $props();
let text: string = $state("");
let isPosting: boolean = $state(false);
let isAttaching: boolean = $state(false);
let status: { kind: "ok" | "err" | "info"; msg: string } | null = $state(null);
// Currently logged-in user. We need the DID for `fetchBlob` (the
// PDS endpoint keys blobs by `(did, cid)`), so the compose box
// subscribes to the session store rather than taking a prop.
let did: string = $state("");
$effect(() => {
const u = $session;
did = u?.did ?? "";
});
// The currently-attached image. `null` = no attachment. We hold
// the blob reference + a local object URL for the preview so the
// user sees the image before they post.
let attachment: {
cid: string;
mimeType: string;
size: number;
previewUrl: string;
} | null = $state(null);
let remaining = $derived(MAX - text.length);
let counterClass = $derived(
remaining < 0 ? "counter counter--err" :
@@ -20,17 +49,66 @@
}
}
function fmtBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
return `${(n / (1024 * 1024)).toFixed(2)} MiB`;
}
async function attach() {
if (isAttaching || attachment) return;
if (!did) {
status = { kind: "err", msg: "> log in first" };
return;
}
isAttaching = true;
status = { kind: "info", msg: "> picking…" };
try {
const blob = await pickAndUploadImage();
if (!blob) {
// User cancelled — restore the previous status rather than
// leaving the "picking…" message on screen.
status = null;
return;
}
// Fetch the bytes back from the PDS so we can render the
// preview. `fetchBlob` caches by CID, so re-rendering the
// preview after a re-attach is cheap.
const previewUrl = await fetchBlob(did, blob.cid);
attachment = { ...blob, previewUrl };
status = { kind: "info", msg: `> attached (${fmtBytes(blob.size)})` };
} catch (e) {
status = { kind: "err", msg: `> ${String(e)}` };
} finally {
isAttaching = false;
}
}
function removeAttachment() {
if (attachment) {
// Revoke the object URL. `fetchBlob` may have evicted the
// cache entry for a different reason, so tolerate a no-op.
// The user can re-attach — the next fetch will allocate a
// fresh URL.
releaseBlob(did, attachment.cid);
attachment = null;
}
}
async function post() {
if (!text.trim() || remaining < 0 || isPosting) return;
isPosting = true;
status = { kind: "info", msg: "> posting…" };
try {
const r: Post = await createPost(text);
const embed = attachment ? makeImagesEmbed(attachment) : null;
const r: Post = await createPost(text, embed);
status = { kind: "ok", msg: `> ok (cid: ${(r as any).cid?.slice?.(0, 8) ?? "?"}…)` };
text = "";
removeAttachment();
onPosted?.();
} catch (e) {
status = { kind: "err", msg: `> ${String(e)}` };
showError(`post failed: ${e}`);
} finally {
isPosting = false;
}
@@ -53,9 +131,39 @@
maxlength="500"
></textarea>
</div>
{#if attachment}
<div class="compose__attach">
<img
class="compose__preview"
src={attachment.previewUrl}
alt="attachment preview"
/>
<div class="compose__attach-meta">
<span class="compose__attach-cid" title={attachment.cid}>cid: {attachment.cid.slice(0, 10)}…</span>
<span class="compose__attach-mime">{attachment.mimeType}</span>
<span class="compose__attach-size">{fmtBytes(attachment.size)}</span>
</div>
<button
type="button"
class="compose__attach-remove"
onclick={removeAttachment}
disabled={isPosting}
title="remove attachment"
>×</button>
</div>
{/if}
<div class="compose__foot">
<span class="hint">⌘↵ to post</span>
<div class="actions">
<button
type="button"
class="btn btn--ghost"
onclick={attach}
disabled={isAttaching || !!attachment || isPosting}
title={attachment ? "image already attached" : "attach image"}
>
{isAttaching ? "picking…" : "📎"}
</button>
<button class="btn btn--ghost" onclick={() => (text = "")} disabled={!text || isPosting}>draft</button>
<button class="btn btn--primary" onclick={post} disabled={!text.trim() || remaining < 0 || isPosting}>
{isPosting ? "posting…" : "post"}
@@ -114,6 +222,51 @@
padding: 0;
}
textarea::placeholder { color: var(--text-dim); }
.compose__attach {
display: flex;
align-items: center;
gap: var(--s-3);
padding: var(--s-3) var(--s-4);
background: var(--bg-deep);
border-top: 1px dashed var(--line);
}
.compose__preview {
width: 64px;
height: 64px;
object-fit: cover;
border-radius: var(--r-sm);
border: 1px solid var(--line-2);
background: var(--bg);
}
.compose__attach-meta {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
font-family: var(--font-mono);
font-size: var(--fs-50);
color: var(--text-dim);
}
.compose__attach-cid { color: var(--cid-fg); }
.compose__attach-mime,
.compose__attach-size { font-variant-numeric: tabular-nums; }
.compose__attach-remove {
background: transparent;
border: 1px solid var(--line-2);
color: var(--text-dim);
font-family: var(--font-mono);
font-size: var(--fs-100);
width: 28px;
height: 28px;
border-radius: var(--r-sm);
cursor: pointer;
line-height: 1;
}
.compose__attach-remove:hover:not(:disabled) {
color: var(--red);
border-color: var(--red);
}
.compose__attach-remove:disabled { opacity: 0.4; cursor: not-allowed; }
.compose__foot {
display: flex;
align-items: center;
@@ -146,4 +299,4 @@
.status--ok { color: var(--green); }
.status--err { color: var(--red); }
.status--info { color: var(--orange); }
</style>
</style>
@@ -81,8 +81,8 @@
// cache bounded to the visible images. The browser will
// free the underlying blob either way when the WebView
// navigates; this is just hygiene.
if (currentCid) {
releaseBlob(currentCid);
if (currentCid && did) {
releaseBlob(did, currentCid);
currentCid = null;
}
objectUrl = null;