fix(cli): topic history decrypts like topic tail (bug5)

`topic history` never decrypted — it printed «(encrypted, Nb)» and the
member key while `topic tail` rendered the same messages. History now
takes tail's path: REST /messages (limit, before) under a read-scoped
key, the topic key via getTopicKey, and tail's shared renderer (author
name, reply context, 🔒 marker, --json with the plaintext). The v1
decode no longer renders binary as U+FFFD (its catch was dead code).

Spec: .artifacts/specs/2026-09-26-session-identity-and-routing.md §6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alejandro Gutiérrez
2026-09-26 21:08:48 +01:00
parent 33a54008e0
commit 6e044abd1f
2 changed files with 41 additions and 34 deletions

View File

@@ -16,6 +16,7 @@ import {
import { render } from "~/ui/render.js"; import { render } from "~/ui/render.js";
import { bold, clay, dim, yellow } from "~/ui/styles.js"; import { bold, clay, dim, yellow } from "~/ui/styles.js";
import { EXIT } from "~/constants/exit-codes.js"; import { EXIT } from "~/constants/exit-codes.js";
import { decodeBase64Utf8 } from "~/utils/text.js";
export interface TopicTailFlags { export interface TopicTailFlags {
mesh?: string; mesh?: string;
@@ -25,7 +26,7 @@ export interface TopicTailFlags {
forwardOnly?: boolean; forwardOnly?: boolean;
} }
interface TopicMessage { export interface TopicMessage {
id: string; id: string;
senderMemberId?: string; senderMemberId?: string;
senderPubkey: string; senderPubkey: string;
@@ -38,7 +39,7 @@ interface TopicMessage {
} }
/** Bounded recent-message cache used to render reply-context lines. */ /** Bounded recent-message cache used to render reply-context lines. */
type RenderedSnippet = { name: string; snippet: string }; export type RenderedSnippet = { name: string; snippet: string };
const RECENT_CACHE_MAX = 256; const RECENT_CACHE_MAX = 256;
function rememberRendered( function rememberRendered(
cache: Map<string, RenderedSnippet>, cache: Map<string, RenderedSnippet>,
@@ -66,14 +67,12 @@ interface HistoryResponse {
* the topic key separately — see decryptForRender below. * the topic key separately — see decryptForRender below.
*/ */
function decodeV1(b64: string): string { function decodeV1(b64: string): string {
try { // Buffer#toString never throws, so the old catch was dead code and
return Buffer.from(b64, "base64").toString("utf-8"); // binary rendered as U+FFFD garbage (spec 2026-09-26 §1).
} catch { return decodeBase64Utf8(b64) ?? "[not text]";
return "[decode failed]";
}
} }
async function decryptForRender( export async function decryptForRender(
m: TopicMessage, m: TopicMessage,
topicKey: Uint8Array | null, topicKey: Uint8Array | null,
): Promise<string> { ): Promise<string> {
@@ -95,7 +94,7 @@ function fmtTime(iso: string): string {
} }
} }
async function printMessage( export async function printMessage(
m: TopicMessage, m: TopicMessage,
topicKey: Uint8Array | null, topicKey: Uint8Array | null,
json: boolean, json: boolean,

View File

@@ -18,6 +18,7 @@
*/ */
import { withMesh } from "./connect.js"; import { withMesh } from "./connect.js";
import type { RenderedSnippet, TopicMessage } from "./topic-tail.js";
import { render } from "~/ui/render.js"; import { render } from "~/ui/render.js";
import { bold, clay, dim, green } from "~/ui/styles.js"; import { bold, clay, dim, green } from "~/ui/styles.js";
import { EXIT } from "~/constants/exit-codes.js"; import { EXIT } from "~/constants/exit-codes.js";
@@ -135,32 +136,39 @@ export async function runTopicHistory(topic: string, flags: TopicFlags): Promise
render.err("Usage: claudemesh topic history <topic> [--limit N] [--before <id>]"); render.err("Usage: claudemesh topic history <topic> [--limit N] [--before <id>]");
return EXIT.INVALID_ARGS; return EXIT.INVALID_ARGS;
} }
return await withMesh({ meshSlug: flags.mesh ?? null }, async (client) => { // bug5 (2026-09-26): history printed «(encrypted, Nb)» for every message
const limit = flags.limit ? Number(flags.limit) : undefined; // while `topic tail` decrypted the same ones. Same path as tail now: REST
const messages = await client.topicHistory({ // /messages with a read-scoped key, the topic key, the shared renderer.
topic, const cleanName = topic.replace(/^#/, "");
limit, const limit = flags.limit ? Number(flags.limit) : 50;
beforeId: flags.before, const { withRestKey } = await import("~/services/api/with-rest-key.js");
}); const { request } = await import("~/services/api/client.js");
if (flags.json) { const { getTopicKey } = await import("~/services/crypto/topic-key.js");
console.log(JSON.stringify(messages, null, 2)); const { printMessage } = await import("./topic-tail.js");
return withRestKey(
{ meshSlug: flags.mesh ?? null, purpose: `history-${cleanName}`, capabilities: ["read"], topicScopes: [cleanName] },
async ({ secret, mesh }) => {
const keyResult = await getTopicKey({ apiKeySecret: secret, memberSecretKeyHex: mesh.secretKey, topicName: cleanName });
const topicKey = keyResult.ok ? keyResult.topicKey ?? null : null;
const qs = new URLSearchParams({ limit: String(limit) });
if (flags.before) qs.set("before", flags.before);
const history = await request<{ messages: TopicMessage[] }>({
path: `/api/v1/topics/${encodeURIComponent(cleanName)}/messages?${qs.toString()}`,
token: secret,
});
const ordered = history.messages.slice().reverse(); // newest-first → chronological
if (!flags.json) {
if (ordered.length === 0) {
render.info(dim(`no messages in ${clay("#" + cleanName)}.`));
return EXIT.SUCCESS;
}
render.section(`${clay("#" + cleanName)} history (${ordered.length})`);
}
const cache = new Map<string, RenderedSnippet>();
for (const m of ordered) await printMessage(m, topicKey, !!flags.json, cache);
return EXIT.SUCCESS; return EXIT.SUCCESS;
} },
if (messages.length === 0) { );
render.info(dim(`no messages in ${clay("#" + topic)}.`));
return EXIT.SUCCESS;
}
// History returns newest-first; render oldest-first for chat UX.
const ordered = [...messages].reverse();
render.section(`${clay("#" + topic)} history (${ordered.length})`);
for (const m of ordered) {
const t = new Date(m.createdAt).toLocaleString();
process.stdout.write(
` ${dim(t)} ${bold(m.senderPubkey.slice(0, 8))} ${dim("(encrypted, " + m.ciphertext.length + "b)")}\n`,
);
}
return EXIT.SUCCESS;
});
} }
export async function runTopicMarkRead(topic: string, flags: TopicFlags): Promise<number> { export async function runTopicMarkRead(topic: string, flags: TopicFlags): Promise<number> {