From cae30f70897147413cad0ac16dea40bd084a8412 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:41:04 -0600 Subject: [PATCH 1/6] feat(import): conversation import protocol and plugin types Kinds 42110 to 42113 and the relay-signed 30623 snapshot: record templates in NIP-CI key and tag order, strict parsers, validation of prepared imported events, a filter that drops imported history from live batches, and the plugin-facing service types. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- .../conversation-import/protocol.test.ts | 401 +++++++++++ src/features/conversation-import/protocol.ts | 645 ++++++++++++++++++ src/features/conversation-import/types.ts | 236 +++++++ 3 files changed, 1282 insertions(+) create mode 100644 src/features/conversation-import/protocol.test.ts create mode 100644 src/features/conversation-import/protocol.ts create mode 100644 src/features/conversation-import/types.ts diff --git a/src/features/conversation-import/protocol.test.ts b/src/features/conversation-import/protocol.test.ts new file mode 100644 index 0000000000..2f4bc8e5c6 --- /dev/null +++ b/src/features/conversation-import/protocol.test.ts @@ -0,0 +1,401 @@ +import { describe, expect, it } from "vitest"; +import { getEventHash } from "nostr-tools"; +import { + completeTemplate, + consentTemplate, + fingerprint, + importedMarker, + importRecord, + importRecordText, + isImportedEvent, + parseProposal, + parseSnapshot, + preparedProblem, + proposalProblem, + proposalTemplate, + sourceLabel, + withdrawTemplate, + withoutImported, +} from "./protocol"; +import type { ImportProposalInput } from "./types"; + +const alice = "a".repeat(64); +const bob = "b".repeat(64); +const relay = "c".repeat(64); +const channel = "f0".repeat(16); +const proposalId = "1".repeat(64); +const manifest = "d".repeat(64); +const now = 1_740_000_000; + +const input: ImportProposalInput = { + channelId: channel, + source: { + type: "slack", + conversation: "e".repeat(64), + kind: "dm", + label: "Direct message", + }, + range: { from: 1_735_689_600, to: 1_735_776_000 }, + participants: [ + { pubkey: bob, source_user: "2".repeat(64), messages: 3, reactions: 1 }, + { pubkey: alice, source_user: "3".repeat(64), messages: 2, reactions: 0 }, + ], + excluded_authors: 1, + manifest, + expires_at: now + 86_400, +}; +const { channelId: _channel, ...content } = input; + +const signedFrom = ( + pubkey: string, + template: { kind: number; content: string; tags: string[][] }, + created_at = now, +) => { + const unsigned = { ...template, pubkey, created_at }; + return { ...unsigned, id: getEventHash(unsigned), sig: "0".repeat(128) }; +}; + +const rules = { + proposalId, + channelId: channel, + sourceType: "slack", + range: input.range, +}; +const message = ( + tags: string[][], + extra: Partial<{ content: string }> = {}, +) => ({ + kind: 9 as const, + created_at: 1_735_732_800, + tags, + content: extra.content ?? "Hello", +}); + +describe("deterministic ids", () => { + it("matches the NIP-CI test vector", () => { + expect( + getEventHash({ + pubkey: alice, + created_at: 1_735_732_800, + kind: 9, + tags: [ + ["h", channel], + ["import", proposalId], + ["source", "slack", "1735732800.000100"], + ], + content: 'Hello "world"\nline two é 😀', + }), + ).toBe("8700e9d79a391c7bde29babf26fd2167e00335bafa08abfc8e21ea34b68268e4"); + }); +}); + +describe("proposal", () => { + it("emits NIP-CI key order and sorted participant tags", () => { + const template = proposalTemplate(input); + expect(template.kind).toBe(42110); + expect(template.tags).toEqual([ + ["h", channel], + ["p", alice], + ["p", bob], + ["manifest", manifest], + ["import-source", "slack"], + ]); + expect(Object.keys(JSON.parse(template.content))).toEqual([ + "v", + "source", + "range", + "participants", + "excluded_authors", + "manifest", + "expires_at", + ]); + expect( + JSON.parse(template.content).participants.map( + (item: { pubkey: string }) => item.pubkey, + ), + ).toEqual([alice, bob]); + }); + + it("round-trips through the parser and rejects tags that disagree with content", () => { + const event = signedFrom(alice, proposalTemplate(input)); + expect(parseProposal(event)?.content.participants).toHaveLength(2); + const tampered = { + ...event, + tags: event.tags.map((tag) => + tag[0] === "manifest" ? ["manifest", "9".repeat(64)] : tag, + ), + }; + expect(parseProposal(tampered)).toBeUndefined(); + }); + + it("enforces the proposal rules", () => { + expect(proposalProblem(content, now)).toBeUndefined(); + expect( + proposalProblem( + { ...content, source: { ...content.source, type: "Slack!" } }, + now, + ), + ).toBeDefined(); + expect( + proposalProblem({ ...content, range: { from: 10, to: 10 } }, now), + ).toBeDefined(); + expect( + proposalProblem({ ...content, range: { from: 10, to: now + 60 } }, now), + ).toBeDefined(); + expect( + proposalProblem({ ...content, participants: [] }, now), + ).toBeDefined(); + expect( + proposalProblem( + { + ...content, + participants: [ + content.participants[0], + content.participants[0], + ] as never, + }, + now, + ), + ).toBeDefined(); + expect(proposalProblem({ ...content, manifest: "xyz" }, now)).toBeDefined(); + expect(proposalProblem({ ...content, expires_at: now }, now)).toBeDefined(); + expect( + proposalProblem({ ...content, excluded_authors: -1 }, now), + ).toBeDefined(); + }); +}); + +describe("records", () => { + it("builds consent, withdraw and complete records in NIP-CI tag order", () => { + const consent = consentTemplate( + { id: proposalId, channelId: channel, manifest, proposer: alice }, + "accept", + "2".repeat(64), + ); + expect(consent.tags).toEqual([ + ["e", proposalId], + ["h", channel], + ["manifest", manifest], + ["p", alice], + ]); + expect(consent.content).toBe( + `{"v":1,"decision":"accept","source_user":"${"2".repeat(64)}"}`, + ); + expect(withdrawTemplate(proposalId, channel).content).toBe('{"v":1}'); + expect(() => + withdrawTemplate(proposalId, channel, "x".repeat(201)), + ).toThrow(); + expect( + completeTemplate(proposalId, channel, { messages: 2, reactions: 0 }) + .content, + ).toBe('{"v":1,"published":{"messages":2,"reactions":0}}'); + }); + + it("describes each record as a system line", () => { + const records = [ + signedFrom(alice, proposalTemplate(input)), + signedFrom( + bob, + consentTemplate( + { id: proposalId, channelId: channel, manifest, proposer: alice }, + "accept", + "2".repeat(64), + ), + ), + signedFrom( + bob, + consentTemplate( + { id: proposalId, channelId: channel, manifest, proposer: alice }, + "accept", + "admin", + ), + ), + signedFrom(bob, withdrawTemplate(proposalId, channel, "Wrong range")), + signedFrom( + bob, + completeTemplate(proposalId, channel, { messages: 1, reactions: 2 }), + ), + ].map((event) => { + const record = importRecord(event); + return record && importRecordText(record); + }); + expect(records).toEqual([ + "Proposed importing Direct message from Slack", + "Accepted the conversation import", + "Approved the conversation import as an admin", + "Withdrew the conversation import: Wrong range", + "Finished importing 1 message and 2 reactions", + ]); + }); + + it("accepts session snapshots only from the relay key", () => { + const snapshot = { + kind: 30623, + content: JSON.stringify({ + v: 1, + status: "active", + required: [alice, bob], + consents: { [alice]: "accept", [bob]: "accept" }, + published: { [alice]: { messages: 1, reactions: 0 } }, + completed: [], + expires_at: now + 60, + }), + tags: [ + ["d", proposalId], + ["e", proposalId], + ["h", channel], + ["p", alice], + ["p", bob], + ], + }; + expect(parseSnapshot(signedFrom(relay, snapshot), relay)?.status).toBe( + "active", + ); + expect(parseSnapshot(signedFrom(alice, snapshot), relay)).toBeUndefined(); + }); +}); + +describe("imported events", () => { + it("validates the canonical kind 9 tag order", () => { + const base = [ + ["h", channel], + ["import", proposalId], + ["source", "slack", "1735732800.000100"], + ]; + expect(preparedProblem(message(base), rules, now)).toBeUndefined(); + expect( + preparedProblem( + message([ + ["h", channel], + ["e", "4".repeat(64), "", "root"], + ["e", "5".repeat(64), "", "reply"], + ["p", alice], + ["p", bob], + ["import", proposalId], + ["source", "slack", "1735732800.000200"], + ["source-edited", "1"], + ["source-flag", "broadcast"], + ["imeta", "url https://media.example/abc.png", "m image/png"], + ]), + rules, + now, + ), + ).toBeUndefined(); + expect( + preparedProblem( + message([ + ["h", channel], + ["p", bob], + ["p", alice], + ["import", proposalId], + ["source", "slack", "1"], + ]), + rules, + now, + ), + ).toMatch("sorted"); + expect( + preparedProblem( + message([base[1], base[0], base[2]] as string[][]), + rules, + now, + ), + ).toMatch("destination channel"); + expect( + preparedProblem(message([...base, ["client-id", "x"]]), rules, now), + ).toMatch("Unexpected tag"); + expect( + preparedProblem( + message([base[0], ["import", "9".repeat(64)], base[2]] as string[][]), + rules, + now, + ), + ).toBeDefined(); + expect( + preparedProblem( + { ...message(base), created_at: input.range.to + 1 }, + rules, + now, + ), + ).toMatch("range"); + expect( + preparedProblem(message(base, { content: " " }), rules, now), + ).toMatch("no content"); + expect( + preparedProblem( + { ...message(base), kind: 1 as unknown as 9 }, + rules, + now, + ), + ).toMatch("kind 9"); + }); + + it("validates the reaction tag order of the existing reaction builder", () => { + const reaction = { + kind: 7 as const, + created_at: 1_735_732_801, + content: "👍", + tags: [ + ["h", channel], + ["e", "4".repeat(64)], + ["import", proposalId], + ["source", "slack", "1735732800.000100"], + ], + }; + expect(preparedProblem(reaction, rules, now)).toBeUndefined(); + expect( + preparedProblem( + { + ...reaction, + tags: [ + reaction.tags[1], + reaction.tags[0], + ...reaction.tags.slice(2), + ] as string[][], + }, + rules, + now, + ), + ).toBeDefined(); + }); + + it("marks imported messages and keeps ordinary messages unmarked", () => { + const tags = [ + ["h", channel], + ["import", proposalId], + ["source", "slack", "1735732800.000100"], + ["source-edited", "1"], + ]; + expect(isImportedEvent({ kind: 9, tags })).toBe(true); + expect(isImportedEvent({ kind: 9, tags: [["h", channel]] })).toBe(false); + expect(importedMarker({ kind: 9, tags })).toEqual({ + proposalId, + source: "slack", + ref: "1735732800.000100", + sourceEdited: true, + }); + expect(importedMarker({ kind: 9, tags: [["h", channel]] })).toBeUndefined(); + }); + + it("drops imported history from a live batch before agents see it", () => { + const imported = { + kind: 7, + tags: [ + ["h", channel], + ["import", proposalId], + ["source", "slack", "1"], + ], + }; + const live = { kind: 9, tags: [["h", channel]] }; + const batch = { epoch: 1, events: [imported, live] }; + expect(withoutImported(batch)).toEqual({ epoch: 1, events: [live] }); + const plain = { epoch: 2, events: [live] }; + expect(withoutImported(plain)).toBe(plain); + }); + + it("labels known and unknown sources", () => { + expect(sourceLabel("slack")).toBe("Slack"); + expect(sourceLabel("team_chat")).toBe("Team Chat"); + expect(fingerprint("ab".repeat(32)).split(" ")).toHaveLength(8); + }); +}); diff --git a/src/features/conversation-import/protocol.ts b/src/features/conversation-import/protocol.ts new file mode 100644 index 0000000000..27f563948a --- /dev/null +++ b/src/features/conversation-import/protocol.ts @@ -0,0 +1,645 @@ +import type { + ImportCounts, + ImportProposalInput, + ImportSourceKind, + ImportStatus, + PreparedImportEvent, + ProposalParticipant, +} from "./types"; + +/** NIP-CI conversation import kinds. */ +export const IMPORT_PROPOSAL_KIND = 42110; +export const IMPORT_CONSENT_KIND = 42111; +export const IMPORT_WITHDRAW_KIND = 42112; +export const IMPORT_COMPLETE_KIND = 42113; +export const IMPORT_SNAPSHOT_KIND = 30623; +export const IMPORT_RECORD_KINDS: readonly number[] = [ + IMPORT_PROPOSAL_KIND, + IMPORT_CONSENT_KIND, + IMPORT_WITHDRAW_KIND, + IMPORT_COMPLETE_KIND, +]; +export const MAX_PROPOSAL_CONTENT_BYTES = 16 * 1024; +export const MAX_PARTICIPANTS = 64; + +const HEX64 = /^[0-9a-f]{64}$/; +const SOURCE_TYPE = /^[a-z0-9_-]{1,32}$/; +const SOURCE_KINDS: readonly ImportSourceKind[] = [ + "dm", + "group_dm", + "private_channel", + "public_channel", +]; +const STATUSES: readonly ImportStatus[] = [ + "proposed", + "active", + "declined", + "withdrawn", + "expired", + "completed", +]; + +type Tags = readonly (readonly string[])[]; +type Tagged = Readonly<{ kind: number; tags: Tags }>; +type Signed = Tagged & + Readonly<{ id: string; pubkey: string; content: string; created_at: number }>; + +const tagValue = (tags: Tags, name: string) => + tags.find((tag) => tag[0] === name)?.[1]; +const count = (value: unknown): value is number => + Number.isSafeInteger(value) && (value as number) >= 0; +const record = (value: unknown): value is Record => + !!value && typeof value === "object" && !Array.isArray(value); +const parse = (content: string): unknown => { + try { + return JSON.parse(content); + } catch { + return undefined; + } +}; + +/** Any kind 9 or 7 carrying an `import` tag is history: it never notifies, + * marks unread or bumps a conversation. */ +export function isImportedEvent(event: Tagged) { + return ( + (event.kind === 9 || event.kind === 7) && + event.tags.some((tag) => tag[0] === "import") + ); +} + +/** A live batch without imported history, for consumers that act on fresh + * activity such as agent dispatch. Returns the same batch when none is. */ +export function withoutImported< + T extends Readonly<{ events: readonly Tagged[] }>, +>(batch: T): T { + return batch.events.some(isImportedEvent) + ? { + ...batch, + events: batch.events.filter((event) => !isImportedEvent(event)), + } + : batch; +} + +export function sourceLabel(type: string) { + return type + .split(/[-_]+/) + .filter(Boolean) + .map((word) => word[0]?.toUpperCase() + word.slice(1)) + .join(" "); +} + +export const SOURCE_KIND_LABELS: Readonly> = { + dm: "Direct message", + group_dm: "Group direct message", + private_channel: "Private channel", + public_channel: "Public channel", +}; + +/** A 64-character hex key or hash as 8 groups of 8. */ +export function fingerprint(hex: string) { + return (hex.match(/.{1,8}/g) ?? []).join(" "); +} + +export type ImportedMarker = Readonly<{ + proposalId: string; + source: string; + ref: string; + sourceEdited?: true; +}>; + +export function importedMarker(event: Tagged): ImportedMarker | undefined { + if (event.kind !== 9) return; + const imports = event.tags.filter((tag) => tag[0] === "import"); + const sources = event.tags.filter((tag) => tag[0] === "source"); + const proposalId = imports[0]?.[1]; + const source = sources[0]?.[1]; + const ref = sources[0]?.[2]; + if ( + imports.length !== 1 || + sources.length !== 1 || + !proposalId || + !HEX64.test(proposalId) || + !source || + !SOURCE_TYPE.test(source) || + !ref + ) + return; + return Object.freeze({ + proposalId, + source, + ref, + ...(event.tags.some((tag) => tag[0] === "source-edited" && tag[1] === "1") + ? { sourceEdited: true as const } + : {}), + }); +} + +export type ImportProposalContent = Omit; + +/** Strict 42110 content. Returns the first rule the input breaks. */ +export function proposalProblem( + input: ImportProposalContent, + now: number, +): string | undefined { + const { source, range, participants } = input; + if (!record(source) || !SOURCE_TYPE.test(String(source.type))) + return "The source type is invalid."; + if (!HEX64.test(String(source.conversation))) + return "The source conversation hash is invalid."; + if (!SOURCE_KINDS.includes(source.kind)) + return "The source conversation kind is invalid."; + if ( + typeof source.label !== "string" || + !source.label.trim() || + [...source.label].length > 80 + ) + return "The source label must be 1 to 80 characters."; + if ( + !record(range) || + !count(range.from) || + !count(range.to) || + range.from >= range.to || + range.to > now + ) + return "The date range must end in the past and after it starts."; + if ( + !Array.isArray(participants) || + participants.length < 1 || + participants.length > MAX_PARTICIPANTS + ) + return `An import needs 1 to ${MAX_PARTICIPANTS} participants.`; + const seen = new Set(); + for (const participant of participants) { + if ( + !record(participant) || + !HEX64.test(String(participant.pubkey)) || + !HEX64.test(String(participant.source_user)) || + !count(participant.messages) || + !count(participant.reactions) || + seen.has(String(participant.pubkey)) + ) + return "A participant entry is invalid or repeated."; + seen.add(String(participant.pubkey)); + } + if (!count(input.excluded_authors)) + return "The excluded author count is invalid."; + if (!HEX64.test(String(input.manifest))) + return "The manifest hash is invalid."; + if (!count(input.expires_at) || input.expires_at <= now) + return "The proposal expiry must be in the future."; +} + +const sortedParticipants = (participants: readonly ProposalParticipant[]) => + [...participants].sort((a, b) => + a.pubkey < b.pubkey ? -1 : a.pubkey > b.pubkey ? 1 : 0, + ); + +/** Kind 42110 with the NIP-CI key and tag order. */ +export function proposalTemplate(input: ImportProposalInput) { + const participants = sortedParticipants(input.participants); + const content = JSON.stringify({ + v: 1, + source: { + type: input.source.type, + conversation: input.source.conversation, + kind: input.source.kind, + label: input.source.label, + }, + range: { from: input.range.from, to: input.range.to }, + participants: participants.map((participant) => ({ + pubkey: participant.pubkey, + source_user: participant.source_user, + messages: participant.messages, + reactions: participant.reactions, + })), + excluded_authors: input.excluded_authors, + manifest: input.manifest, + expires_at: input.expires_at, + }); + if (new TextEncoder().encode(content).length > MAX_PROPOSAL_CONTENT_BYTES) + throw new Error("The import proposal is larger than 16 KiB."); + return { + kind: IMPORT_PROPOSAL_KIND, + content, + tags: [ + ["h", input.channelId], + ...participants.map((participant) => ["p", participant.pubkey]), + ["manifest", input.manifest], + ["import-source", input.source.type], + ], + }; +} + +export function consentTemplate( + proposal: Readonly<{ + id: string; + channelId: string; + manifest: string; + proposer: string; + }>, + decision: "accept" | "decline", + sourceUser: string, +) { + return { + kind: IMPORT_CONSENT_KIND, + content: JSON.stringify({ v: 1, decision, source_user: sourceUser }), + tags: [ + ["e", proposal.id], + ["h", proposal.channelId], + ["manifest", proposal.manifest], + ["p", proposal.proposer], + ], + }; +} + +export function withdrawTemplate( + proposalId: string, + channelId: string, + reason?: string, +) { + const text = reason?.trim(); + if (text && [...text].length > 200) + throw new Error("A withdrawal reason can be at most 200 characters."); + return { + kind: IMPORT_WITHDRAW_KIND, + content: JSON.stringify(text ? { v: 1, reason: text } : { v: 1 }), + tags: [ + ["e", proposalId], + ["h", channelId], + ], + }; +} + +export function completeTemplate( + proposalId: string, + channelId: string, + published: ImportCounts, +) { + if (!count(published.messages) || !count(published.reactions)) + throw new Error("Published counts must be whole numbers."); + return { + kind: IMPORT_COMPLETE_KIND, + content: JSON.stringify({ + v: 1, + published: { + messages: published.messages, + reactions: published.reactions, + }, + }), + tags: [ + ["e", proposalId], + ["h", channelId], + ], + }; +} + +export type ParsedProposal = Readonly<{ + id: string; + channelId: string; + proposer: string; + createdAt: number; + content: ImportProposalContent; +}>; + +/** A 42110 whose tags agree with its content. Validity against the clock is + * the relay's call; the read model only rejects malformed records. */ +export function parseProposal(event: Signed): ParsedProposal | undefined { + if (event.kind !== IMPORT_PROPOSAL_KIND) return; + const channelId = tagValue(event.tags, "h"); + const body = parse(event.content); + if (!channelId || !record(body) || body.v !== 1) return; + const content = body as unknown as ImportProposalContent; + if ( + !record(content.source) || + !record(content.range) || + !Array.isArray(content.participants) || + !count(content.expires_at) || + proposalProblem( + { ...content, expires_at: Number.MAX_SAFE_INTEGER }, + Number(content.range.to), + ) + ) + return; + const pubkeys = event.tags + .filter((tag) => tag[0] === "p") + .map((tag) => tag[1]); + const declared = sortedParticipants(content.participants).map( + (participant) => participant.pubkey, + ); + if ( + tagValue(event.tags, "manifest") !== content.manifest || + tagValue(event.tags, "import-source") !== content.source.type || + pubkeys.length !== declared.length || + pubkeys.some((pubkey, index) => pubkey !== declared[index]) + ) + return; + return Object.freeze({ + id: event.id, + channelId, + proposer: event.pubkey, + createdAt: event.created_at, + content: Object.freeze({ + source: Object.freeze({ + type: content.source.type, + conversation: content.source.conversation, + kind: content.source.kind, + label: content.source.label, + }), + range: Object.freeze({ from: content.range.from, to: content.range.to }), + participants: Object.freeze( + content.participants.map((participant) => + Object.freeze({ + pubkey: participant.pubkey, + source_user: participant.source_user, + messages: participant.messages, + reactions: participant.reactions, + }), + ), + ), + excluded_authors: content.excluded_authors, + manifest: content.manifest, + expires_at: content.expires_at, + }), + }); +} + +/** A conversation import event shown in the timeline. */ +export type ImportRecord = + | Readonly<{ type: "proposal"; proposal: ParsedProposal }> + | Readonly<{ + type: "consent"; + proposalId: string; + decision: "accept" | "decline"; + admin: boolean; + }> + | Readonly<{ type: "withdraw"; proposalId: string; reason?: string }> + | Readonly<{ + type: "complete"; + proposalId: string; + published: ImportCounts; + }>; + +export function importRecord(event: Signed): ImportRecord | undefined { + if (event.kind === IMPORT_PROPOSAL_KIND) { + const proposal = parseProposal(event); + return proposal && Object.freeze({ type: "proposal", proposal }); + } + const proposalId = tagValue(event.tags, "e"); + const body = parse(event.content); + if (!proposalId || !HEX64.test(proposalId) || !record(body) || body.v !== 1) + return; + if (event.kind === IMPORT_CONSENT_KIND) { + if (body.decision !== "accept" && body.decision !== "decline") return; + return Object.freeze({ + type: "consent", + proposalId, + decision: body.decision, + admin: body.source_user === "admin", + }); + } + if (event.kind === IMPORT_WITHDRAW_KIND) + return Object.freeze({ + type: "withdraw", + proposalId, + ...(typeof body.reason === "string" && body.reason.trim() + ? { reason: Array.from(body.reason.trim()).slice(0, 200).join("") } + : {}), + }); + if (event.kind === IMPORT_COMPLETE_KIND) { + const published = body.published; + if ( + !record(published) || + !count(published.messages) || + !count(published.reactions) + ) + return; + return Object.freeze({ + type: "complete", + proposalId, + published: Object.freeze({ + messages: published.messages, + reactions: published.reactions, + }), + }); + } +} + +/** Plain text for previews, search and a missing renderer. Names are added by + * the timeline, which resolves the author. */ +export function importRecordText(record: ImportRecord) { + switch (record.type) { + case "proposal": + return `Proposed importing ${record.proposal.content.source.label} from ${sourceLabel(record.proposal.content.source.type)}`; + case "consent": + return record.decision === "accept" + ? record.admin + ? "Approved the conversation import as an admin" + : "Accepted the conversation import" + : "Declined the conversation import"; + case "withdraw": + return record.reason + ? `Withdrew the conversation import: ${record.reason}` + : "Withdrew the conversation import"; + case "complete": + return `Finished importing ${record.published.messages} ${record.published.messages === 1 ? "message" : "messages"} and ${record.published.reactions} ${record.published.reactions === 1 ? "reaction" : "reactions"}`; + } +} + +export type ParsedSnapshot = Readonly<{ + proposalId: string; + channelId: string; + createdAt: number; + status: ImportStatus; + required: readonly string[]; + consents: Readonly>; + published: Readonly>; + completed: readonly string[]; + expires_at: number; +}>; + +/** Only the community's relay key may state session status. */ +export function parseSnapshot( + event: Signed, + relayAuthor: string | undefined, +): ParsedSnapshot | undefined { + if ( + event.kind !== IMPORT_SNAPSHOT_KIND || + !relayAuthor || + event.pubkey !== relayAuthor + ) + return; + const proposalId = tagValue(event.tags, "d"); + const channelId = tagValue(event.tags, "h"); + const body = parse(event.content); + if ( + !proposalId || + !HEX64.test(proposalId) || + !channelId || + !record(body) || + body.v !== 1 || + !STATUSES.includes(body.status as ImportStatus) || + !Array.isArray(body.required) || + !body.required.every((key) => HEX64.test(String(key))) || + !record(body.consents) || + !record(body.published) || + !Array.isArray(body.completed) || + !body.completed.every((key) => HEX64.test(String(key))) || + !count(body.expires_at) + ) + return; + const consents: Record = {}; + for (const [key, value] of Object.entries(body.consents)) { + if (!HEX64.test(key) || (value !== "accept" && value !== "decline")) return; + consents[key] = value; + } + const published: Record = {}; + for (const [key, value] of Object.entries(body.published)) { + if ( + !HEX64.test(key) || + !record(value) || + !count(value.messages) || + !count(value.reactions) + ) + return; + published[key] = Object.freeze({ + messages: value.messages, + reactions: value.reactions, + }); + } + return Object.freeze({ + proposalId, + channelId, + createdAt: event.created_at, + status: body.status as ImportStatus, + required: Object.freeze(body.required.map(String)), + consents: Object.freeze(consents), + published: Object.freeze(published), + completed: Object.freeze(body.completed.map(String)), + expires_at: body.expires_at, + }); +} + +/** The first rule a prepared event breaks, or undefined. Mirrors the relay's + * import acceptance rules that the client can check, and the canonical tag + * order every participant needs for identical ids. */ +export function preparedProblem( + event: PreparedImportEvent, + session: Readonly<{ + proposalId: string; + channelId: string; + sourceType: string; + range: Readonly<{ from: number; to: number }>; + }>, + now: number, +): string | undefined { + if (!event || (event.kind !== 9 && event.kind !== 7)) + return "Only messages (kind 9) and reactions (kind 7) can be imported."; + if ( + !Number.isSafeInteger(event.created_at) || + event.created_at < session.range.from || + event.created_at > session.range.to + ) + return "The event time is outside the proposal's date range."; + if (event.created_at > now) return "The event time is in the future."; + if (typeof event.content !== "string" || !event.content.trim()) + return "The event has no content."; + const tags = event.tags; + if ( + !Array.isArray(tags) || + tags.some( + (tag) => + !Array.isArray(tag) || + !tag.length || + tag.some((value) => typeof value !== "string"), + ) + ) + return "The event tags are malformed."; + let index = 0; + const at = (): readonly string[] | undefined => tags[index]; + const expect = ( + test: (tag: readonly string[]) => boolean, + problem: string, + ) => { + const tag = at(); + if (!tag || !test(tag)) return problem; + index++; + }; + const h = expect( + (tag) => tag.length === 2 && tag[0] === "h" && tag[1] === session.channelId, + "The first tag must be the destination channel.", + ); + if (h) return h; + if (event.kind === 9) { + const root = at(); + if (root?.[0] === "e" && root[3] === "root") { + if (root.length !== 4 || !HEX64.test(root[1] ?? "") || root[2] !== "") + return "The thread root tag is malformed."; + index++; + if (at()?.[3] !== "reply") + return "A thread root tag must be followed by a reply tag."; + } + const reply = at(); + if (reply?.[0] === "e") { + if ( + reply.length !== 4 || + !HEX64.test(reply[1] ?? "") || + reply[2] !== "" || + reply[3] !== "reply" + ) + return "The reply tag is malformed."; + index++; + } + let previous = ""; + while (at()?.[0] === "p") { + const value = at()?.[1] ?? ""; + if (at()?.length !== 2 || !HEX64.test(value) || value <= previous) + return "Mention tags must be unique and sorted ascending."; + previous = value; + index++; + } + } else { + const target = expect( + (tag) => tag.length === 2 && tag[0] === "e" && HEX64.test(tag[1] ?? ""), + "A reaction needs its target message tag after the channel tag.", + ); + if (target) return target; + } + const importTag = expect( + (tag) => + tag.length === 2 && tag[0] === "import" && tag[1] === session.proposalId, + "The import tag must name this proposal.", + ); + if (importTag) return importTag; + const source = expect( + (tag) => + tag.length === 3 && + tag[0] === "source" && + tag[1] === session.sourceType && + !!tag[2], + "The source tag must name the proposal's source and a message reference.", + ); + if (source) return source; + if (event.kind === 9) { + if (at()?.[0] === "source-edited") { + if (at()?.length !== 2 || at()?.[1] !== "1") + return "The source-edited tag is malformed."; + index++; + } + if (at()?.[0] === "source-flag") { + if (at()?.length !== 2 || at()?.[1] !== "broadcast") + return "Only the broadcast source flag is defined."; + index++; + } + while (at()?.[0] === "imeta") { + if ( + !at() + ?.slice(1) + .some((field) => field.startsWith("url ")) + ) + return "An attachment tag has no URL."; + index++; + } + } + if (index !== tags.length) + return `Unexpected tag "${tags[index]?.[0]}" at position ${index + 1}.`; +} diff --git a/src/features/conversation-import/types.ts b/src/features/conversation-import/types.ts new file mode 100644 index 0000000000..08c1b77eca --- /dev/null +++ b/src/features/conversation-import/types.ts @@ -0,0 +1,236 @@ +import type {} from "@deepseek-ai/cordis"; +/** Plugin-facing conversation import types (NIP-CI). Exported through the + * author package; the host service implements `ConversationImportService`. */ + +export type ImportSourceKind = + | "dm" + | "group_dm" + | "private_channel" + | "public_channel"; + +/** A relay-signed kind 30382 identity. Never derived from kind 0. */ +export type VerifiedProfileView = Readonly<{ + pubkey: string; + displayName: string; + username: string; + fullName?: string; + issuerLabel: string; + verifiedAt: number; + /** The pubkey as 8 groups of 8 hex characters. */ + fingerprint: string; +}>; + +export type ProposalParticipant = Readonly<{ + pubkey: string; + source_user: string; + messages: number; + reactions: number; +}>; + +/** Kind 42110 content plus the channel it is proposed in. The host adds the tags. */ +export type ImportProposalInput = Readonly<{ + channelId: string; + source: Readonly<{ + type: string; + conversation: string; + kind: ImportSourceKind; + label: string; + }>; + range: Readonly<{ from: number; to: number }>; + participants: readonly ProposalParticipant[]; + excluded_authors: number; + manifest: string; + expires_at: number; +}>; + +export type ImportStatus = + | "proposed" + | "active" + | "declined" + | "withdrawn" + | "expired" + | "completed"; + +export type ImportCounts = Readonly<{ messages: number; reactions: number }>; + +/** The relay snapshot (kind 30623) joined with the proposal it describes. + * Before the relay publishes a snapshot, status is `proposed` and `required` + * lists the proposal's participants. */ +export type ImportSessionView = Readonly<{ + proposalId: string; + channelId: string; + proposer: string; + /** Unix seconds of the proposal event. */ + proposedAt: number; + proposal: Omit; + status: ImportStatus; + required: readonly string[]; + consents: Readonly>; + published: Readonly>; + completed: readonly string[]; + expires_at: number; + /** False until a relay-signed snapshot for this proposal has been read. */ + confirmed: boolean; +}>; + +export type PreparedImportEvent = Readonly<{ + kind: 9 | 7; + created_at: number; + tags: readonly (readonly string[])[]; + content: string; +}>; + +export type UnsignedImportEvent = PreparedImportEvent & + Readonly<{ pubkey: string }>; + +export type PublishProgress = Readonly<{ + published: number; + total: number; + /** Display name of the participant whose parent event is awaited. */ + waitingFor?: string; +}>; + +export type PublishReport = Readonly<{ + /** `waiting`: a parent from another participant did not arrive in time. + * `stopped`: cancelled, or the session stopped being active. + * `rejected`: the host or relay refused an event; `reason` is verbatim. */ + status: "done" | "stopped" | "waiting" | "rejected"; + published: number; + /** Ids of accepted events, in input order. */ + ids: readonly string[]; + /** Index of the first event not published. */ + stoppedAt?: number; + reason?: string; +}>; + +export type ReadBackEvent = Readonly<{ + id: string; + pubkey: string; + kind: number; + source_ref: string; + created_at: number; +}>; + +export type ReadBackReport = Readonly<{ events: readonly ReadBackEvent[] }>; + +export type MembershipView = Readonly<{ + members: string[]; + channelType: "dm" | "channel"; + visibility: "private" | "public" | "unknown"; +}>; + +export type ImportedAttachment = Readonly<{ + url: string; + /** Attachment tags (one `imeta`) to embed in the imported event. */ + tags: string[][]; + /** The Markdown link Buzz appends to message content for this file. */ + markdown: string; +}>; + +/** What every participant knows about a source file before anyone uploads it. */ +export type AttachmentTagsInput = Readonly<{ + sha256Hex: string; + name: string; + size: number; + /** The file's first 4096 bytes, or the whole file when shorter. The relay + * stores a file under the type it sniffs from these, not a declared type. */ + head: Uint8Array; +}>; + +export interface ConversationImportService { + /** Verified identity from the relay-signed kind 30382 record; undefined when none. Never falls back to kind 0. */ + verifiedProfile(pubkey: string): VerifiedProfileView | undefined; + /** Search verified profiles by exact username. Kind 30382 carries no + * email, so an email-only query rejects. Returns only relay-verified records. */ + findVerified( + query: { email?: string; username?: string }, + signal?: AbortSignal, + ): Promise; + /** Finds the DM with exactly these members (viewer + others) or, after a host-owned confirmation listing fingerprints, opens it. */ + ensureDirectMessage( + otherPubkeys: string[], + opts: { createIfMissing: boolean }, + signal?: AbortSignal, + ): Promise<{ channelId: string; created: boolean; members: string[] }>; + /** Finds or creates a channel with the given name/visibility/members behind a host-owned confirmation. Private channels get exactly `members`. */ + ensureChannel( + input: { + name: string; + visibility: "private" | "public"; + members: string[]; + existingChannelId?: string; + }, + signal?: AbortSignal, + ): Promise<{ channelId: string; created: boolean; members: string[] }>; + /** Current members of a channel (kind 39002 read model) and channel type/visibility. */ + membership(channelId: string): MembershipView | undefined; + /** Shows the host-owned proposal dialog (dry-run summary) and on approval signs and publishes kind 42110. */ + propose( + input: ImportProposalInput, + signal?: AbortSignal, + ): Promise<{ proposalId: string }>; + /** Shows the host-owned consent dialog and on approval publishes kind 42111. */ + consent( + proposalId: string, + decision: "accept" | "decline", + sourceUserHash: string, + signal?: AbortSignal, + ): Promise; + withdraw(proposalId: string, reason?: string): Promise; + complete(proposalId: string, published: ImportCounts): Promise; + /** Read model of the relay snapshot (kind 30623) plus the proposal content. */ + session(proposalId: string): ImportSessionView | undefined; + /** Reads the proposal and its newest relay snapshot from the relay, for + * proposals outside the viewer's own sessions. */ + refresh( + proposalId: string, + signal?: AbortSignal, + ): Promise; + /** All sessions visible to the viewer. Calls back immediately with the current list. */ + subscribe(cb: (sessions: readonly ImportSessionView[]) => void): () => void; + /** Signs and publishes prepared events authored by the viewer under an active session. Validates each (pubkey = viewer, import tag = proposalId, kind 9|7, created_at within range, tag order), paces (<= 8 events/s), waits for cross-author parents, stops on the first rejection and returns the report. + * Publishing requires a relay snapshot with status `active`. Immediately + * before signing each event, the destination's type and visibility must + * still match the source and its current members must equal + * `expectedMembers` exactly. For direct message and private channel sources + * it defaults to the proposal's participants; for direct messages it must + * equal them, and for private channels it must be a subset of them. A + * change stops the run with status `stopped`. */ + publish( + proposalId: string, + events: readonly PreparedImportEvent[], + opts: { + onProgress?: (p: PublishProgress) => void; + expectedMembers?: readonly string[]; + }, + signal?: AbortSignal, + ): Promise; + /** The content-addressed URL, attachment tags and Markdown link for a file, + * computed from its hash, name, size and first bytes alone, so every + * participant derives the same event id whoever uploads it. Throws for a + * file type the relay refuses or that cannot be predicted; import that + * file as a placeholder instead. */ + attachmentTags(input: AttachmentTagsInput): ImportedAttachment; + /** Uploads a file through the host media path and returns `attachmentTags` + * for it. Throws when the server stores different bytes or a different URL + * than predicted. Uploads are channel-scoped: pass the destination channel. */ + uploadAttachment( + file: Blob, + name: string, + sha256Hex: string, + signal?: AbortSignal, + options?: { channelId?: string }, + ): Promise; + /** Computes the Nostr id for an unsigned event (pubkey, created_at, kind, tags, content) so plugins can derive parent ids for other authors. */ + eventId(unsigned: UnsignedImportEvent): string; + /** Checks whether an event id exists in the channel history read model (used while waiting for a partner's parent). */ + exists(channelId: string, eventId: string): boolean; + /** Reads back imported events for a session: ids, authors, source refs, created_at. No content. */ + readBack(proposalId: string, signal?: AbortSignal): Promise; +} + +declare module "@deepseek-ai/cordis" { + interface Context { + conversationImport: ConversationImportService; + } +} From d3fa53f84785acbcc8d55856a2b314a429d58877 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:41:05 -0600 Subject: [PATCH 2/6] feat(relay): host-only explicit-timestamp path for imported events The outbox gains sendAt for imported history at its original time with a deterministic id, and sendRecord for import records carrying exactly the NIP-CI tags. Both go through a module-private send path; the public send and retry refuse import entries, so listeners cannot forge them. A session's import writer serves only the first service that claims it. Failed import entries do not count toward the pending limit. Relay refusal text is kept on the journal entry. The native signer checks the record shape of kinds 42110 to 42113 as the browser broker does, and hosts report NIP-CI support from the relay's NIP-11 document. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- browser-host/relay-broker.mjs | 46 +++ browser-host/relay-broker.test.mjs | 41 +++ browser-host/workflow-broker.test.mjs | 8 +- src-tauri/src/relay.rs | 30 ++ src-tauri/src/relay/tests.rs | 43 +++ src/features/relay/import-writes.ts | 38 ++ src/features/relay/live.ts | 3 +- src/features/relay/mentions.test.ts | 40 +- src/features/relay/native.test.ts | 79 ++++ src/features/relay/native.ts | 90 ++++- src/features/relay/outbox-import.test.ts | 317 ++++++++++++++++ src/features/relay/outbox.ts | 449 +++++++++++++++-------- src/features/relay/session.ts | 23 +- src/features/relay/transport.ts | 7 + 14 files changed, 1035 insertions(+), 179 deletions(-) create mode 100644 src/features/relay/import-writes.ts create mode 100644 src/features/relay/outbox-import.test.ts diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index 14029a7e03..ea4b32747a 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -332,6 +332,10 @@ async function relayAuthority(fetch, relay) { searchSort: Array.isArray(nip11.supported_extensions) && nip11.supported_extensions.includes("buzz-search-sort"), + // NIP-CI: the relay admits consented conversation imports. + conversationImport: + Array.isArray(nip11.supported_extensions) && + nip11.supported_extensions.includes("nip-ci"), ...(readSnapshotCommunity(nip11.read_state_snapshot) ? { readStateCommunity: readSnapshotCommunity(nip11.read_state_snapshot) } : {}), @@ -511,6 +515,38 @@ export function validMessageTemplate(event) { })() ); } +/** NIP-CI proposal, consent, withdrawal or completion: one channel, JSON + * content within 16 KiB, and a proposal reference on everything but the + * proposal itself. The relay decides membership and session rules. */ +export function validImportRecordTemplate(event) { + if ( + !event || + !(event.kind >= 42110 && event.kind <= 42113) || + typeof event.content !== "string" || + Buffer.byteLength(event.content) > 16 * 1024 || + !Number.isSafeInteger(event.created_at) || + event.created_at < 0 || + !Array.isArray(event.tags) || + !event.tags.every( + (tag) => + Array.isArray(tag) && + tag.length >= 2 && + tag.every((value) => typeof value === "string"), + ) || + event.tags.filter((tag) => tag[0] === "h" && tag[1]).length !== 1 + ) + return false; + try { + const body = JSON.parse(event.content); + if (!body || typeof body !== "object" || body.v !== 1) return false; + } catch { + return false; + } + const references = event.tags.filter((tag) => tag[0] === "e"); + return event.kind === 42110 + ? !references.length + : references.length === 1 && /^[0-9a-f]{64}$/.test(references[0][1]); +} /** NIP-56 message report: exactly one author and one typed message target. */ export function validReport(event) { if ( @@ -1548,6 +1584,10 @@ export function relayBrokerPlugin({ 9, 40003, 42000, + 42110, + 42111, + 42112, + 42113, 9000, 9001, 30078, @@ -2758,6 +2798,12 @@ export function relayBrokerPlugin({ error: "Malformed catalog publication", sent: false, }); + } else if (filters?.kind >= 42110 && filters?.kind <= 42113) { + if (!validImportRecordTemplate(filters)) + return json(res, 400, { + error: "Conversation import record rejected", + sent: false, + }); } else if (filters?.kind === 45010) { // NIP-AR artifacts; the relay enforces write permission. } else if (filters?.kind === 1984) { diff --git a/browser-host/relay-broker.test.mjs b/browser-host/relay-broker.test.mjs index ac3cacf050..41c5cdea17 100644 --- a/browser-host/relay-broker.test.mjs +++ b/browser-host/relay-broker.test.mjs @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { createUpstream, validFilters, + validImportRecordTemplate, validMessageTemplate, } from "./relay-broker.mjs"; @@ -230,3 +231,43 @@ test("workflow list batches alone may exceed four filters, with 128 unique chann ]) assert.equal(validFilters(invalid), false); }); + +test("broker signs only well-formed conversation import records", () => { + const channel = "f0".repeat(16); + const proposal = "1".repeat(64); + const record = (kind, tags, content = '{"v":1}') => ({ + kind, + content, + created_at: 1_740_000_000, + tags, + }); + assert.equal( + validImportRecordTemplate(record(42110, [["h", channel]])), + true, + ); + assert.equal( + validImportRecordTemplate( + record(42111, [ + ["e", proposal], + ["h", channel], + ]), + ), + true, + ); + for (const bad of [ + record(42110, [ + ["h", channel], + ["e", proposal], + ]), + record(42112, [["h", channel]]), + record(42113, [ + ["e", "x"], + ["h", channel], + ]), + record(42111, [["e", proposal]]), + record(42110, [["h", channel]], '{"v":2}'), + record(42110, [["h", channel]], "not json"), + record(9, [["h", channel]]), + ]) + assert.equal(validImportRecordTemplate(bad), false); +}); diff --git a/browser-host/workflow-broker.test.mjs b/browser-host/workflow-broker.test.mjs index 01c6b82282..7ee7c72337 100644 --- a/browser-host/workflow-broker.test.mjs +++ b/browser-host/workflow-broker.test.mjs @@ -228,8 +228,8 @@ it("real broker scoped history signs exact GET path/cursor and captured principa const other = await connectBrokerTransport(h.base, undefined, "secondary"); expect(h.calls).toHaveLength(0); expect(first.writer.kinds).toEqual([ - 30315, 30030, 7, 9, 40003, 42000, 9000, 9001, 30078, 30175, 30177, 30178, - 40100, 1984, 45010, 30620, 46020, 5, + 30315, 30030, 7, 9, 40003, 42000, 42110, 42111, 42112, 42113, 9000, 9001, + 30078, 30175, 30177, 30178, 40100, 1984, 45010, 30620, 46020, 5, ]); await first.workflows.runs(id, cursor, signal()); await other.workflows.runs(id, undefined, signal()); @@ -396,8 +396,8 @@ it("existing backend signs only canonical workflow sign/publish with exact own e const t = await connectBrokerTransport(h.base); live = await openBrokerSocket(t); expect(t.writer.kinds).toEqual([ - 30315, 30030, 7, 9, 40003, 42000, 9000, 9001, 30078, 30175, 30177, 30178, - 40100, 1984, 45010, 30620, 46020, 5, + 30315, 30030, 7, 9, 40003, 42000, 42110, 42111, 42112, 42113, 9000, 9001, + 30078, 30175, 30177, 30178, 40100, 1984, 45010, 30620, 46020, 5, ]); for (const input of [ template(), diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index 20299a5ff7..cca3cdd116 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -390,6 +390,10 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> { if !valid_member_command(event) { return Err("Invalid member change".into()); } + } else if matches!(event.kind, 42110..=42113) { + if !valid_import_record(event) { + return Err("Malformed conversation import record".into()); + } } else if !matches!( event.kind, 0 | 7 | 9 | 1984 | 9000 | 9001 | 20001 | 30030 | 30177 | 30315 | 40003 | 42000 | 45010 @@ -399,6 +403,32 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> { Ok(()) } +/** Match the broker's import record shape (`validImportRecordTemplate` in + * `browser-host/relay-broker.mjs`); the relay decides consent and authority. */ +fn valid_import_record(event: &EventTemplate) -> bool { + if event.content.len() > 16 * 1024 + || !event.tags.iter().all(|tag| tag.len() >= 2) + || event + .tags + .iter() + .filter(|tag| tag[0] == "h" && !tag[1].is_empty()) + .count() + != 1 + || serde_json::from_str::(&event.content) + .ok() + .and_then(|body| body.get("v").and_then(serde_json::Value::as_u64)) + != Some(1) + { + return false; + } + let references: Vec<_> = event.tags.iter().filter(|tag| tag[0] == "e").collect(); + if event.kind == 42110 { + references.is_empty() + } else { + matches!(references.as_slice(), [tag] if hex_key(&tag[1])) + } +} + /** Match the broker's NIP-43 member command shape (`memberCommand` in * `src/features/communities/admin-protocol.ts`); the relay decides authority. */ fn valid_member_command(event: &EventTemplate) -> bool { diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index 5a1d2c429a..25427af85a 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -152,6 +152,49 @@ fn agent_presence_signs_only_a_status_and_agent_keys() { } } +#[test] +fn import_records_sign_only_the_broker_shape() { + let record = |kind: u16, content: &str, tags: &[&[&str]]| EventTemplate { + kind, + created_at: 1, + content: content.into(), + tags: tags + .iter() + .map(|tag| tag.iter().map(|value| value.to_string()).collect()) + .collect(), + }; + let proposal = "a".repeat(64); + let h: &[&str] = &["h", "channel"]; + let e: &[&str] = &["e", &proposal]; + let body = r#"{"v":1}"#; + for accepted in [ + record(42110, body, &[h, &["p", &proposal]]), + record(42111, body, &[h, e]), + record(42112, body, &[h, e]), + record(42113, body, &[h, e]), + ] { + assert!(validate_event("https://relay.test", &accepted).is_ok()); + } + let upper = "A".repeat(64); + let large = format!(r#"{{"v":1,"pad":"{}"}}"#, "x".repeat(16 * 1024)); + for rejected in [ + record(42110, body, &[h, e]), + record(42111, body, &[h]), + record(42111, body, &[h, e, e]), + record(42111, body, &[h, &["e", &upper]]), + record(42111, body, &[e]), + record(42111, body, &[h, h, e]), + record(42111, body, &[&["h", ""], e]), + record(42111, body, &[h, e, &["p"]]), + record(42111, r#"{"v":2}"#, &[h, e]), + record(42111, "[1]", &[h, e]), + record(42111, "not json", &[h, e]), + record(42111, &large, &[h, e]), + ] { + assert!(validate_event("https://relay.test", &rejected).is_err()); + } +} + #[test] fn member_commands_sign_only_the_broker_shape() { let command = |kind: u16, content: &str, tags: &[&[&str]]| EventTemplate { diff --git a/src/features/relay/import-writes.ts b/src/features/relay/import-writes.ts new file mode 100644 index 0000000000..3526fa0a3d --- /dev/null +++ b/src/features/relay/import-writes.ts @@ -0,0 +1,38 @@ +import type { EventTemplate } from "nostr-tools"; +import type { ExplicitTimestampInput, LocalEvents } from "./outbox"; + +/** Host-only conversation import writes. Plugins see the session object but + * cannot reach this module, so these capabilities stay with the host service + * that shows the confirmation dialogs. */ +export type ImportWriter = Readonly<{ + /** Imported history at its original time; see `sendAt` in `createOutbox`. */ + sendAt(input: ExplicitTimestampInput): string; + /** Proposal, consent, withdrawal and completion records. */ + sendRecord(input: Pick): string; + /** Retries an import entry; the plugin-visible retry refuses them. */ + retry(id: string): void; + /** Removes an entry from the journal, for refused or abandoned imports. */ + dismiss(id: string): Promise; + /** Raw journal, including confirmed events, for delivery tracking. */ + local: LocalEvents; +}>; + +const writers = new WeakMap(); + +export function registerImportWriter(session: object, writer: ImportWriter) { + if (writers.has(session)) + throw new Error("This session already has an import writer."); + writers.set(session, { writer }); +} + +/** The session's writer, bound to the first claimant; any other claimant gets + * nothing, so a second import service cannot sign through this session. */ +export function claimImportWriter( + session: object, + claimant: object, +): ImportWriter | undefined { + const entry = writers.get(session); + if (!entry) return; + entry.owner ??= claimant; + return entry.owner === claimant ? entry.writer : undefined; +} diff --git a/src/features/relay/live.ts b/src/features/relay/live.ts index d70b043019..9419078af0 100644 --- a/src/features/relay/live.ts +++ b/src/features/relay/live.ts @@ -288,7 +288,8 @@ type Route = { }; export const CHANNEL_KINDS = [ 9, 40002, 40008, 45001, 45003, 40099, 40100, 40003, 5, 9005, 7, 39000, 39002, - 39005, 20002, 45010, 48100, 48101, 48102, 48103, + 39005, 20002, 45010, 48100, 48101, 48102, 48103, 42110, 42111, 42112, 42113, + 30623, ]; /** The browser socket and native header-capable facade share only frame transport. */ export interface LiveSocket { diff --git a/src/features/relay/mentions.test.ts b/src/features/relay/mentions.test.ts index aecac712d9..b656a3a090 100644 --- a/src/features/relay/mentions.test.ts +++ b/src/features/relay/mentions.test.ts @@ -2,6 +2,7 @@ import { assert, afterEach, expect, it, vi } from "vitest"; import type { EventTemplate } from "nostr-tools"; import type { RelayEvent } from "./events"; import { createRelaySession } from "./session"; +import { claimImportWriter } from "./import-writes"; import { mentionConformance } from "../../bundled/mentions/mention-rules.conformance"; import { flush, @@ -31,6 +32,7 @@ function setup(soloMode = false) { }); let currentRoster: RelayEvent | undefined; let replicaRoster: RelayEvent | undefined; + const strongRosterReads = { count: 0 }; const profileEvents: RelayEvent[] = []; const owner = createRelaySession( { @@ -40,7 +42,8 @@ function setup(soloMode = false) { filters[0]?.authors?.[0] === relay.pubkey && filters[0]?.kinds?.[0] === 39002 && filters[0]?.limit === 1 - ) + ) { + if (filters[0]?.consistency === "strong") strongRosterReads.count++; return Promise.resolve( replicaRoster && filters[0]?.consistency !== "strong" ? [replicaRoster] @@ -48,6 +51,7 @@ function setup(soloMode = false) { ? [currentRoster] : [], ); + } if ( soloMode && filters.every((filter) => filter.kinds?.every((kind) => kind === 0)) @@ -105,6 +109,7 @@ function setup(soloMode = false) { ...wire, ...owner, members, + strongRosterReads, lagReplica: () => { replicaRoster = currentRoster; }, @@ -155,6 +160,39 @@ it.each([false, true])( expect(h.session.outbox?.snapshot()[0]?.delivery).toBe("accepted"); }, ); +it("checks mentions in imported history against the current roster before signing and publishing", async () => { + const h = setup(); + await h.members([viewer.pubkey, honey.pubkey]); + const writer = claimImportWriter(h.session, {}); + assert.exists(writer); + await h.session.outbox?.ready(); + const imported = (key: string, ref: string) => ({ + kind: 9 as const, + created_at: 1_690_000_000, + content: `[@Someone](nostr:${key}) archived`, + tags: [ + ["h", "c"], + ["p", key], + ["import", "1".repeat(64)], + ["source", "slack", ref], + ], + }); + const reads = h.strongRosterReads.count; + const id = writer.sendAt(imported(honey.pubkey, "1")); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledOnce()); + const event = h.publish.mock.calls[0]?.[0]; + expect(event?.id).toBe(id); + expect(event?.created_at).toBe(1_690_000_000); + expect(event?.tags).toContainEqual(["p", honey.pubkey]); + expect(h.strongRosterReads.count).toBeGreaterThan(reads); + const refused = writer.sendAt(imported(namesake.pubkey, "2")); + await vi.waitFor(() => + expect( + h.session.outbox?.snapshot().find((item) => item.event.id === refused), + ).toMatchObject({ delivery: "failed" }), + ); + expect(h.publish).toHaveBeenCalledOnce(); +}); it("mentions a just-added member despite an older replica roster", async () => { const h = setup(); await h.members([viewer.pubkey]); diff --git a/src/features/relay/native.test.ts b/src/features/relay/native.test.ts index 3130ee6ee4..dc2edb3c93 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -224,6 +224,85 @@ it("reads back expired delivery with strong consistency without re-signing or pu vi.mocked(invoke).mock.calls.some(([command]) => command === "relay_sign"), ).toBe(false); }); +it("publishes imported history on its first attempt without a read-back, and reads back only an unsettled retry", async () => { + const transport = await connectNativeTransport(community); + assert.exists(transport.writer); + const writer = transport.writer; + const event = signed(viewer, { + kind: 9, + created_at: 1_600_000_000, + content: "archived message", + tags: [ + ["h", "channel"], + ["import", "1".repeat(64)], + ["source", "slack", "1"], + ], + }); + const paths = async (run: () => Promise) => { + requests.length = 0; + await run().catch(() => {}); + return requests.filter((r) => r.path !== "/").map((r) => r.path); + }; + const publish = () => writer.publish(event, new AbortController().signal); + respond = () => ({ status: 503, body: { error: "offline" } }); + expect(await paths(publish)).toEqual(["/events"]); + respond = (request) => + request.path === "/query" + ? { body: [event] } + : { body: { accepted: true, event_id: event.id } }; + expect(await paths(publish)).toEqual(["/query"]); + // Confirmed, so the id is forgotten and a new attempt is a first attempt. + expect(await paths(publish)).toEqual(["/events"]); + + respond = () => ({ + body: { accepted: false, event_id: event.id, message: "invalid: no" }, + }); + expect(await paths(publish)).toEqual(["/events"]); + respond = () => ({ body: { accepted: true, event_id: event.id } }); + // A refusal is terminal too: nothing was stored to read back. + expect(await paths(publish)).toEqual(["/events"]); + + respond = () => ({ status: 503, body: { error: "offline" } }); + for (let i = 0; i <= 4096; i++) + await writer + .publish( + { ...event, id: i.toString(16).padStart(64, "0") }, + new AbortController().signal, + ) + .catch(() => {}); + respond = (request) => + request.path === "/query" + ? { body: [] } + : { body: { accepted: true, event_id: event.id } }; + // The oldest unsettled id was evicted; the newest still reads back. + expect( + await paths(() => + writer.publish( + { ...event, id: "0".repeat(64) }, + new AbortController().signal, + ), + ), + ).toEqual(["/events"]); + expect( + await paths(() => + writer.publish( + { ...event, id: (4096).toString(16).padStart(64, "0") }, + new AbortController().signal, + ), + ), + ).toEqual(["/query", "/events"]); +}); + +it("advertises conversation import only when the relay lists NIP-CI", async () => { + expect((await connectNativeTransport(community)).conversationImport).toBe( + undefined, + ); + discovery = { supported_extensions: ["nip-ci"] }; + expect((await connectNativeTransport(community)).conversationImport).toBe( + true, + ); +}); + it("publishes config artifacts straight to the relay, re-sending identical bytes and keeping typed refusals", async () => { const transport = await connectNativeTransport(community); assert.exists(transport.configArtifacts); diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index e509ae7a4e..39b5e551a3 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -1,3 +1,4 @@ +import { isImportedEvent } from "../conversation-import/protocol"; import { verifiedProfileAuthority, verifiedProfileDiscovery, @@ -95,6 +96,10 @@ export const nativeWriteKinds = [ 40003, 40100, 42000, + 42110, + 42111, + 42112, + 42113, 45010, ...WORKFLOW_KINDS, ] as const; @@ -316,6 +321,9 @@ export function nativeRelaySigner(community: string): Signer { }; } +/** Imported events whose next attempt reads back first. */ +const ATTEMPTED_IMPORTS_MAX = 4096; + export const NOT_A_COMMUNITY_ERROR = "That URL didn't look like a Buzz community. Enter a community URL like wss://communities.buzz.xyz."; @@ -354,6 +362,9 @@ export async function connectNativeTransport( const searchSort = Array.isArray(info.supported_extensions) && info.supported_extensions.includes("buzz-search-sort"); + const conversationImport = + Array.isArray(info.supported_extensions) && + info.supported_extensions.includes("nip-ci"); const artifacts = info.artifacts as | { sync?: { version?: unknown } } | undefined; @@ -366,6 +377,7 @@ export async function connectNativeTransport( ); signal?.throwIfAborted(); const writer = transport.writer; + const attemptedImports = new Set(); const readCommunity = readSnapshotCommunity(info.read_state_snapshot); if (!writer) throw new Error("Native relay writer is unavailable"); const commandWriter = ( @@ -412,6 +424,44 @@ export async function connectNativeTransport( ); }, }); + type Publish = NonNullable["publish"]; + async function publishChecked( + event: Parameters[0], + signal: Parameters[1], + imported: boolean, + confirm: boolean, + ) { + if (!writer) throw new Error("Native relay writer is unavailable"); + // The relay rejects old events before deduplication. An explicit retry + // can confirm the original ID, but must never silently re-date it. + if (confirm && event.created_at < Math.floor(Date.now() / 1000) - 15 * 60) { + const found = await transport.query( + [ + { + kinds: [event.kind], + ids: [event.id], + authors: [event.pubkey], + limit: 1, + consistency: "strong", + }, + ], + signal, + ); + if (found.some((value) => value.id === event.id)) { + attemptedImports.delete(event.id); + return ""; + } + // Imported history keeps its original time by design; the relay + // admits it only under an active consented import session. + if (!imported) + throw new PublishRejected( + "This event is too old to retry and was not found on the relay. Check the conversation before sending it again.", + ); + } + const result = (await writer.publish(event, signal)) ?? ""; + attemptedImports.delete(event.id); + return result; + } // Capabilities describe implemented host operations, not everything this key can sign. return { ...transport, @@ -795,6 +845,7 @@ export async function connectNativeTransport( nativeAttachmentUpload(origin, file, signal, progress), ...(channelIdentity ? { channelIdentity: true as const } : {}), ...(searchSort ? { searchSort: true as const } : {}), + ...(conversationImport ? { conversationImport: true as const } : {}), ...(artifactSync ? { artifactSync: true as const } : {}), verifiedProfiles: verifiedProfileAuthority(info), async readVerifiedProfileAuthority(signal) { @@ -804,27 +855,26 @@ export async function connectNativeTransport( ...writer, kinds: creation ? [...nativeWriteKinds, 9007] : nativeWriteKinds, async publish(event, signal) { - // The relay rejects old events before deduplication. An explicit retry - // can confirm the original ID, but must never silently re-date it. - if (event.created_at < Math.floor(Date.now() / 1000) - 15 * 60) { - const found = await transport.query( - [ - { - kinds: [event.kind], - ids: [event.id], - authors: [event.pubkey], - limit: 1, - consistency: "strong", - }, - ], - signal, - ); - if (found.some((value) => value.id === event.id)) return ""; - throw new PublishRejected( - "This event is too old to retry and was not found on the relay. Check the conversation before sending it again.", - ); + const imported = isImportedEvent(event); + // A first attempt at imported history has nothing to confirm yet. + const confirm = !imported || attemptedImports.has(event.id); + if (imported) { + attemptedImports.delete(event.id); + attemptedImports.add(event.id); + // An evicted id only loses the read-back on retry; the relay + // still deduplicates the republished event. + if (attemptedImports.size > ATTEMPTED_IMPORTS_MAX) + attemptedImports.delete( + attemptedImports.values().next().value as string, + ); + } + try { + return await publishChecked(event, signal, imported, confirm); + } catch (error) { + if (error instanceof PublishRejected) + attemptedImports.delete(event.id); + throw error; } - return (await writer.publish(event, signal)) ?? ""; }, }, }; diff --git a/src/features/relay/outbox-import.test.ts b/src/features/relay/outbox-import.test.ts new file mode 100644 index 0000000000..161a45a968 --- /dev/null +++ b/src/features/relay/outbox-import.test.ts @@ -0,0 +1,317 @@ +import { afterEach, assert, expect, it, vi } from "vitest"; +import { getEventHash } from "nostr-tools"; +import { + PublishRejected, + createOutbox, + type OutboxStorage, + type OutgoingEvent, +} from "./outbox"; +import type { RelayEvent } from "./events"; +import { keypair, signed } from "./testing"; + +const viewer = keypair(); +const channel = "f0".repeat(16); +const proposal = "1".repeat(64); +const owners: ReturnType[] = []; + +function memoryStorage(): OutboxStorage { + let records: readonly OutgoingEvent[] = []; + return { + load: () => structuredClone(records), + save: (next) => { + records = structuredClone(next); + }, + }; +} + +function setup(publish = vi.fn(async (_event: RelayEvent) => {})) { + const sign = vi.fn(async (template: Parameters[1]) => + signed(viewer, template), + ); + const owner = createOutbox(viewer.pubkey, { sign, publish }, memoryStorage()); + owners.push(owner); + return { ...owner, sign, publish }; +} + +afterEach(() => { + for (const owner of owners.splice(0)) owner.dispose(); +}); + +const imported = (created_at = 1_735_732_800) => ({ + kind: 9 as const, + created_at, + tags: [ + ["h", channel], + ["import", proposal], + ["source", "slack", "1735732800.000100"], + ], + content: "Hello from the archive", +}); + +it("publishes an imported event at its original time with a deterministic id and no client tags", async () => { + const h = setup(); + await h.ready; + const input = imported(); + const id = h.sendAt(input); + expect(id).toBe( + getEventHash({ ...input, pubkey: viewer.pubkey, tags: input.tags }), + ); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledOnce()); + const sent = h.publish.mock.calls[0]?.[0]; + assert.exists(sent); + expect(sent.id).toBe(id); + expect(sent.created_at).toBe(1_735_732_800); + expect(sent.tags).toEqual(input.tags); + expect( + sent.tags.some(([name]) => name === "client-id" || name === "ms"), + ).toBe(false); + await vi.waitFor(() => + expect( + h.local.snapshot().find((item) => item.event.id === id)?.delivery, + ).toBe("accepted"), + ); +}); + +it("returns the same id for a resubmitted event without publishing twice", async () => { + let release = () => {}; + const publish = vi.fn( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + const h = setup(publish); + await h.ready; + const first = h.sendAt(imported()); + const second = h.sendAt(imported()); + expect(second).toBe(first); + await vi.waitFor(() => expect(publish).toHaveBeenCalledOnce()); + release(); +}); + +it("refuses imported events without exactly one import tag, with bad times, or of other kinds", async () => { + const h = setup(); + await h.ready; + const base = imported(); + expect(() => + h.sendAt({ + ...base, + tags: base.tags.filter(([name]) => name !== "import"), + }), + ).toThrow("exactly one import tag"); + expect(() => + h.sendAt({ ...base, tags: [...base.tags, ["import", proposal]] }), + ).toThrow("exactly one import tag"); + expect(() => + h.sendAt({ + ...base, + created_at: Math.floor(Date.now() / 1000) + 3600, + }), + ).toThrow("time is invalid"); + expect(() => h.sendAt({ ...base, created_at: -1 })).toThrow( + "time is invalid", + ); + expect(() => h.sendAt({ ...base, kind: 1 as unknown as 9 })).toThrow( + "cannot publish", + ); + expect(() => h.sendAt({ ...base, content: " " })).toThrow("empty"); + expect(h.publish).not.toHaveBeenCalled(); +}); + +it("keeps import records and imported events off the ordinary send path", async () => { + const h = setup(); + await h.ready; + expect(() => + h.outbox.send({ + kind: 9, + content: "x", + tags: [ + ["h", channel], + ["import", proposal], + ], + }), + ).toThrow("only by the host import service"); + for (const kind of [42110, 42111, 42112, 42113]) + expect(() => + h.outbox.send({ kind, content: "{}", tags: [["h", channel]] }), + ).toThrow("only by the host import service"); + expect(() => + h.sendRecord({ kind: 9, content: "x", tags: [["h", channel]] }), + ).toThrow("Not a conversation import record"); + const id = h.sendRecord({ + kind: 42111, + content: '{"v":1}', + tags: [ + ["h", channel], + ["e", proposal], + ], + }); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledOnce()); + expect(h.publish.mock.calls[0]?.[0]?.id).toBe(id); +}); + +it("keeps the relay's refusal text for a rejected import", async () => { + const publish = vi.fn(async () => { + throw new PublishRejected( + "invalid: import event is outside the proposal range", + ); + }); + const h = setup(publish); + await h.ready; + const id = h.sendAt(imported()); + await vi.waitFor(() => + expect( + h.local.snapshot().find((item) => item.event.id === id)?.delivery, + ).toBe("failed"), + ); + const item = h.local.snapshot().find((entry) => entry.event.id === id); + expect(item?.reason ?? item?.error).toBe( + "invalid: import event is outside the proposal range", + ); +}); + +const record = (kind = 42111) => ({ + kind, + content: '{"v":1}', + tags: [ + ["h", channel], + ["e", proposal], + ], +}); + +it("signs import records with exactly their protocol tags", async () => { + const h = setup(); + await h.ready; + const id = h.sendRecord(record()); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledOnce()); + const sent = h.publish.mock.calls[0]?.[0]; + expect(sent?.id).toBe(id); + expect(sent?.tags).toEqual(record().tags); + const proposed = h.sendRecord({ + kind: 42110, + content: '{"v":1}', + tags: [["h", channel]], + }); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledTimes(2)); + expect(h.publish.mock.calls[1]?.[0]?.id).toBe(proposed); + expect(h.publish.mock.calls[1]?.[0]?.tags).toEqual([["h", channel]]); +}); + +it("orders a second record about the same proposal after the first", async () => { + const h = setup(); + await h.ready; + const first = h.sendRecord(record()); + const second = h.sendRecord({ ...record(), content: '{"v":1,"n":2}' }); + const events = h.local.snapshot().map((item) => item.event); + const at = (id: string) => + events.find((event) => event.id === id)?.created_at ?? 0; + expect(at(second)).toBeGreaterThan(at(first)); +}); + +it("lets no send or change listener forge import writes while a record is sent", async () => { + const h = setup(); + await h.ready; + const forged: unknown[] = []; + const attempt = (input: Parameters[0]) => { + try { + forged.push(h.outbox.send(input)); + } catch (error) { + forged.push(error instanceof Error ? error.message : error); + } + }; + const observed = vi.fn(() => { + attempt({ + kind: 9, + content: "forged history", + tags: [ + ["h", channel], + ["import", proposal], + ["source", "slack", "1"], + ], + }); + return undefined; + }); + h.outbox.observeSend(observed); + let fired = false; + h.outbox.subscribe(() => { + if (fired) return; + fired = true; + attempt(record()); + attempt({ kind: 42110, content: '{"v":1}', tags: [["h", channel]] }); + }); + h.sendRecord(record(42113)); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledOnce()); + // A record is not fresh user intent: send observers never see it. + expect(observed).not.toHaveBeenCalled(); + h.outbox.send({ kind: 9, content: "hello", tags: [["h", channel]] }); + expect(observed).toHaveBeenCalledOnce(); + expect(forged).toEqual([ + "Conversation import events are published only by the host import service", + "Conversation import events are published only by the host import service", + "Conversation import events are published only by the host import service", + ]); + await vi.waitFor(() => expect(h.publish).toHaveBeenCalledTimes(2)); + expect( + h.local + .snapshot() + .filter( + (item) => + item.event.kind !== 42113 && + (item.event.kind >= 42110 || + item.event.tags.some(([name]) => name === "import")), + ), + ).toEqual([]); +}); + +it("retries import entries only for the host writer", async () => { + let refuse = true; + const publish = vi.fn(async () => { + if (refuse) throw new PublishRejected("rate-limited: slow down"); + }); + const h = setup(publish); + await h.ready; + const id = h.sendAt(imported()); + const recordId = h.sendRecord(record()); + await vi.waitFor(() => + expect( + h.local + .snapshot() + .filter((item) => item.delivery === "failed") + .map((item) => item.event.id) + .sort(), + ).toEqual([id, recordId].sort()), + ); + expect(() => h.outbox.retry(id)).toThrow("only by the host import service"); + expect(() => h.outbox.retry(recordId)).toThrow( + "only by the host import service", + ); + refuse = false; + h.retryImport(id); + await vi.waitFor(() => + expect( + h.local.snapshot().find((item) => item.event.id === id)?.delivery, + ).toBe("accepted"), + ); +}); + +it("does not count refused import entries toward the outstanding limit", async () => { + const publish = vi.fn(async (event: RelayEvent) => { + if (event.tags.some(([name]) => name === "import")) + throw new PublishRejected("invalid: import event malformed: test"); + await new Promise(() => {}); + }); + const h = setup(publish); + await h.ready; + for (let index = 0; index < 256; index++) + h.sendAt(imported(1_735_732_800 + index)); + await vi.waitFor( + () => + expect( + h.local.snapshot().filter((item) => item.delivery === "failed"), + ).toHaveLength(256), + { timeout: 10_000 }, + ); + expect(() => + h.outbox.send({ kind: 9, content: "still sends", tags: [["h", channel]] }), + ).not.toThrow(); +}); diff --git a/src/features/relay/outbox.ts b/src/features/relay/outbox.ts index a2f2503bc9..9afcae600b 100644 --- a/src/features/relay/outbox.ts +++ b/src/features/relay/outbox.ts @@ -43,6 +43,8 @@ export type OutgoingEvent = Readonly<{ /** The relay refused the last attempt, rather than it failing on this * device, being asked to wait, or going unanswered. */ refused?: true | undefined; + /** The relay's own refusal text for the last attempt, when it sent one. */ + reason?: string | undefined; }>; export interface Outbox { /** Outstanding operations only. Confirmed events live in the session's retained data. */ @@ -74,6 +76,13 @@ type SendObserver = ( signal: AbortSignal, ) => ((pending: readonly EventData[]) => void) | undefined; export type LocalEvents = Pick; +/** A fully specified imported event; see `sendAt` in `createOutbox`. */ +export type ExplicitTimestampInput = Readonly<{ + kind: 9 | 7; + created_at: number; + tags: readonly (readonly string[])[]; + content: string; +}>; export interface OutboxStorage { close?(): void; load(): readonly OutgoingEvent[] | Promise; @@ -98,6 +107,16 @@ export { browserOutboxStorage } from "./outbox-storage"; const abortError = () => new DOMException("Relay session closed", "AbortError"); const MAX_PENDING = 256; const MAX_CONFIRMED = 2048; +const IMPORT_ONLY = + "Conversation import events are published only by the host import service"; + +/** Import records (kinds 42110 to 42113) and imported history. */ +function importEntry(event: Pick) { + return ( + (event.kind >= 42110 && event.kind <= 42113) || + event.tags.some((tag) => tag[0] === "import") + ); +} /** One journal owns pending delivery and bounded confirmed retention. Views receive one change stream. */ export function createOutbox( @@ -146,6 +165,12 @@ export function createOutbox( }; let snapshot: readonly OutgoingEvent[] = Object.freeze([]); let visible: readonly OutgoingEvent[] = snapshot; + // A refused import entry waits only for the import service to dismiss it; + // it never holds back ordinary sends. + const outstanding = () => + snapshot.filter( + (item) => !(item.delivery === "failed" && importEntry(item.event)), + ).length; let finalSnapshot: readonly OutgoingEvent[] | undefined; let finalVisible: readonly OutgoingEvent[] | undefined; const completed = new ByteLru(MAX_CONFIRMED, 8 * 1024 * 1024); @@ -587,6 +612,7 @@ export function createOutbox( !(error instanceof PublishNotSent) ? true : undefined, + reason: error instanceof PublishRejected ? error.reason : undefined, error: awaitsReceipt(latest.event) ? publishing && !(error instanceof PublishRejected) ? "Workflow delivery could not be confirmed; inspect recent activity before submitting another command." @@ -632,12 +658,276 @@ export function createOutbox( pumpDeliveries(); } } + /** Conversation import records (kinds 42110 to 42113), host service only. */ + function sendRecord(input: Pick) { + if (input.kind < 42110 || input.kind > 42113) + throw new Error("Not a conversation import record"); + return sendInternal(input, undefined, undefined, true); + } + function enqueue( + event: EventData, + savedRecovery?: OutboxRecovery, + active?: () => boolean, + ) { + profiling.measure("send.local", event.id, () => { + snapshot = Object.freeze([ + ...snapshot, + Object.freeze({ + event, + delivery: "sending" as const, + ...(savedRecovery ? { recovery: savedRecovery } : {}), + ...(active ? { guarded: true } : {}), + }), + ]); + notify(); + }); + const intent = ready.then(() => { + if (storageError) throw new Error(storageError); + return persist(event.id); + }); + void intent.catch(() => {}); // Delivery reports persistence errors; disposal still saves queued intent. + schedule(event.id, intent); + } + /** Conversation import only: publishes exactly the caller's tags at the + * caller's created_at so every participant derives the same event id. No + * client-id or ms tag, no send clock and no send observers: an imported + * message is history, not fresh intent. */ + function sendAt(input: ExplicitTimestampInput) { + if (closed) throw abortError(); + if (storageError) throw new Error(storageError); + if (!hydrated) + throw new Error("Message history is still loading. Try again."); + if ((input.kind !== 9 && input.kind !== 7) || !outbox.supports(input.kind)) + throw new Error("This relay connection cannot publish that event kind"); + if ( + !Number.isSafeInteger(input.created_at) || + input.created_at < 0 || + input.created_at > Math.floor(Date.now() / 1000) + 900 + ) + throw new Error("Imported event time is invalid"); + if ( + !Array.isArray(input.tags) || + input.tags.some( + (tag) => + !Array.isArray(tag) || + !tag.length || + tag.some((value) => typeof value !== "string"), + ) || + input.tags.filter(([name]) => name === "import").length !== 1 + ) + throw new Error("An imported event needs exactly one import tag"); + if ( + typeof input.content !== "string" || + (input.kind === 9 && !input.content.trim()) || + byteSize({ + kind: input.kind, + content: input.content, + tags: input.tags, + }) > OUTBOX_INPUT_MAX_BYTES + ) + throw new Error("Message is empty or too large"); + const template = { + kind: input.kind, + content: input.content, + pubkey: viewer, + created_at: input.created_at, + tags: input.tags.map((tag) => [...tag]), + }; + const id = getEventHash(template); + // A resumed run may resubmit an event this journal already holds. + if (visible.some((item) => item.event.id === id)) return id; + if (outstanding() >= MAX_PENDING) + throw new Error( + "Too many outstanding operations; resolve or dismiss a pending operation", + ); + enqueue( + Object.freeze({ + ...template, + tags: Object.freeze( + template.tags.map((tag) => Object.freeze(tag)), + ) as unknown as string[][], + id, + }), + ); + return id; + } const subscribe = (set: Set<() => void>, listener: () => void) => { set.add(listener); return () => { set.delete(listener); }; }; + function sendInternal( + { + supersedes, + ...input + }: Pick & { + supersedes?: number; + }, + recovery: OutboxRecovery | undefined, + active: (() => boolean) | undefined, + record: boolean, + ) { + if (active && !active()) + throw new DOMException("Channel addition cancelled", "AbortError"); + if (closed) throw abortError(); + if (storageError) throw new Error(storageError); + // Consent records and imported history are signed only after the + // host's own confirmation, never through the plugin-visible outbox. + if (!record && importEntry(input)) throw new Error(IMPORT_ONLY); + const savedRecovery = recoveryValue(recovery); + if ( + savedRecovery && + (!hydrated || + snapshot.some((item) => item.recovery?.key === savedRecovery.key)) + ) + throw new Error("Recover the earlier message before sending another"); + if ( + !Number.isInteger(input.kind) || + input.kind < 0 || + input.kind > 65535 || + !outbox.supports(input.kind) + ) + throw new Error("This relay connection cannot publish that event kind"); + const catalog = isCatalogKind(input.kind); + if ( + (input.kind === 9 && !input.content.trim()) || + // NIP-AP admits larger public definitions than ordinary input. + (catalog + ? bytes(input.content) > MAX_CONTENT_BYTES || + byteSize(input) > MAX_EVENT_BYTES + : byteSize(input) > OUTBOX_INPUT_MAX_BYTES) + ) + throw new Error("Message is empty or too large"); + if (outstanding() >= MAX_PENDING) + throw new Error( + "Too many outstanding operations; resolve or dismiss a pending operation", + ); + // Rendered messages carry send order within their second; the optimistic + // row and the signed event share this exact ms and created_at. + // Import records carry exactly their protocol tags, so no ms tag. + const channelId = + !record && channelRowKind(input.kind) + ? input.tags.find(([name]) => name === "h")?.[1] + : undefined; + const ms = channelId ? clock.next(channelId) : Date.now(); + let createdAt = Math.floor(ms / 1000); + if (input.kind === 40003) { + if (!hydrated) + throw new Error("Message history is still loading. Try again."); + const target = input.tags.find(([name]) => name === "e")?.[1]; + const channel = input.tags.find(([name]) => name === "h")?.[1]; + // Edits use second precision on every client. Preserve retained local + // submission order without changing the protocol's event-ID tie-break. + for (const { event } of visible) { + if ( + target && + channel && + event.kind === 40003 && + event.pubkey === viewer && + event.tags.some(([name, id]) => name === "e" && id === target) && + event.tags.some(([name, id]) => name === "h" && id === channel) + ) + createdAt = Math.max(createdAt, event.created_at + 1); + } + // Stay well inside the signer's 15-minute clock-skew allowance. + if (createdAt > Math.floor(ms / 1000) + 60) + throw new Error( + "Edits are arriving too quickly or your clock changed. Wait a moment and try again.", + ); + } + if (catalog) { + // NIP-AP: max(now, head + 1) over the observed relay head and this + // device's retained writes, so a replacement can never lose or tie. + if (supersedes !== undefined) + createdAt = Math.max(createdAt, supersedes + 1); + const d = input.tags.find(([name]) => name === "d")?.[1]; + for (const { event } of visible) + if ( + event.kind === input.kind && + event.pubkey === viewer && + event.tags.some(([name, value]) => name === "d" && value === d) + ) + createdAt = Math.max(createdAt, event.created_at + 1); + if (createdAt > Math.floor(ms / 1000) + 60) + throw new Error( + "Sharing is changing too quickly or your clock changed. Wait a moment and try again.", + ); + } + if (record) { + // A later record about the same proposal must not tie an earlier one. + const target = input.tags.find(([name]) => name === "e")?.[1]; + for (const { event } of visible) + if ( + event.kind === input.kind && + event.pubkey === viewer && + target && + event.tags.some(([name, id]) => name === "e" && id === target) + ) + createdAt = Math.max(createdAt, event.created_at + 1); + } + const template = { + ...input, + pubkey: viewer, + created_at: createdAt, + tags: record + ? input.tags.map((tag) => [...tag]) + : [ + ...input.tags.map((tag) => [...tag]), + ["client-id", crypto.randomUUID()], + ...(channelId ? [["ms", String(ms % 1000)]] : []), + ], + }; + const event = Object.freeze({ + ...template, + tags: Object.freeze( + template.tags.map((tag) => Object.freeze(tag)), + ) as unknown as string[][], + id: getEventHash(template), + }); + if (active) admissionGates.set(event.id, active); + if (!record) captureSend(event); + enqueue(event, savedRecovery, active); + return event.id; + } + function retryInternal( + id: string, + active: (() => boolean) | undefined, + host: boolean, + ) { + const item = find(id); + if (item && !host && importEntry(item.event)) throw new Error(IMPORT_ONLY); + if (item?.guarded && (active ?? admissionGates.get(id))?.() !== true) + throw new DOMException("Channel addition cancelled", "AbortError"); + // Workflow recovery is inspect/dismiss only, including restored intents. + if ( + !closed && + item && + !(item.event.kind === 9000 && item.acknowledged) && + !isWorkflowOperation(item.event) && + !attempts.has(id) && + !dismissing.has(id) + ) { + // A profile retry can reuse an older, unguarded saved invitation. + // Promote that intent before scheduling so signing and publication honor + // the renewed caller policy, including after the next hydration. + if (active) admissionGates.set(id, active); + if ( + !importEntry(item.event) && + (item.delivery === "failed" || item.delivery === "unknown") + ) + captureSend(item.event); + replace({ + ...item, + ...(active ? { guarded: true } : {}), + delivery: "sending", + error: undefined, + refused: undefined, + reason: undefined, + }); + schedule(id, undefined, item.delivery); + } + } const outbox: Outbox = Object.freeze({ snapshot: () => finalSnapshot ?? snapshot, subscribe: (listener: () => void) => subscribe(listeners, listener), @@ -673,7 +963,7 @@ export function createOutbox( ) ) throw new Error("Recover the earlier message before sending another"); - if (!find(id) && snapshot.length >= MAX_PENDING) + if (!find(id) && outstanding() >= MAX_PENDING) throw new Error( "Too many outstanding operations; resolve a pending operation", ); @@ -705,163 +995,16 @@ export function createOutbox( await persist(id, "acknowledge"); }, send( - { - supersedes, - ...input - }: Pick & { + input: Pick & { supersedes?: number; }, recovery?: OutboxRecovery, active?: () => boolean, ) { - if (active && !active()) - throw new DOMException("Channel addition cancelled", "AbortError"); - if (closed) throw abortError(); - if (storageError) throw new Error(storageError); - const savedRecovery = recoveryValue(recovery); - if ( - savedRecovery && - (!hydrated || - snapshot.some((item) => item.recovery?.key === savedRecovery.key)) - ) - throw new Error("Recover the earlier message before sending another"); - if ( - !Number.isInteger(input.kind) || - input.kind < 0 || - input.kind > 65535 || - !outbox.supports(input.kind) - ) - throw new Error("This relay connection cannot publish that event kind"); - const catalog = isCatalogKind(input.kind); - if ( - (input.kind === 9 && !input.content.trim()) || - // NIP-AP admits larger public definitions than ordinary input. - (catalog - ? bytes(input.content) > MAX_CONTENT_BYTES || - byteSize(input) > MAX_EVENT_BYTES - : byteSize(input) > OUTBOX_INPUT_MAX_BYTES) - ) - throw new Error("Message is empty or too large"); - if (snapshot.length >= MAX_PENDING) - throw new Error( - "Too many outstanding operations; resolve or dismiss a pending operation", - ); - // Rendered messages carry send order within their second; the optimistic - // row and the signed event share this exact ms and created_at. - const channelId = channelRowKind(input.kind) - ? input.tags.find(([name]) => name === "h")?.[1] - : undefined; - const ms = channelId ? clock.next(channelId) : Date.now(); - let createdAt = Math.floor(ms / 1000); - if (input.kind === 40003) { - if (!hydrated) - throw new Error("Message history is still loading. Try again."); - const target = input.tags.find(([name]) => name === "e")?.[1]; - const channel = input.tags.find(([name]) => name === "h")?.[1]; - // Edits use second precision on every client. Preserve retained local - // submission order without changing the protocol's event-ID tie-break. - for (const { event } of visible) { - if ( - target && - channel && - event.kind === 40003 && - event.pubkey === viewer && - event.tags.some(([name, id]) => name === "e" && id === target) && - event.tags.some(([name, id]) => name === "h" && id === channel) - ) - createdAt = Math.max(createdAt, event.created_at + 1); - } - // Stay well inside the signer's 15-minute clock-skew allowance. - if (createdAt > Math.floor(ms / 1000) + 60) - throw new Error( - "Edits are arriving too quickly or your clock changed. Wait a moment and try again.", - ); - } - if (catalog) { - // NIP-AP: max(now, head + 1) over the observed relay head and this - // device's retained writes, so a replacement can never lose or tie. - if (supersedes !== undefined) - createdAt = Math.max(createdAt, supersedes + 1); - const d = input.tags.find(([name]) => name === "d")?.[1]; - for (const { event } of visible) - if ( - event.kind === input.kind && - event.pubkey === viewer && - event.tags.some(([name, value]) => name === "d" && value === d) - ) - createdAt = Math.max(createdAt, event.created_at + 1); - if (createdAt > Math.floor(ms / 1000) + 60) - throw new Error( - "Sharing is changing too quickly or your clock changed. Wait a moment and try again.", - ); - } - const template = { - ...input, - pubkey: viewer, - created_at: createdAt, - tags: [ - ...input.tags.map((tag) => [...tag]), - ["client-id", crypto.randomUUID()], - ...(channelId ? [["ms", String(ms % 1000)]] : []), - ], - }; - const event = Object.freeze({ - ...template, - tags: Object.freeze( - template.tags.map((tag) => Object.freeze(tag)), - ) as unknown as string[][], - id: getEventHash(template), - }); - if (active) admissionGates.set(event.id, active); - captureSend(event); - profiling.measure("send.local", event.id, () => { - snapshot = Object.freeze([ - ...snapshot, - Object.freeze({ - event, - delivery: "sending" as const, - ...(savedRecovery ? { recovery: savedRecovery } : {}), - ...(active ? { guarded: true } : {}), - }), - ]); - notify(); - }); - const intent = ready.then(() => { - if (storageError) throw new Error(storageError); - return persist(event.id); - }); - void intent.catch(() => {}); // Delivery reports persistence errors; disposal still saves queued intent. - schedule(event.id, intent); - return event.id; + return sendInternal(input, recovery, active, false); }, retry(id: string, active?: () => boolean) { - const item = find(id); - if (item?.guarded && (active ?? admissionGates.get(id))?.() !== true) - throw new DOMException("Channel addition cancelled", "AbortError"); - // Workflow recovery is inspect/dismiss only, including restored intents. - if ( - !closed && - item && - !(item.event.kind === 9000 && item.acknowledged) && - !isWorkflowOperation(item.event) && - !attempts.has(id) && - !dismissing.has(id) - ) { - // A profile retry can reuse an older, unguarded saved invitation. - // Promote that intent before scheduling so signing and publication honor - // the renewed caller policy, including after the next hydration. - if (active) admissionGates.set(id, active); - if (item.delivery === "failed" || item.delivery === "unknown") - captureSend(item.event); - replace({ - ...item, - ...(active ? { guarded: true } : {}), - delivery: "sending", - error: undefined, - refused: undefined, - }); - schedule(id, undefined, item.delivery); - } + retryInternal(id, active, false); }, observeDismiss(listener: (item: OutgoingEvent) => void) { dismissListeners.add(listener); @@ -893,6 +1036,10 @@ export function createOutbox( }); return { outbox, + sendAt, + sendRecord, + /** Host import service retry; the public retry refuses import entries. */ + retryImport: (id: string) => retryInternal(id, undefined, true), local: Object.freeze({ snapshot: () => finalVisible ?? visible, subscribe: (listener: () => void) => subscribe(localListeners, listener), diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index c7901722ba..bc55ac08ba 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -63,6 +63,8 @@ import { createUnread } from "./unread"; import type { SnapshotRead } from "../agents/agent-config-artifacts"; import { createInboxFeed } from "./inbox-feed"; +import { registerImportWriter } from "./import-writes"; +import { isImportedEvent } from "../conversation-import/protocol"; import type { IncomingListener, IncomingMessage, @@ -307,7 +309,8 @@ export function createRelaySession( const id = event.tags.find(([name]) => name === "h")?.[1]; if (!id) return; const ready = channelWrites.starting(id); - if (ready && event.kind === 9) hearStarting(event, id); + if (ready && event.kind === 9 && !isImportedEvent(event)) + hearStarting(event, id); return ready; }, preparePublish: async (event, signal) => { @@ -852,6 +855,7 @@ export function createRelaySession( } /** The relay's ACK or read-back verifies an own send before any live echo. */ function acceptOwnActivity(event: RelayEvent) { + if (isImportedEvent(event)) return; const channelId = event.tags.find(([name]) => name === "h")?.[1]; if (!cacheClearing && channelId && canReadRemote(channelId)) channelActivity.accept([event]); @@ -2647,6 +2651,8 @@ export function createRelaySession( }, /** Whether read() search filters may ask for `search_sort: "newest"`. */ searchSort: transport?.searchSort === true, + /** The relay advertises NIP-CI consented conversation import. */ + conversationImport: transport?.conversationImport === true, /** NIP-AR sync: an exact, kept-current set of current artifacts for a * filter that names its channels with `#h`. Status `unsupported` means * this relay has no sync; use read() with `artifact: "current"` instead. @@ -3261,7 +3267,12 @@ export function createRelaySession( const delivered = new Set(); const incoming: readonly IncomingMessage[] = Object.freeze( visible.flatMap((event) => { - if (!candidates.has(event.id) || delivered.has(event.id)) return []; + if ( + !candidates.has(event.id) || + delivered.has(event.id) || + isImportedEvent(event) + ) + return []; delivered.add(event.id); const body = event.kind === 40002 ? objectBody(event.content) : undefined; @@ -3442,6 +3453,14 @@ export function createRelaySession( const stopInterests = channels.queries.subscribeList(updateInterests); updateInterests(); refreshChannelActivity(); + if (writes) + registerImportWriter(session, { + sendAt: writes.sendAt, + sendRecord: writes.sendRecord, + retry: writes.retryImport, + dismiss: writes.outbox.dismiss, + local: writes.local, + }); return { session, diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index b9c231369b..f369dd41a8 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -133,6 +133,9 @@ export interface ReadTransport { /** The relay advertises `buzz-search-sort`: bridge search accepts * `search_sort: "newest"`. Older relays silently rank by relevance. */ readonly searchSort?: true; + /** The relay advertises NIP-CI (`nip-ci` in NIP-11 `supported_extensions`): + * it admits consented conversation imports. */ + readonly conversationImport?: true; /** The relay advertises NIP-AR sync (`artifacts.sync.version` 1 in NIP-11): * a REQ with `"artifact": "current"` streams a complete set, then live heads. */ readonly artifactSync?: true; @@ -471,6 +474,7 @@ export async function connectBrokerTransport( channelKit?: boolean; channelIdentity?: boolean; searchSort?: boolean; + conversationImport?: boolean; artifactSync?: boolean; sidebarPreferenceWrites?: boolean; sidebarSectionRemoval?: boolean; @@ -801,6 +805,9 @@ export async function connectBrokerTransport( ? { channelIdentity: true as const } : {}), ...(session.searchSort === true ? { searchSort: true as const } : {}), + ...(session.conversationImport === true + ? { conversationImport: true as const } + : {}), ...(session.artifactSync === true ? { artifactSync: true as const } : {}), ...(session.channelKit ? { From 1954bc548fa218df0d62ea2c878aca821269f7a1 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:41:06 -0600 Subject: [PATCH 3/6] feat(relay): keep imported history out of unread, inbox and activity Imported messages and reactions never count as unread evidence, inbox mentions, channel activity or agent triggers. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- src/features/agents/service.ts | 4 ++- src/features/relay/channel-activity.test.ts | 29 +++++++++++++++++++++ src/features/relay/channel-activity.ts | 8 +++++- src/features/relay/inbox-feed.test.ts | 24 +++++++++++++++++ src/features/relay/inbox-feed.ts | 6 ++++- src/features/relay/unread.test.ts | 20 ++++++++++++++ src/features/relay/unread.ts | 2 ++ 7 files changed, 90 insertions(+), 3 deletions(-) diff --git a/src/features/agents/service.ts b/src/features/agents/service.ts index eb38f4c99d..0f108f441a 100644 --- a/src/features/agents/service.ts +++ b/src/features/agents/service.ts @@ -1,3 +1,4 @@ +import { withoutImported } from "../conversation-import/protocol"; import type {} from "../navigation/service"; import { appClient, readFile } from "../../buzz-mcp/app-client"; import { respond } from "../../buzz-mcp/rpc"; @@ -5152,7 +5153,8 @@ export class AgentsService extends Service implements Agents { if (connected) Object.assign(connection, { epoch: 1, since }); const heard = (agent: Agent) => originOf(agent.relay) === origin; const stopEvents = session.subscribeLive( - (batch) => this.runners.dispatch(batch, heard, since), + // Imported history never triggers agents. + (batch) => this.runners.dispatch(withoutImported(batch), heard, since), { replay: true }, ); const stopStatus = session.live.subscribe(() => { diff --git a/src/features/relay/channel-activity.test.ts b/src/features/relay/channel-activity.test.ts index ec2f3826a1..81db0a3f4f 100644 --- a/src/features/relay/channel-activity.test.ts +++ b/src/features/relay/channel-activity.test.ts @@ -59,6 +59,35 @@ it("reads authoritative activity in 128-channel batches across message and forum expect(activity.status()).toBe("ready"); }); +it("never bumps a channel for imported history, read or live", async () => { + const peer = keypair(); + const wire = deferredReader(); + const activity = createChannelActivity(wire.read); + const imported = (created_at: number) => + signed(peer, { + kind: 9, + created_at, + content: "archived", + tags: [ + ["h", "room"], + ["import", "1".repeat(64)], + ["source", "slack", String(created_at)], + ], + }); + const refresh = activity.refresh(["room"]); + await flush(); + take(wire.pending).resolve([ + message(peer, "room", "live", 100), + imported(200), + ]); + await refresh; + expect(activity.last("room")).toBe(100); + activity.accept([imported(300)]); + expect(activity.last("room")).toBe(100); + activity.accept([message(peer, "room", "later", 150)]); + expect(activity.last("room")).toBe(150); +}); + it("keeps the last good projection on failure and never rolls back newer live activity", async () => { const peer = keypair(); const wire = deferredReader(); diff --git a/src/features/relay/channel-activity.ts b/src/features/relay/channel-activity.ts index 2dc9ffd59e..8be20ca5a4 100644 --- a/src/features/relay/channel-activity.ts +++ b/src/features/relay/channel-activity.ts @@ -1,3 +1,4 @@ +import { isImportedEvent } from "../conversation-import/protocol"; import type { RelayEvent } from "./events"; export const CHANNEL_ACTIVITY_KINDS = [9, 40002, 40008, 45001, 45003] as const; @@ -35,7 +36,11 @@ export function createChannelActivity( if (closed) return; let changed = false; for (const event of events) { - if (!CHANNEL_ACTIVITY_KINDS.includes(event.kind as never)) continue; + if ( + !CHANNEL_ACTIVITY_KINDS.includes(event.kind as never) || + isImportedEvent(event) + ) + continue; const channelId = channelOf(event); if (!channelId || event.created_at <= (values.get(channelId) ?? -1)) continue; @@ -98,6 +103,7 @@ export function createChannelActivity( channelId && batch.includes(channelId) && CHANNEL_ACTIVITY_KINDS.includes(event.kind as never) && + !isImportedEvent(event) && event.created_at > (refreshed.get(channelId) ?? -1) ) refreshed.set(channelId, event.created_at); diff --git a/src/features/relay/inbox-feed.test.ts b/src/features/relay/inbox-feed.test.ts index 880cad7b54..88e53af6b3 100644 --- a/src/features/relay/inbox-feed.test.ts +++ b/src/features/relay/inbox-feed.test.ts @@ -106,6 +106,30 @@ it("reads addressed history independently of the retained unread window, never a { kinds: [40002, 9], "#p": [h.viewer.pubkey], limit: 50 }, ]); }); +it("keeps imported history out of the inbox, from a read or live", async () => { + const h = setup(); + h.admit([h.viewer.pubkey, h.alice.pubkey]); + const imported = (content: string, at: number) => + message(h.alice, "room", content, at, [ + ["p", h.viewer.pubkey], + ["import", "1".repeat(64)], + ["source", "slack", String(at)], + ]); + const plain = message(h.alice, "room", "live mention", 21, [ + ["p", h.viewer.pubkey], + ]); + const work = h.session.inboxFeed.ensure(); + const mentions = await take(h, 9); + mentions.resolve([imported("archived mention", 20), plain]); + await work; + expect(h.session.unread.inbox().items.map((item) => item.messageId)).toEqual([ + plain.id, + ]); + h.live.receive([imported("archived live", 22)]); + expect(h.session.unread.inbox().items.map((item) => item.messageId)).toEqual([ + plain.id, + ]); +}); it("reconciles live addressed updates and drops membership-revoked history before listeners", async () => { const h = setup(); h.admit([h.viewer.pubkey, h.alice.pubkey]); diff --git a/src/features/relay/inbox-feed.ts b/src/features/relay/inbox-feed.ts index c20ae2e03c..4e26dcbdcd 100644 --- a/src/features/relay/inbox-feed.ts +++ b/src/features/relay/inbox-feed.ts @@ -1,3 +1,4 @@ +import { isImportedEvent } from "../conversation-import/protocol"; import { byteSize } from "./budget"; import type { ChannelQueries } from "./contracts"; import type { RelayEvent, ReadFilter } from "./events"; @@ -56,7 +57,10 @@ export function createInboxFeed({ // Metadata can hide a row without revoking access. Settle its overlays before // later ordinary metadata can reveal the retained mention. const admitted = (event: RelayEvent) => { - if (!event.tags.some(([name, value]) => name === "p" && value === viewer)) + if ( + isImportedEvent(event) || + !event.tags.some(([name, value]) => name === "p" && value === viewer) + ) return false; const hs = event.tags.filter(([name]) => name === "h"); return ( diff --git a/src/features/relay/unread.test.ts b/src/features/relay/unread.test.ts index 84314bc4e1..ebed191ab3 100644 --- a/src/features/relay/unread.test.ts +++ b/src/features/relay/unread.test.ts @@ -4012,3 +4012,23 @@ it("catch-up and explicit unread intent still apply to agent-audience rows", asy await unread.markMessageRead("room", progress.id); expect(h.snapshot()).toMatchObject({ observedCount: 0 }); }); + +it("imported history never counts as unread, attention or latest activity", () => { + const h = setup(); + h.grant("room"); + const proposal = "1".repeat(64); + const imported = message(h.alice, "room", "from the archive", 11, [ + ["p", h.viewer.pubkey], + ["import", proposal], + ["source", "slack", "1735732800.000100"], + ]); + h.emit([imported]); + expect(h.snapshot()).toMatchObject({ + observedCount: null, + attentionCount: null, + }); + expect(h.snapshot().latestMessage).toBeUndefined(); + const live = message(h.alice, "room", "hello", 12, [["p", h.viewer.pubkey]]); + h.emit([live]); + expect(h.snapshot()).toMatchObject({ observedCount: 1, attentionCount: 1 }); +}); diff --git a/src/features/relay/unread.ts b/src/features/relay/unread.ts index 55e7523e70..da0720df7f 100644 --- a/src/features/relay/unread.ts +++ b/src/features/relay/unread.ts @@ -4,6 +4,7 @@ import { agentAudience } from "./audience"; import type { InboxItem, InboxSnapshot } from "./inbox"; import type { ChannelQueries } from "./contracts"; import type { RelayEvent } from "./events"; +import { isImportedEvent } from "../conversation-import/protocol"; import { effectiveFrontier, overrideActive, @@ -1822,6 +1823,7 @@ export function createUnread({ for (const event of batch) { if ( ![9, 40002, 40008, 40003, 5, 9005].includes(event.kind) || + isImportedEvent(event) || events.has(event.id) ) continue; From 5abf5955cefff00866b9a668219c5d182f88aa38 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:41:06 -0600 Subject: [PATCH 4/6] feat(messages): render import records and imported messages Consent, withdrawal and completion records render as system lines. Imported messages show their source and original time, an edited marker when the source recorded an edit, a compact marker on continuation rows, no manual Retry, and never trigger the new-message divider. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- src/features/messages/ChannelTimeline.tsx | 11 ++ src/features/messages/DeliveryNotice.tsx | 6 +- .../messages/ImportNoticeRow.test.tsx | 104 ++++++++++++++++++ src/features/messages/ImportNoticeRow.tsx | 42 +++++++ src/features/messages/ImportedMarker.tsx | 41 +++++++ src/features/messages/MessageRow.tsx | 14 ++- src/features/messages/Messages.module.css | 10 ++ src/features/messages/message-grouping.ts | 3 + src/features/relay/contracts.ts | 8 ++ src/features/relay/fold.ts | 29 +++++ src/features/relay/membership.test.ts | 2 +- src/features/relay/membership.ts | 17 ++- src/features/relay/window.test.ts | 2 +- 13 files changed, 281 insertions(+), 8 deletions(-) create mode 100644 src/features/messages/ImportNoticeRow.test.tsx create mode 100644 src/features/messages/ImportNoticeRow.tsx create mode 100644 src/features/messages/ImportedMarker.tsx diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx index 5fff4ff994..03f62a816b 100644 --- a/src/features/messages/ChannelTimeline.tsx +++ b/src/features/messages/ChannelTimeline.tsx @@ -9,6 +9,7 @@ import { ChatCircleIcon, } from "../../shared/design-system/icons"; import { MembershipRow } from "./MembershipRow"; +import { ImportNoticeRow } from "./ImportNoticeRow"; import { membershipRows, withoutStartingAgents } from "./membership-rows"; import { activityGroups, RECENT_ACTIVITY_COUNT } from "./activity-groups"; import { DayDivider } from "./MessageTimestamp"; @@ -842,6 +843,7 @@ function Timeline({ const arrivals = rows.filter( (row, index) => !previousIds.has(row.id) && + !row.imported && (!paged || index > tail) && (row.createdAt > floor || (row.createdAt === floor && !paged)), ).length; @@ -1311,6 +1313,15 @@ function Timeline({ onOpenLink={onOpenLink} canOpenLink={canOpenLink} /> + ) : row.importRecord && + row.importRecord.type !== "proposal" ? ( + ) : ( diff --git a/src/features/messages/ImportNoticeRow.test.tsx b/src/features/messages/ImportNoticeRow.test.tsx new file mode 100644 index 0000000000..9eaf1dd48a --- /dev/null +++ b/src/features/messages/ImportNoticeRow.test.tsx @@ -0,0 +1,104 @@ +// @vitest-environment jsdom +import { cleanup, render, screen } from "@testing-library/react"; +import { getEventHash } from "nostr-tools"; +import { afterEach, assert, expect, it } from "vitest"; +import { + completeTemplate, + consentTemplate, + withdrawTemplate, +} from "../conversation-import/protocol"; +import type { Profile } from "../relay/contracts"; +import { foldMessages } from "../relay/fold"; +import { ImportNoticeRow } from "./ImportNoticeRow"; + +afterEach(cleanup); + +const viewer = "a".repeat(64); +const partner = "b".repeat(64); +const relayKey = "c".repeat(64); +const channel = "f0".repeat(16); +const proposalId = "1".repeat(64); + +function row( + pubkey: string, + template: { kind: number; content: string; tags: string[][] }, +) { + const unsigned = { ...template, pubkey, created_at: 1_740_000_000 }; + const [folded] = foldMessages(channel, relayKey, [ + { ...unsigned, id: getEventHash(unsigned) }, + ]); + assert.exists(folded?.importRecord); + return folded; +} + +const profiles: ReadonlyMap = new Map([ + [partner, { name: "Partner Person" } as Profile], +]); +const proposal = { + id: proposalId, + channelId: channel, + manifest: "d".repeat(64), + proposer: viewer, +}; + +it("renders consent, withdrawal and completion as quiet notices", () => { + const accepted = row( + partner, + consentTemplate(proposal, "accept", "3".repeat(64)), + ); + const { container } = render( + , + ); + expect(container.querySelector("[data-import-notice-row]")).toBeTruthy(); + expect(container.textContent).toContain( + "Partner Person accepted the conversation import", + ); + cleanup(); + render( + , + ); + expect(screen.getByText("You")).toBeTruthy(); + expect( + screen.getByText(/withdrew the conversation import: Wrong channel/), + ).toBeTruthy(); + cleanup(); + render( + "Resolved Name"} + />, + ); + expect(screen.getByText("Resolved Name")).toBeTruthy(); + expect( + screen.getByText(/finished importing 1 message and 2 reactions/), + ).toBeTruthy(); +}); + +it("renders nothing for an ordinary message", () => { + const unsigned = { + kind: 9, + content: "hello", + tags: [["h", channel]], + pubkey: partner, + created_at: 1_740_000_000, + }; + const [plain] = foldMessages(channel, relayKey, [ + { ...unsigned, id: getEventHash(unsigned) }, + ]); + assert.exists(plain); + const { container } = render( + , + ); + expect(container.textContent).toBe(""); +}); diff --git a/src/features/messages/ImportNoticeRow.tsx b/src/features/messages/ImportNoticeRow.tsx new file mode 100644 index 0000000000..c7ce70e397 --- /dev/null +++ b/src/features/messages/ImportNoticeRow.tsx @@ -0,0 +1,42 @@ +import { memo } from "react"; +import { importRecordText } from "../conversation-import/protocol"; +import type { ChannelMessage, Profile } from "../relay/contracts"; +import { DayDivider } from "./MessageTimestamp"; +import styles from "./Messages.module.css"; + +/** A conversation import consent, withdrawal or completion, as a quiet + * system line in the style of membership activity. */ +export const ImportNoticeRow = memo(function ImportNoticeRow({ + row, + profiles, + viewer, + day, + resolveName, +}: { + row: ChannelMessage; + profiles: ReadonlyMap; + viewer?: string | undefined; + day: boolean; + resolveName?: (pubkey: string, fallback: string) => string; +}) { + if (!row.importRecord) return null; + const fallback = + profiles.get(row.authorId)?.name ?? row.authorId.slice(0, 10); + const name = + row.authorId === viewer + ? "You" + : (resolveName?.(row.authorId, fallback) ?? fallback); + const text = importRecordText(row.importRecord); + return ( +
+ {day && } +
+

+ {name}{" "} + {text[0]?.toLowerCase()} + {text.slice(1)} +

+
+
+ ); +}); diff --git a/src/features/messages/ImportedMarker.tsx b/src/features/messages/ImportedMarker.tsx new file mode 100644 index 0000000000..9ea2a1a7b1 --- /dev/null +++ b/src/features/messages/ImportedMarker.tsx @@ -0,0 +1,41 @@ +import { sourceLabel } from "../conversation-import/protocol"; +import type { ChannelMessage } from "../relay/contracts"; +import { Tooltip } from "../../shared/design-system/ui/Tooltip"; +import styles from "./Messages.module.css"; + +/** A Buzz edit, or an edit the import source recorded before the message + * was imported. Only the former changes how mentions bind. */ +export function markedEdited(row: ChannelMessage) { + return !!row.edited || !!row.imported?.sourceEdited; +} + +/** `compact` is for continuation rows, which show no byline. */ +export function ImportedMarker({ + imported, + compact = false, +}: { + imported: NonNullable; + compact?: boolean; +}) { + const label = sourceLabel(imported.source); + return ( + + + {compact ? ( + "Imported" + ) : ( + <> + + Imported from {label} · original time + + )} + + + ); +} diff --git a/src/features/messages/MessageRow.tsx b/src/features/messages/MessageRow.tsx index 35047b4069..a67a5bd000 100644 --- a/src/features/messages/MessageRow.tsx +++ b/src/features/messages/MessageRow.tsx @@ -75,6 +75,7 @@ import { isNativeMediaSource, isProxySource } from "./attachment-source"; import { FileAttachment } from "./FileAttachment"; import { useReferenceDirectory } from "./ReferenceText"; import { EditedMarker, MessageMarkdown } from "./MessageMarkdown"; +import { ImportedMarker, markedEdited } from "./ImportedMarker"; import { safeMessageUrl } from "../relay/message-content"; import styles from "./Messages.module.css"; import { usesLargeEmojiPresentation } from "./emoji-size"; @@ -537,7 +538,7 @@ function MessageRowContent({ canOpenLink={canOpenLink} participantProfiles={participantProfiles} largeEmoji={emojiOnly} - edited={editedInBody && displayRow.edited} + edited={editedInBody && markedEdited(displayRow)} /> ); const avatar = row.workflowOwnerId ? ( @@ -924,6 +925,7 @@ function MessageRowContent({
{!row.membership && !row.huddle && + !row.importRecord && !renderMessage && messageActions()} {/* Screen-reader text stays out of selections: the clipboard carries @@ -972,6 +974,9 @@ function MessageRowContent({ {!stackPrevious && ( )} + {!stackPrevious && row.imported && ( + + )} {session && actions.map( (action) => @@ -985,6 +990,9 @@ function MessageRowContent({ ), )}
+ {stackPrevious && row.imported && ( + + )} {row.sentFromThread && (
@@ -1086,7 +1094,7 @@ function MessageRowContent({ ) : ( body )} - {editedInBubble && shown.edited && } + {editedInBubble && markedEdited(shown) && } {reactionsInBubble && reactionContent}
)} @@ -1282,7 +1290,7 @@ function MessageRowContent({ })} )} - {!editedInBody && !editedInBubble && shown.edited && ( + {!editedInBody && !editedInBubble && markedEdited(shown) && ( )} diff --git a/src/features/messages/Messages.module.css b/src/features/messages/Messages.module.css index 1b8bc79133..378143a25d 100644 --- a/src/features/messages/Messages.module.css +++ b/src/features/messages/Messages.module.css @@ -1773,6 +1773,16 @@ html[data-keyboard-navigation] .text pre code:focus-visible { font-size: var(--text-caption); letter-spacing: var(--text-caption--letter-spacing); } +/* Byline provenance for imported history, beside the timestamp. */ +.importedMarker { + color: var(--message-metadata, var(--text-metadata)); + font-size: var(--text-caption); + letter-spacing: var(--text-caption--letter-spacing); + white-space: nowrap; +} +.importNoticeName { + font-weight: var(--type-weight-medium); +} /* A plugin card's marker sits in its bubble, above the reactions. */ .messagePayload > .edited, .messageBubble > .edited { diff --git a/src/features/messages/message-grouping.ts b/src/features/messages/message-grouping.ts index dc1a66f2c0..d03b699369 100644 --- a/src/features/messages/message-grouping.ts +++ b/src/features/messages/message-grouping.ts @@ -8,6 +8,9 @@ export function continuesMessageGroup( !!previous && !previous.membership && !current.membership && + !previous.importRecord && + !current.importRecord && + !previous.imported === !current.imported && // Legacy output has no workflow ID: one relay signer is not one workflow. !previous.workflowOwnerId && !current.workflowOwnerId && diff --git a/src/features/relay/contracts.ts b/src/features/relay/contracts.ts index 3dc4c9d1a0..89e36288b1 100644 --- a/src/features/relay/contracts.ts +++ b/src/features/relay/contracts.ts @@ -1,4 +1,8 @@ import type { VerifiedProfile } from "./verified-profile"; +import type { + ImportedMarker, + ImportRecord, +} from "../conversation-import/protocol"; import type { ReadFilter } from "./events"; import type { CustomEmoji } from "./emoji"; import type { ReadOptions } from "./reader"; @@ -145,6 +149,10 @@ export type ChannelMessage = Readonly<{ }>; /** Current body came from a replacement edit; original recipients do not bind its prose. */ edited?: true; + /** Kind 9 history brought in by a consented conversation import (NIP-CI). */ + imported?: ImportedMarker; + /** A conversation import proposal, consent, withdrawal or completion. */ + importRecord?: ImportRecord; /** Offsets in `content` where attachment removal joined once-separate text; a * bound name never spans one. */ attachmentSeams?: readonly number[]; diff --git a/src/features/relay/fold.ts b/src/features/relay/fold.ts index 15da25f533..9da3d753c5 100644 --- a/src/features/relay/fold.ts +++ b/src/features/relay/fold.ts @@ -6,6 +6,12 @@ import { agentAudience } from "./audience"; import { emojiTags } from "./emoji"; import { objectBody } from "./body"; import { huddleRoom } from "../huddle/lifecycle"; +import { + IMPORT_RECORD_KINDS, + importedMarker, + importRecord, + importRecordText, +} from "../conversation-import/protocol"; import { newer } from "./events"; import type { EventData } from "./events"; import { @@ -373,6 +379,28 @@ export function foldMessages( ); continue; } + if (IMPORT_RECORD_KINDS.includes(event.kind)) { + const record = importRecord(event); + if (record) + rows.push( + Object.freeze({ + id: event.id, + channelId, + authorId: event.pubkey, + createdAt: event.created_at, + createdAtMs: eventMs(event), + content: importRecordText(record), + importRecord: record, + mentions: Object.freeze([]), + attachments: Object.freeze([]), + reactions: Object.freeze([]), + replyCount: 0, + participants: Object.freeze([]), + }), + ); + continue; + } + const imported = importedMarker(event); const edits = aux .filter( (item) => @@ -462,6 +490,7 @@ export function foldMessages( } : {}), ...(edits.length ? { edited: true as const } : {}), + ...(imported ? { imported } : {}), ...(projected.seams.length ? { attachmentSeams: projected.seams } : {}), mentionReferences: Object.freeze([ ...new Set( diff --git a/src/features/relay/membership.test.ts b/src/features/relay/membership.test.ts index 46c611c0f3..d7398b5db6 100644 --- a/src/features/relay/membership.test.ts +++ b/src/features/relay/membership.test.ts @@ -131,7 +131,7 @@ it.each([false, true])( const head = wire.next(); // Pages leave notices out, so joins cannot crowd messages from them. expect([...(head.filters[0]?.kinds ?? [])].sort((a, b) => a - b)).toEqual( - [9, 40002, 40008, 48100, 48103], + [9, 40002, 40008, 42110, 42111, 42112, 42113, 48100, 48103], ); const hello = message(viewer, "a", "Hello", 20); head.respond([ diff --git a/src/features/relay/membership.ts b/src/features/relay/membership.ts index 845d93b335..21a73124f5 100644 --- a/src/features/relay/membership.ts +++ b/src/features/relay/membership.ts @@ -3,7 +3,9 @@ import type { EventData } from "./events"; import { objectBody } from "./body"; /** Content rows retained by channel history/live windows, not the unread kind set. */ -export const CHANNEL_ROW_KINDS = [9, 40002, 40008, 40099, 48100, 48103]; +export const CHANNEL_ROW_KINDS = [ + 9, 40002, 40008, 40099, 48100, 48103, 42110, 42111, 42112, 42113, +]; export const channelRowKind = (kind: number) => CHANNEL_ROW_KINDS.includes(kind); const pubkey = (value: unknown): value is string => @@ -46,6 +48,11 @@ export function rowProfileIds(row: ChannelMessage): readonly string[] { ...row.mentions, ...(row.mentionReferences ?? []), ...row.participants, + ...(row.importRecord?.type === "proposal" + ? row.importRecord.proposal.content.participants.map( + (participant) => participant.pubkey, + ) + : []), ]; } @@ -55,7 +62,13 @@ export function messagePreview( ): string | undefined { for (let i = rows.length - 1; i >= 0; i--) { const row = rows[i]; - if (row && !row.membership && !row.huddle) + if ( + row && + !row.membership && + !row.huddle && + !row.importRecord && + !row.imported + ) return row.diff ? `Diff: ${row.diff.filePath || "patch"}${row.diff.description ? ` — ${row.diff.description}` : ""}` : row.content; diff --git a/src/features/relay/window.test.ts b/src/features/relay/window.test.ts index c4166e6837..83414446ef 100644 --- a/src/features/relay/window.test.ts +++ b/src/features/relay/window.test.ts @@ -11,7 +11,7 @@ const id = "a".repeat(64); describe("channel window bounds", () => { it("requests top-level rows with aux and summaries, and only echoes a full composite cursor", () => { expect(windowFilter(channel, null)).toMatchObject({ - kinds: [9, 40002, 40008, 48100, 48103], + kinds: [9, 40002, 40008, 48100, 48103, 42110, 42111, 42112, 42113], "#h": [channel], top_level: true, include_aux: true, From 8d79e7ff315ee80f89bf1b8194f0a80b4ec719a6 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:41:08 -0600 Subject: [PATCH 5/6] feat(import): consented conversation import service and consent card The conversationImport service checks verified identities and membership, shows host-owned confirmation dialogs for proposals, consents and new destinations, and publishes imported history paced at 8 events per second, waiting for other participants' parents and stopping on the first refusal or membership change. Host state is unreachable from plugins, and only the host can construct the service; dialogs approve only on a trusted click. Proposals and consents need relay NIP-CI support; publishing needs an active relay snapshot, and the destination is rechecked after each dialog and before each event. Attachment tags are derived from the file hash and the type the relay sniffs from the file's first bytes, so every participant produces the same event ids. The proposal renders as a consent card that reads its own snapshot, with a progress banner while active. Types are exported through the author package; gallery specimens added. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- docs/buzz-help.md | 8 + src/app/App.tsx | 4 + src/app/conversation-features.ts | 2 + src/app/pages.integration.test.mjs | 20 +- src/app/services.ts | 11 + .../ConversationImport.module.css | 117 ++ .../ConversationImportReview.test.tsx | 74 + .../ConversationImportReview.tsx | 129 ++ .../conversation-import/ImportCards.test.tsx | 295 +++ .../conversation-import/ImportCards.tsx | 321 +++ src/features/conversation-import/feature.tsx | 37 + .../relay-media-type.test.ts | 110 ++ .../conversation-import/relay-media-type.ts | 778 ++++++++ src/features/conversation-import/reviews.ts | 92 + .../conversation-import/service.test.ts | 1318 +++++++++++++ src/features/conversation-import/service.ts | 1713 +++++++++++++++++ src/plugins/author.ts | 20 + tests/fixtures/message-gallery/examples.ts | 34 + .../message-gallery/import-examples.ts | 168 ++ tests/fixtures/message-gallery/main.tsx | 26 + 20 files changed, 5266 insertions(+), 11 deletions(-) create mode 100644 src/features/conversation-import/ConversationImport.module.css create mode 100644 src/features/conversation-import/ConversationImportReview.test.tsx create mode 100644 src/features/conversation-import/ConversationImportReview.tsx create mode 100644 src/features/conversation-import/ImportCards.test.tsx create mode 100644 src/features/conversation-import/ImportCards.tsx create mode 100644 src/features/conversation-import/feature.tsx create mode 100644 src/features/conversation-import/relay-media-type.test.ts create mode 100644 src/features/conversation-import/relay-media-type.ts create mode 100644 src/features/conversation-import/reviews.ts create mode 100644 src/features/conversation-import/service.test.ts create mode 100644 src/features/conversation-import/service.ts create mode 100644 tests/fixtures/message-gallery/import-examples.ts diff --git a/docs/buzz-help.md b/docs/buzz-help.md index fae352100a..af09d68e46 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -78,6 +78,14 @@ the interface unless an available tool actually supports that action. - **Sharing a Solo chat** grants access to its conversation history, not only the next message. Copying its link alone does not grant access. Check the intended people and destination before changing access. +- **Conversation import** brings history from another tool into a direct + message or channel when an import plugin is installed and the community's + relay supports it. Nothing is imported until every participant accepts the + proposal card in the conversation; each person then publishes only their own + messages, at their original times. Buzz confirms each step in its own dialog + and shows verified names and key fingerprints. Imported messages are marked + with their source and do not count as unread or send notifications. People + without a verified Buzz identity are left out. ## Choosing and customizing agents diff --git a/src/app/App.tsx b/src/app/App.tsx index 222803c3a0..3dea525aed 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -24,6 +24,7 @@ import { Dialog } from "../shared/design-system/ui/Dialog"; import { UpdateNotice } from "../features/updates/UpdateNotice"; import { RejectedLinkNotice } from "../features/navigation/RejectedLinkNotice"; import { CreationReview } from "../bundled/agents/CreationReview"; +import { ConversationImportReview } from "../features/conversation-import/ConversationImportReview"; import { UpdateReview } from "../bundled/agents/UpdateReview"; import { InterruptedNotice } from "../features/agents/InterruptedNotice"; import { @@ -635,6 +636,9 @@ function ConnectedAppContent({ services }: { services: AppServices }) { + {!settings && startup === "recovery" ? ( diff --git a/src/app/conversation-features.ts b/src/app/conversation-features.ts index 094c3dddc9..c7b737b4e9 100644 --- a/src/app/conversation-features.ts +++ b/src/app/conversation-features.ts @@ -3,10 +3,12 @@ import emojiManifest from "../bundled/emoji/manifest.json"; import * as emoji from "../bundled/emoji"; import mentionsManifest from "../bundled/mentions/manifest.json"; import * as mentions from "../bundled/mentions"; +import * as conversationImport from "../features/conversation-import/feature"; // Host-owned features use the shared contribution lifecycle, without catalog // entries or saved enablement. Keep their keys for composer and huddle consumers. export const conversationFeatures: readonly BundledPlugin[] = [ { manifest: { ...emojiManifest, apiVersion: 1 }, module: emoji }, { manifest: { ...mentionsManifest, apiVersion: 1 }, module: mentions }, + { manifest: conversationImport.manifest, module: conversationImport }, ]; diff --git a/src/app/pages.integration.test.mjs b/src/app/pages.integration.test.mjs index 98fd08707f..087180a89b 100644 --- a/src/app/pages.integration.test.mjs +++ b/src/app/pages.integration.test.mjs @@ -281,26 +281,24 @@ test("the app runtime exposes ready bundled pages and removes them on disable", .snapshot() .some((panel) => panel.pluginId === "buzz.agent-activity"), ); - assert.equal(services.conversation.accessories.snapshot().length, 2); - assert.deepEqual( + // The host's conversation import banner is a built-in accessory. + const pluginAccessories = () => services.conversation.accessories .snapshot() - .map(({ id, placement }) => [id, placement]), + .filter((item) => item.pluginId !== "buzz.conversation-import"); + assert.equal(pluginAccessories().length, 2); + assert.deepEqual( + pluginAccessories().map(({ id, placement }) => [id, placement]), [ ["activity", "message"], ["typing-presentation", undefined], ], ); - assert.equal( - services.conversation.accessories.snapshot()[0].pluginId, - "buzz.agent-activity", - ); + assert.equal(pluginAccessories()[0].pluginId, "buzz.agent-activity"); await services.plugins.change("disable", "buzz.agent-activity"); - assert.equal(services.conversation.accessories.snapshot().length, 0); + assert.equal(pluginAccessories().length, 0); await services.plugins.change("enable", "buzz.agent-activity"); - await vi.waitFor(() => - assert.equal(services.conversation.accessories.snapshot().length, 2), - ); + await vi.waitFor(() => assert.equal(pluginAccessories().length, 2)); await services.plugins.change("enable", "buzz.bestie"); await vi.waitFor(() => diff --git a/src/app/services.ts b/src/app/services.ts index d1d3770541..f3eb7cff9c 100644 --- a/src/app/services.ts +++ b/src/app/services.ts @@ -1,4 +1,6 @@ import { ArtifactStorageService } from "../features/artifact-storage/service"; +import { createConversationImportHost } from "../features/conversation-import/service"; +import { createImportReviews } from "../features/conversation-import/reviews"; import { createAdminAccess } from "../bundled/admin-access"; import { nativeRelayStaff } from "../features/relay-staff/native"; import { createLocalAgentActivity } from "../features/agents/local-activity"; @@ -99,6 +101,13 @@ export function createServices() { }); const relay = communities.relay; const artifactStorage = new ArtifactStorageService(ctx); + const conversationImportReviews = createImportReviews(); + const conversationImport = createConversationImportHost( + ctx, + relay, + conversationImportReviews, + ); + ctx.effect(() => () => conversationImportReviews.dispose()); // Expose v2 only with the complete label/projection/frame/Destination/guard slice. new SoloNavigationService(ctx, relay, plugins); // The one recovery point for federated sign-in; see onSignedIn. @@ -225,6 +234,8 @@ export function createServices() { shortcutBindings, conversation, artifactStorage, + conversationImport, + conversationImportReviews, settingsCards, adminAccess, pages, diff --git a/src/features/conversation-import/ConversationImport.module.css b/src/features/conversation-import/ConversationImport.module.css new file mode 100644 index 0000000000..7541f4aad7 --- /dev/null +++ b/src/features/conversation-import/ConversationImport.module.css @@ -0,0 +1,117 @@ +.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: var(--space-1) var(--space-3); + margin: 0; + font-size: var(--text-body-sm); + line-height: var(--text-body-sm--line-height); + letter-spacing: var(--text-body-sm--letter-spacing); +} +.facts dt { + color: var(--text-subtle); +} +.facts dd { + margin: 0; + min-width: 0; + overflow-wrap: anywhere; +} +.members { + display: flex; + flex-direction: column; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; +} +.member { + display: flex; + flex-direction: column; + gap: 0; + min-width: 0; +} +.memberName { + font-weight: var(--type-weight-medium); +} +.memberMeta, +.fingerprint { + color: var(--text-subtle); + font-size: var(--text-caption); + line-height: var(--text-caption--line-height); + letter-spacing: var(--text-caption--letter-spacing); +} +.fingerprint { + font-family: var(--font-mono); + overflow-wrap: anywhere; +} +.unverified { + color: var(--text-danger); +} +.statement { + margin: 0; + font-weight: var(--type-weight-medium); +} +.refusal { + margin: 0; + color: var(--text-danger); +} +.body { + display: flex; + flex-direction: column; + gap: var(--space-4); +} +.sectionTitle { + margin: 0 0 var(--space-2); + color: var(--text-subtle); + font-size: var(--text-caption); + line-height: var(--text-caption--line-height); + letter-spacing: var(--text-caption--letter-spacing); +} +.card { + display: flex; + flex-direction: column; + gap: var(--space-3); + padding: var(--space-3); + border: 1px solid var(--border-standard); + border-radius: var(--radius-control); + background: var(--surface-panel); + width: min(100%, 36rem); +} +.cardTitle { + margin: 0; + font-weight: var(--type-weight-medium); +} +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} +.status { + margin: 0; + color: var(--text-subtle); + font-size: var(--text-body-sm); + line-height: var(--text-body-sm--line-height); + letter-spacing: var(--text-body-sm--letter-spacing); +} +.banner { + display: flex; + align-items: center; + gap: var(--space-3); + padding: var(--space-2) var(--space-3); + border: 1px solid var(--border-standard); + border-radius: var(--radius-control); + background: var(--surface-panel); + font-size: var(--text-body-sm); + line-height: var(--text-body-sm--line-height); + letter-spacing: var(--text-body-sm--letter-spacing); +} +.bannerText { + flex: 1; + min-width: 0; +} +.meter { + flex-shrink: 0; + width: 6rem; +} +.fact { + display: contents; +} diff --git a/src/features/conversation-import/ConversationImportReview.test.tsx b/src/features/conversation-import/ConversationImportReview.test.tsx new file mode 100644 index 0000000000..bf84766a6c --- /dev/null +++ b/src/features/conversation-import/ConversationImportReview.test.tsx @@ -0,0 +1,74 @@ +// @vitest-environment jsdom +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { afterEach, expect, it } from "vitest"; +import { ConversationImportReview } from "./ConversationImportReview"; +import { createImportReviews } from "./reviews"; + +afterEach(cleanup); + +function pending() { + const reviews = createImportReviews(); + let approved: boolean | undefined; + void reviews + .request({ + type: "consent", + title: "Accept this import?", + description: "Your messages will be imported.", + facts: [], + members: [], + confirmLabel: "Accept", + }) + .then((result) => { + approved = result; + }); + render(); + return { reviews, approved: () => approved }; +} + +/** React reads `nativeEvent`, so a synthetic trusted click is delivered + * straight to the button's handler, as a real pointer or key press would be. */ +function trustedClick(button: HTMLElement) { + const key = Object.keys(button).find((name) => + name.startsWith("__reactProps$"), + ); + const props = key && (button as unknown as Record)[key]; + (props as { onClick(event: unknown): void }).onClick({ + nativeEvent: { isTrusted: true }, + }); +} + +it("ignores a scripted click on approve", async () => { + const { reviews, approved } = pending(); + const button = screen.getByRole("button", { name: "Accept" }); + fireEvent.click(button); + await act(async () => { + button.click(); + button.dispatchEvent(new MouseEvent("click", { bubbles: true })); + }); + expect(reviews.snapshot()).toHaveLength(1); + expect(approved()).toBeUndefined(); +}); + +it("approves on a trusted click", async () => { + const { reviews, approved } = pending(); + await act(async () => { + trustedClick(screen.getByRole("button", { name: "Accept" })); + }); + expect(reviews.snapshot()).toHaveLength(0); + expect(approved()).toBe(true); +}); + +it("cancels on any click", async () => { + const { reviews, approved } = pending(); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + }); + expect(reviews.snapshot()).toHaveLength(0); + expect(approved()).toBe(false); +}); diff --git a/src/features/conversation-import/ConversationImportReview.tsx b/src/features/conversation-import/ConversationImportReview.tsx new file mode 100644 index 0000000000..e9cb14e2cf --- /dev/null +++ b/src/features/conversation-import/ConversationImportReview.tsx @@ -0,0 +1,129 @@ +import { useSyncExternalStore } from "react"; +import { Button } from "../../shared/design-system/ui/Button"; +import { Dialog } from "../../shared/design-system/ui/Dialog"; +import { fingerprint } from "./protocol"; +import type { ImportReview, ImportReviews, ReviewMember } from "./reviews"; +import styles from "./ConversationImport.module.css"; + +export function ImportMembers({ + members, +}: { + members: readonly ReviewMember[]; +}) { + return ( +
    + {members.map((member) => ( +
  • + {member.verified ? ( + <> + + {member.verified.displayName} + + + @{member.verified.username} + {member.note ? ` · ${member.note}` : ""} + + + ) : ( + <> + + No verified identity + + {member.note && ( + {member.note} + )} + + )} + + {member.verified?.fingerprint ?? fingerprint(member.pubkey)} + +
  • + ))} +
+ ); +} + +export function ImportReviewDialog({ + review, + onApprove, + onDismiss, +}: { + review: ImportReview; + onApprove(): void; + onDismiss(): void; +}) { + return ( + { + if (!open) onDismiss(); + }} + actions={ + <> + + {!review.refusal && ( + + )} + + } + > +
+ {review.refusal && ( +

+ {review.refusal} +

+ )} +
+ {review.facts.map((fact) => ( +
+
{fact.label}
+
{fact.value}
+
+ ))} +
+
+

People

+ +
+ {review.statement && ( +

{review.statement}

+ )} +
+
+ ); +} + +/** Mounted once by the app shell. Shows the oldest pending import request. */ +export function ConversationImportReview({ + reviews, +}: { + reviews: ImportReviews; +}) { + const pending = useSyncExternalStore(reviews.subscribe, reviews.snapshot); + const review = pending[0]; + if (!review) return null; + return ( + reviews.approve(review.id)} + onDismiss={() => reviews.dismiss(review.id)} + /> + ); +} diff --git a/src/features/conversation-import/ImportCards.test.tsx b/src/features/conversation-import/ImportCards.test.tsx new file mode 100644 index 0000000000..a304674b25 --- /dev/null +++ b/src/features/conversation-import/ImportCards.test.tsx @@ -0,0 +1,295 @@ +// @vitest-environment jsdom +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { getEventHash } from "nostr-tools"; +import { afterEach, assert, expect, it, vi } from "vitest"; +import { foldMessages } from "../relay/fold"; +import type { RelayData } from "../relay/service"; +import { ImportedMarker, markedEdited } from "../messages/ImportedMarker"; +import { ImportConsentCard, ImportProgressBanner } from "./ImportCards"; +import { proposalTemplate } from "./protocol"; +import type { + ConversationImportService, + ImportProposalInput, + ImportSessionView, +} from "./types"; + +afterEach(cleanup); + +const viewer = "a".repeat(64); +const partner = "b".repeat(64); +const relayKey = "c".repeat(64); +const channel = "f0".repeat(16); +const now = 1_740_000_000; +const input: ImportProposalInput = { + channelId: channel, + source: { + type: "slack", + conversation: "e".repeat(64), + kind: "private_channel", + label: "#project-room", + }, + range: { from: 1_735_689_600, to: 1_735_776_000 }, + participants: [ + { pubkey: viewer, source_user: "2".repeat(64), messages: 12, reactions: 3 }, + { pubkey: partner, source_user: "3".repeat(64), messages: 8, reactions: 1 }, + ], + excluded_authors: 2, + manifest: "0123456789abcdef".repeat(4), + expires_at: now + 86_400, +}; + +function event( + pubkey: string, + template: { kind: number; content: string; tags: string[][] }, + created_at = now - 60, +) { + const unsigned = { ...template, pubkey, created_at }; + return { ...unsigned, id: getEventHash(unsigned), sig: "0".repeat(128) }; +} + +function harness( + view?: Partial, + options: { + input?: ImportProposalInput; + refreshed?: Partial; + role?: string; + } = {}, +) { + const source = options.input ?? input; + const proposal = event(partner, proposalTemplate(source)); + const [row] = foldMessages(channel, relayKey, [proposal]); + assert.exists(row?.importRecord); + const verified = (displayName: string, username: string) => ({ + name: displayName, + verified: { + displayName, + username, + issuerLabel: "Example Directory", + verifiedAt: 1_700_000_000, + status: "checked" as const, + multipleIssuers: false, + }, + }); + const profiles = new Map([ + [viewer, verified("Viewer Person", "viewer")], + [partner, verified("Partner Person", "partner")], + ]); + const session = { + profiles: { + snapshot: () => profiles, + subscribe: () => () => {}, + ensure: async () => {}, + }, + channels: { + list: () => ({ + channels: [{ id: channel, viewerRole: options.role ?? "member" }], + }), + }, + }; + const connection = { session, viewer, status: "ready" }; + const relay = { + snapshot: () => connection, + subscribe: () => () => {}, + } as unknown as RelayData; + const base: ImportSessionView = { + proposalId: proposal.id, + channelId: channel, + proposer: partner, + proposedAt: proposal.created_at, + proposal: (({ channelId: _, ...rest }) => rest)(source), + status: "proposed", + required: source.participants.map((item) => item.pubkey), + consents: { [partner]: "accept" }, + published: {}, + completed: [], + expires_at: source.expires_at, + confirmed: true, + }; + const sessionView: ImportSessionView | undefined = view && { + ...base, + ...view, + }; + const refreshedView = options.refreshed && { ...base, ...options.refreshed }; + const service = { + session: () => sessionView, + subscribe: (cb: (sessions: readonly ImportSessionView[]) => void) => { + cb(sessionView ? [sessionView] : []); + return () => {}; + }, + refresh: vi.fn(async () => refreshedView ?? sessionView), + consent: vi.fn(async () => {}), + withdraw: vi.fn(async () => {}), + } as unknown as ConversationImportService & { + consent: ReturnType; + refresh: ReturnType; + }; + return { row, relay, service, proposal }; +} + +it("renders the consent card with verified identities, counts and the manifest fingerprint", () => { + const { row, relay, service, proposal } = harness({}); + render(); + expect(screen.getByText("Import #project-room from Slack")).toBeTruthy(); + expect(screen.getByText(/1 of 2 accepted/)).toBeTruthy(); + expect(screen.getByText("Private channel")).toBeTruthy(); + expect(screen.getByText("20 messages, 4 reactions")).toBeTruthy(); + expect( + screen.getByText(/Messages from 2 people without a verified/), + ).toBeTruthy(); + expect( + screen.getByText( + "01234567 89abcdef 01234567 89abcdef 01234567 89abcdef 01234567 89abcdef", + ), + ).toBeTruthy(); + expect(screen.getByText("Viewer Person")).toBeTruthy(); + expect( + screen.getByText(/@partner · 8 messages, 1 reactions · accepted/), + ).toBeTruthy(); + expect( + screen.getByText( + "bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb bbbbbbbb", + ), + ).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Accept" })); + expect(service.consent).toHaveBeenCalledWith( + proposal.id, + "accept", + "2".repeat(64), + ); +}); + +it("offers no decision once the import has ended", () => { + const { row, relay, service } = harness({ status: "declined" }); + render(); + expect(screen.getByText("Declined")).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Accept" })).toBeNull(); +}); + +const outsiderInput: ImportProposalInput = { + ...input, + source: { ...input.source, kind: "public_channel" }, + participants: [ + input.participants[1] as ImportProposalInput["participants"][number], + ], +}; + +it("reads its own snapshot so a member outside the import sees how it ended", async () => { + const { row, relay, service, proposal } = harness(undefined, { + input: outsiderInput, + refreshed: { status: "completed" }, + role: "admin", + }); + render(); + await waitFor(() => expect(screen.getByText("Imported")).toBeTruthy()); + expect(service.refresh).toHaveBeenCalledWith(proposal.id, expect.anything()); + expect(screen.queryByRole("button", { name: "Approve as admin" })).toBeNull(); +}); + +it("offers admin approval only on a live proposal", async () => { + const live = harness(undefined, { + input: outsiderInput, + refreshed: { status: "proposed", consents: {} }, + role: "admin", + }); + render( + , + ); + await waitFor(() => + expect( + screen.getByRole("button", { name: "Approve as admin" }), + ).toBeTruthy(), + ); + cleanup(); + const expired = harness(undefined, { + input: { ...outsiderInput, expires_at: Math.floor(Date.now() / 1000) - 1 }, + role: "admin", + }); + expired.service.refresh.mockRejectedValue(new Error("offline")); + render( + , + ); + expect(screen.getByText("Expired before everyone accepted")).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Approve as admin" })).toBeNull(); +}); + +it("counts people done against every participant", () => { + const active = harness({ + status: "active", + required: [partner], + completed: [partner], + }); + render(); + expect(screen.getByText(/1 of 2 people done/)).toBeTruthy(); +}); + +it("shows a compact imported marker on continuation rows", () => { + render( + , + ); + expect(screen.getByText("Imported")).toBeTruthy(); +}); + +it("shows a progress banner only while the import is active", () => { + const active = harness({ + status: "active", + published: { [partner]: { messages: 8, reactions: 1 } }, + completed: [partner], + }); + render(); + expect( + screen.getByText( + "Importing #project-room from Slack: 9 of 24 items, 1 of 2 people done", + ), + ).toBeTruthy(); + cleanup(); + const done = harness({ status: "completed" }); + const { container } = render( + , + ); + expect(container.textContent).toBe(""); +}); + +it("marks imported messages and their source edits", () => { + const imported = event( + viewer, + { + kind: 9, + content: "From the archive", + tags: [ + ["h", channel], + ["import", "1".repeat(64)], + ["source", "slack", "1735732800.000100"], + ["source-edited", "1"], + ], + }, + 1_735_732_800, + ); + const plain = event(viewer, { + kind: 9, + content: "Live", + tags: [["h", channel]], + }); + const [first, second] = foldMessages(channel, relayKey, [imported, plain]); + assert.exists(first?.imported); + expect(second?.imported).toBeUndefined(); + expect(markedEdited(first)).toBe(true); + render(); + expect(screen.getByText(/Imported from Slack · original time/)).toBeTruthy(); +}); diff --git a/src/features/conversation-import/ImportCards.tsx b/src/features/conversation-import/ImportCards.tsx new file mode 100644 index 0000000000..6978febb08 --- /dev/null +++ b/src/features/conversation-import/ImportCards.tsx @@ -0,0 +1,321 @@ +import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; +import { Button } from "../../shared/design-system/ui/Button"; +import type { ChannelMessage, Profile } from "../relay/contracts"; +import { useRelayConnection } from "../relay/react"; +import type { RelayData } from "../relay/service"; +import { ImportMembers } from "./ConversationImportReview"; +import { fingerprint, SOURCE_KIND_LABELS, sourceLabel } from "./protocol"; +import type { ReviewMember } from "./reviews"; +import type { + ConversationImportService, + ImportSessionView, + VerifiedProfileView, +} from "./types"; +import styles from "./ConversationImport.module.css"; + +const emptyProfiles: ReadonlyMap = new Map(); +const noSubscribe = () => () => {}; + +const STATUS_TEXT: Record = { + proposed: "Waiting for everyone to accept", + active: "Importing", + declined: "Declined", + withdrawn: "Withdrawn", + expired: "Expired before everyone accepted", + completed: "Imported", +}; + +function formatDate(seconds: number) { + return new Date(seconds * 1000).toLocaleDateString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + }); +} + +/** The live read model, seeded by one relay read so that members outside + * the session still see its current status. */ +function useImportSession( + service: ConversationImportService, + proposalId: string, +) { + const subscribe = useCallback( + (changed: () => void) => service.subscribe(() => changed()), + [service], + ); + const read = () => (proposalId ? service.session(proposalId) : undefined); + const live = useSyncExternalStore(subscribe, read, read); + const [fetched, setFetched] = useState(); + useEffect(() => { + if (!proposalId) return; + const controller = new AbortController(); + void service + .refresh(proposalId, controller.signal) + .then((view) => { + if (!controller.signal.aborted) setFetched(view); + }) + .catch(() => {}); + return () => controller.abort(); + }, [service, proposalId]); + return live ?? (fetched?.proposalId === proposalId ? fetched : undefined); +} + +function verifiedFrom( + pubkey: string, + profile: Profile | undefined, +): VerifiedProfileView | undefined { + const verified = profile?.verified; + return ( + verified && { + pubkey, + displayName: verified.displayName, + username: verified.username, + issuerLabel: verified.issuerLabel, + verifiedAt: verified.verifiedAt, + fingerprint: fingerprint(pubkey), + } + ); +} + +/** The proposal (kind 42110) as an in-timeline consent card. Accept and + * Decline open the host's confirmation dialog; the card never signs. */ +export function ImportConsentCard({ + message, + relay, + service, +}: { + message: ChannelMessage; + relay: RelayData; + service: ConversationImportService; +}) { + const record = message.importRecord; + const proposal = record?.type === "proposal" ? record.proposal : undefined; + const connection = useRelayConnection(relay); + const session = connection.session; + const profiles = useSyncExternalStore( + session?.profiles.subscribe ?? noSubscribe, + () => session?.profiles.snapshot() ?? emptyProfiles, + () => session?.profiles.snapshot() ?? emptyProfiles, + ); + const view = useImportSession(service, proposal?.id ?? ""); + const [pending, setPending] = useState(false); + const [error, setError] = useState(); + const participantKeys = + proposal?.content.participants.map((item) => item.pubkey).join(":") ?? ""; + useEffect(() => { + if (participantKeys) + void session?.profiles.ensure(participantKeys.split(":")).catch(() => {}); + }, [session, participantKeys]); + if (!proposal) return null; + const { content } = proposal; + const viewer = connection.viewer; + // Without a read model yet, the proposal's own expiry still applies. + const status = + view?.status ?? + (content.expires_at <= Date.now() / 1000 ? "expired" : "proposed"); + const consents = view?.consents ?? {}; + const own = content.participants.find((item) => item.pubkey === viewer); + const open = status === "proposed" || status === "active"; + const totals = content.participants.reduce( + (sum, item) => ({ + messages: sum.messages + item.messages, + reactions: sum.reactions + item.reactions, + }), + { messages: 0, reactions: 0 }, + ); + const accepted = content.participants.filter( + (item) => consents[item.pubkey] === "accept", + ).length; + const members: ReviewMember[] = content.participants.map((item) => { + const verified = verifiedFrom(item.pubkey, profiles.get(item.pubkey)); + const decision = consents[item.pubkey]; + const state = + decision === "accept" + ? "accepted" + : decision === "decline" + ? "declined" + : view?.confirmed + ? "waiting" + : undefined; + const note = [ + `${item.messages} messages, ${item.reactions} reactions`, + state, + ] + .filter(Boolean) + .join(" · "); + return { pubkey: item.pubkey, ...(verified ? { verified } : {}), note }; + }); + const act = async (run: () => Promise) => { + setPending(true); + setError(undefined); + try { + await run(); + } catch (reason) { + if (!(reason instanceof DOMException && reason.name === "AbortError")) + setError(reason instanceof Error ? reason.message : String(reason)); + } finally { + setPending(false); + } + }; + const decided = own ? consents[own.pubkey] : undefined; + const role = session?.channels + ?.list() + .channels.find((item) => item.id === proposal.channelId)?.viewerRole; + const canApprove = + open && + !!view && + !own && + !!viewer && + !consents[viewer] && + (role === "owner" || role === "admin"); + return ( +
+

+ Import {content.source.label} from {sourceLabel(content.source.type)} +

+

+ {STATUS_TEXT[status]} + {status === "proposed" && view?.confirmed + ? ` (${accepted} of ${content.participants.length} accepted)` + : ""} +

+
+
+
Source
+
{SOURCE_KIND_LABELS[content.source.kind]}
+
+
+
Date range
+
+ {formatDate(content.range.from)} to {formatDate(content.range.to)} +
+
+
+
Messages
+
+ {totals.messages} messages, {totals.reactions} reactions +
+
+ {content.excluded_authors > 0 && ( +
+
Not imported
+
+ Messages from {content.excluded_authors}{" "} + {content.excluded_authors === 1 ? "person" : "people"} without a + verified Buzz identity +
+
+ )} +
+
Manifest
+
+ {fingerprint(content.manifest)} +
+
+
+ + {error && ( +

+ {error} +

+ )} + {open && own && ( +
+ {!decided && ( + <> + + + + )} + {(decided === "accept" || proposal.proposer === viewer) && ( + + )} +
+ )} + {canApprove && ( +
+ +
+ )} +
+ ); +} + +/** Composer banner while an import in this channel is publishing. */ +export function ImportProgressBanner({ + channelId, + service, +}: { + channelId: string; + service: ConversationImportService; +}) { + const [sessions, setSessions] = useState([]); + useEffect(() => service.subscribe(setSessions), [service]); + const active = sessions.find( + (item) => item.channelId === channelId && item.status === "active", + ); + if (!active) return null; + const total = active.proposal.participants.reduce( + (sum, item) => sum + item.messages + item.reactions, + 0, + ); + const published = Object.values(active.published).reduce( + (sum, item) => sum + item.messages + item.reactions, + 0, + ); + const done = Math.min(published, total); + return ( +
+ + Importing {active.proposal.source.label} from{" "} + {sourceLabel(active.proposal.source.type)}: {done} of {total} items,{" "} + {active.completed.length} of {active.proposal.participants.length}{" "} + people done + + +
+ ); +} diff --git a/src/features/conversation-import/feature.tsx b/src/features/conversation-import/feature.tsx new file mode 100644 index 0000000000..ca88fca30d --- /dev/null +++ b/src/features/conversation-import/feature.tsx @@ -0,0 +1,37 @@ +import type { PluginModule } from "../../plugins/api"; +import { ImportConsentCard, ImportProgressBanner } from "./ImportCards"; + +export const manifest = { + id: "buzz.conversation-import", + name: "Conversation import", + apiVersion: 1, + description: + "Consent cards and progress for conversations imported from other tools.", +} as const; + +export const inject = ["conversation", "relay", "conversationImport"]; +export const apply: PluginModule["apply"] = (ctx) => { + ctx.conversation.registerMessage({ + id: "proposal", + title: "Conversation import proposal", + matches: (message) => message.importRecord?.type === "proposal", + component: ({ message }) => ( + + ), + }); + ctx.conversation.registerAccessory({ + id: "progress", + title: "Import progress", + component: ({ channelId, threadRootId }) => + threadRootId ? null : ( + + ), + }); +}; diff --git a/src/features/conversation-import/relay-media-type.test.ts b/src/features/conversation-import/relay-media-type.test.ts new file mode 100644 index 0000000000..cd8034811c --- /dev/null +++ b/src/features/conversation-import/relay-media-type.test.ts @@ -0,0 +1,110 @@ +import { expect, it } from "vitest"; +import { + relayMediaType, + SNIFF_BYTES, + UNSUPPORTED_FILE, +} from "./relay-media-type"; + +const text = (value: string) => new TextEncoder().encode(value); +const join = (...parts: (Uint8Array | number[] | string)[]) => { + const chunks = parts.map((part) => + typeof part === "string" ? text(part) : Uint8Array.from(part), + ); + const out = new Uint8Array(chunks.reduce((sum, c) => sum + c.length, 0)); + let at = 0; + for (const chunk of chunks) { + out.set(chunk, at); + at += chunk.length; + } + return out; +}; +const whole = (bytes: Uint8Array) => relayMediaType(bytes, bytes.length); + +/** A ZIP local file header whose first entry is `name`. */ +function zipEntry(name: string, body = "") { + const header = new Uint8Array(30); + header.set([0x50, 0x4b, 0x03, 0x04]); + new DataView(header.buffer).setUint32(18, body.length, true); + new DataView(header.buffer).setUint16(26, name.length, true); + return join(header, name, body); +} + +it("sniffs images, documents and archives as the relay does", () => { + expect(whole(join([0xff, 0xd8, 0xff, 0xe0], "JFIF"))).toEqual({ + mime: "image/jpeg", + ext: "jpg", + }); + expect(whole(join("RIFF", [0, 0, 0, 0], "WEBPVP8 "))).toEqual({ + mime: "image/webp", + ext: "webp", + }); + expect( + whole(join(zipEntry("word/document.xml"), new Uint8Array(64))), + ).toEqual({ + mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ext: "docx", + }); + expect( + whole( + join( + zipEntry("mimetype", "application/vnd.oasis.opendocument.text"), + new Uint8Array(16), + ), + ).ext, + ).toBe("odt"); + expect(whole(join(zipEntry("readme.txt"), new Uint8Array(64))).ext).toBe( + "zip", + ); + expect(whole(join([0x1f, 0x8b, 0x08, 0]))).toEqual({ + mime: "application/gzip", + ext: "gz", + }); + expect(whole(text("\n")).ext).toBe("html"); + expect(whole(text("{\\rtf1 hello}")).ext).toBe("rtf"); +}); + +it("stores unsniffable text as an opaque download", () => { + for (const sample of ['{"a":1}', "a,b\n1,2\n", "plain words\n"]) + expect(whole(text(sample))).toEqual({ + mime: "application/octet-stream", + ext: "bin", + }); +}); + +it("treats an ISO media file as video, and only MP4 brands as supported", () => { + const box = (brand: string, compatible: string) => + join([0, 0, 0, 0x18], "ftyp", brand, [0, 0, 2, 0], compatible); + expect(whole(box("isom", "isomiso2"))).toEqual({ + mime: "video/mp4", + ext: "mp4", + }); + expect(() => whole(box("heic", "mif1heic"))).toThrow(UNSUPPORTED_FILE); + expect(() => whole(box("qt ", "qt qt "))).toThrow(UNSUPPORTED_FILE); +}); + +it("refuses what the relay refuses or stores outside the table", () => { + for (const sample of [ + join("fLaC", [0, 0, 0, 0]), + join("OggS", [0, 2, 0, 0]), + join("RIFF", [0, 0, 0, 0], "WAVEfmt "), + join("BM", [0, 0, 0, 0]), + join("MZ", [0x90, 0]), + text(""), + text("#!/bin/sh\necho hi\n"), + // The relay's sniff reads a leading "BC" as LLVM bitcode. + text("BC,123\n"), + ]) + expect(() => whole(sample)).toThrow(UNSUPPORTED_FILE); +}); + +it("needs exactly the file's first bytes, and refuses a type that depends on later ones", () => { + const png = join([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + expect(() => relayMediaType(png, 100)).toThrow("first 4096 bytes"); + const big = new Uint8Array(SNIFF_BYTES); + big.set(png); + expect(relayMediaType(big, 10_000_000).ext).toBe("png"); + // An OOXML package whose folder entry lies past the sniffed prefix. + const ooxml = new Uint8Array(SNIFF_BYTES); + ooxml.set(zipEntry("[Content_Types].xml")); + expect(() => relayMediaType(ooxml, 1_000_000)).toThrow(UNSUPPORTED_FILE); +}); diff --git a/src/features/conversation-import/relay-media-type.ts b/src/features/conversation-import/relay-media-type.ts new file mode 100644 index 0000000000..071bd2657b --- /dev/null +++ b/src/features/conversation-import/relay-media-type.ts @@ -0,0 +1,778 @@ +/** The type and extension the relay stores an attachment under, decided as + * the relay decides it: by sniffing the bytes (the `infer` crate's matchers, + * in its order), never by the declared type. Only the first 4096 bytes are + * needed; a file whose type depends on later bytes is reported unsupported. */ + +export const SNIFF_BYTES = 4096; + +export const UNSUPPORTED_FILE = + "This file type cannot be imported as an attachment."; + +/** Sniffed types the relay stores, with their extensions. Unsniffable files + * (plain text, CSV, JSON) are stored as `application/octet-stream` and `bin`. */ +export const MEDIA_EXTENSIONS: Readonly> = { + "image/jpeg": "jpg", + "image/png": "png", + "image/gif": "gif", + "image/webp": "webp", + "video/mp4": "mp4", + "application/pdf": "pdf", + "application/msword": "doc", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": + "docx", + "application/vnd.ms-excel": "xls", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx", + "application/vnd.ms-powerpoint": "ppt", + "application/vnd.openxmlformats-officedocument.presentationml.presentation": + "pptx", + "application/vnd.oasis.opendocument.text": "odt", + "application/vnd.oasis.opendocument.spreadsheet": "ods", + "application/vnd.oasis.opendocument.presentation": "odp", + "application/rtf": "rtf", + "application/epub+zip": "epub", + "application/zip": "zip", + "application/gzip": "gz", + "application/x-tar": "tar", + "application/x-7z-compressed": "7z", + "application/vnd.rar": "rar", + "application/x-bzip2": "bz2", + "application/x-xz": "xz", + "application/zstd": "zst", + "text/html": "html", +}; + +const IMAGE_PATH = new Set([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp", +]); + +const UNKNOWN = Symbol("unknown"); + +/** A file prefix that reads as the whole file's length; reading past the + * prefix means the answer depends on bytes we do not have. */ +type Bytes = { readonly length: number; at(index: number): number }; + +function bytes(head: Uint8Array, length: number, offset = 0): Bytes { + return { + length: Math.max(0, length - offset), + at(index) { + const i = index + offset; + if (i < head.length) return head[i] as number; + throw UNKNOWN; + }, + }; +} + +const slice = (buf: Bytes, start: number): Bytes => ({ + length: Math.max(0, buf.length - start), + at: (index) => buf.at(index + start), +}); + +/** `compare_bytes`: in range and equal, read in order. */ +function eq(buf: Bytes, offset: number, expected: string | readonly number[]) { + const values = + typeof expected === "string" + ? [...expected].map((char) => char.charCodeAt(0)) + : expected; + if (buf.length < offset + values.length) return false; + return values.every((value, i) => buf.at(offset + i) === value); +} + +const u32le = (buf: Bytes, at: number) => + (buf.at(at) | + (buf.at(at + 1) << 8) | + (buf.at(at + 2) << 16) | + (buf.at(at + 3) << 24)) >>> + 0; +const u32be = (buf: Bytes, at: number) => + ((buf.at(at) << 24) | + (buf.at(at + 1) << 16) | + (buf.at(at + 2) << 8) | + buf.at(at + 3)) >>> + 0; + +const ZIP = [0x50, 0x4b, 0x03, 0x04]; +const OLE = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]; + +function zipSearch(buf: Bytes, start: number, range: number) { + const end = Math.min(start + range, buf.length); + for (let i = start; i + 4 <= end; i++) if (eq(buf, i, ZIP)) return i - start; + return undefined; +} + +function ooxmlFolder(buf: Bytes, offset: number) { + if (eq(buf, offset, "word/")) return "docx"; + if (eq(buf, offset, "ppt/")) return "pptx"; + if (eq(buf, offset, "xl/")) return "xlsx"; + return undefined; +} + +function msooxml(buf: Bytes) { + if (!eq(buf, 0, ZIP)) return undefined; + const first = ooxmlFolder(buf, 0x1e); + if (first) return first; + if ( + !eq(buf, 0x1e, "[Content_Types].xml") && + !eq(buf, 0x1e, "_rels/.rels") && + !eq(buf, 0x1e, "docProps") + ) + return undefined; + let start = u32le(buf, 18) + 49; + if (start > 0xffffffff) return undefined; + let index = zipSearch(buf, start, 6000); + if (index === undefined) return undefined; + start += index + 4 + 26; + index = zipSearch(buf, start, 6000); + if (index === undefined) return undefined; + start += index + 4 + 26; + if (!ooxmlFolder(buf, start)) return undefined; + start += 26; + index = zipSearch(buf, start, 6000); + if (index === undefined) return "ooxml"; + start += index + 4 + 26; + return ooxmlFolder(buf, start) ?? "ooxml"; +} + +/** The root storage CLSID of a compound file, read where the header places + * the first directory sector. */ +function ole2(buf: Bytes) { + if (!eq(buf, 0, OLE)) return undefined; + const shift = buf.at(0x1e) | (buf.at(0x1f) << 8); + if (shift !== 9 && shift !== 12) return undefined; + const sector = u32le(buf, 0x30); + const entry = (sector + 1) * 2 ** shift; + if (!Number.isSafeInteger(entry) || buf.length < entry + 128) + return undefined; + if (buf.at(entry + 0x42) !== 5) return undefined; + const hex = (from: number, count: number, reverse: boolean) => { + const out: string[] = []; + for (let i = 0; i < count; i++) + out.push( + buf + .at(entry + 0x50 + from + i) + .toString(16) + .padStart(2, "0"), + ); + return (reverse ? out.reverse() : out).join(""); + }; + const clsid = `${hex(0, 4, true)}-${hex(4, 2, true)}-${hex(6, 2, true)}-${hex(8, 2, false)}-${hex(10, 6, false)}`; + if ( + clsid === "00020810-0000-0000-c000-000000000046" || + clsid === "00020820-0000-0000-c000-000000000046" + ) + return "xls"; + if (clsid === "00020906-0000-0000-c000-000000000046") return "doc"; + if (clsid === "64818d10-4f9b-11cf-86ea-00aa00b929e8") return "ppt"; + return undefined; +} + +function skippableFrames(buf: Bytes, magic: (buf: Bytes) => boolean): boolean { + if (magic(buf)) return true; + if (buf.length < 8) return false; + if ((u32le(buf, 0) & 0xfffffff0) >>> 0 !== 0x184d2a50) return false; + const length = u32le(buf, 4); + if (buf.length < 8 + length) return false; + return skippableFrames(slice(buf, 8 + length), magic); +} + +function trimmed(buf: Bytes) { + let start = 0; + while (start < buf.length && [9, 10, 12, 13, 32].includes(buf.at(start))) + start++; + return slice(buf, start); +} + +function startsWithIgnoreCase(buf: Bytes, needle: string) { + if (buf.length < needle.length) return false; + for (let i = 0; i < needle.length; i++) { + const a = buf.at(i); + const lower = a >= 0x41 && a <= 0x5a ? a + 32 : a; + if (lower !== needle.toLowerCase().charCodeAt(i)) return false; + } + return true; +} + +const HTML = [ + "= header + 8 ? [header, end] : undefined; +} + +const MP4_BRANDS = [ + "isom", + "iso2", + "iso3", + "iso4", + "iso5", + "iso6", + "iso7", + "iso8", + "iso9", + "mp41", + "mp42", + "avc1", + "dash", + "M4V ", +]; + +function looksLikeMp4(buf: Bytes) { + const payload = isoBmffPayload(buf); + if (!payload) return false; + const [start, end] = payload; + if (MP4_BRANDS.some((brand) => eq(buf, start, brand))) return true; + for (let at = start + 8; at + 4 <= end; at += 4) + if (MP4_BRANDS.some((brand) => eq(buf, at, brand))) return true; + return false; +} + +const MP4_FTYP = [ + "avc1", + "dash", + "iso2", + "iso3", + "iso4", + "iso5", + "iso6", + "isom", + "mmp4", + "mp41", + "mp42", + "mp4v", + "mp71", + "MSNV", + "NDAS", + "NDSC", + "NSDC", + "NDSH", + "NDSM", + "NDSP", + "NDSS", + "NDXC", + "NDXH", + "NDXM", + "NDXP", + "NDXS", + "F4V ", + "F4P ", +]; + +function ftypBrands(buf: Bytes) { + if (buf.length < 16 || !eq(buf, 4, "ftyp")) return undefined; + const length = u32be(buf, 0); + if (buf.length < length) return undefined; + const brands: string[] = []; + const count = Math.max(0, Math.floor(length / 4) - 4); + for (let i = 0; i < count && 16 + i * 4 + 4 <= buf.length; i++) + brands.push( + String.fromCharCode( + buf.at(16 + i * 4), + buf.at(17 + i * 4), + buf.at(18 + i * 4), + buf.at(19 + i * 4), + ), + ); + const major = String.fromCharCode( + buf.at(8), + buf.at(9), + buf.at(10), + buf.at(11), + ); + return { major, brands }; +} + +const is = + (length: number, offset: number, expected: string | number[]) => + (buf: Bytes) => + buf.length > length && eq(buf, offset, expected); + +/** `infer::get`'s matchers in its order. */ +const MATCHERS: readonly (readonly [string, (buf: Bytes) => boolean])[] = [ + [ + "application/wasm", + (b) => b.length >= 8 && eq(b, 0, [0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]), + ], + ["application/x-executable", is(52, 0, [0x7f, 0x45, 0x4c, 0x46])], + ["application/vnd.microsoft.portable-executable", is(1, 0, "MZ")], + [ + "application/java", + (b) => + b.length >= 8 && + eq(b, 0, [0xca, 0xfe, 0xba, 0xbe]) && + u32be(b, 4) >= 45 && + ((b.at(6) << 8) | b.at(7)) >= 45, + ], + ["application/x-llvm", (b) => b.length >= 2 && eq(b, 0, "BC")], + [ + "application/x-mach-binary", + (b) => { + if (b.length < 4) return false; + const [w, x, y, z] = [b.at(0), b.at(1), b.at(2), b.at(3)]; + if ((w === 0xcf || w === 0xce) && x === 0xfa && y === 0xed && z === 0xfe) + return true; + if (w === 0xfe && x === 0xed && y === 0xfa && (z === 0xcf || z === 0xce)) + return true; + return ( + w === 0xca && + x === 0xfe && + y === 0xba && + z === 0xbe && + b.length >= 8 && + u32be(b, 4) < 45 + ); + }, + ], + [ + "application/vnd.android.dex", + (b) => b.length > 36 && eq(b, 0, "dex\n") && b.at(36) === 0x70, + ], + [ + "application/vnd.android.dey", + (b) => + b.length > 100 && + eq(b, 0, "dey\n") && + (() => { + const inner: Bytes = { length: 60, at: (i) => b.at(40 + i) }; + return ( + inner.length > 36 && eq(inner, 0, "dex\n") && inner.at(36) === 0x70 + ); + })(), + ], + ["application/x-x509-ca-cert", is(2, 0, [0x30, 0x82])], + [ + "application/x-executable", + (b) => + b.length > 2 && + (eq(b, 0, [0x64, 0x86]) || + eq(b, 0, [0x4c, 0x01]) || + eq(b, 0, [0x00, 0x02])), + ], + ["application/x-x509-ca-cert", is(11, 0, "-----BEGIN ")], + [ + "application/epub+zip", + (b) => + b.length > 57 && + eq(b, 0, ZIP) && + eq(b, 30, "mimetypeapplication/epub+zip"), + ], + [ + "application/x-mobipocket-ebook", + (b) => b.length > 67 && eq(b, 60, "BOOKMOBI"), + ], + ["image/jpeg", is(2, 0, [0xff, 0xd8, 0xff])], + [ + "image/jp2", + is(12, 0, [0, 0, 0, 0xc, 0x6a, 0x50, 0x20, 0x20, 0xd, 0xa, 0x87, 0xa, 0]), + ], + ["image/png", is(3, 0, [0x89, 0x50, 0x4e, 0x47])], + ["image/gif", is(2, 0, "GIF")], + ["image/webp", is(11, 8, "WEBP")], + [ + "image/x-canon-cr2", + (b) => + b.length > 10 && + (eq(b, 0, [0x49, 0x49, 0x2a, 0]) || eq(b, 0, [0x4d, 0x4d, 0, 0x2a])) && + eq(b, 8, [0x43, 0x52, 0x02]), + ], + [ + "image/tiff", + (b) => + b.length > 9 && + (eq(b, 0, [0x49, 0x49, 0x2a, 0]) || eq(b, 0, [0x4d, 0x4d, 0, 0x2a])) && + b.at(8) !== 0x43 && + b.at(9) !== 0x52, + ], + ["image/bmp", is(1, 0, "BM")], + ["image/vnd.ms-photo", is(2, 0, [0x49, 0x49, 0xbc])], + ["image/vnd.adobe.photoshop", is(3, 0, "8BPS")], + ["image/vnd.microsoft.icon", is(3, 0, [0, 0, 1, 0])], + [ + "image/heif", + (b) => { + const ftyp = ftypBrands(b); + if (!ftyp) return false; + if (ftyp.major === "heic" || ftyp.major === "heix") return true; + return ( + (ftyp.major === "mif1" || ftyp.major === "msf1") && + ftyp.brands.includes("heic") + ); + }, + ], + [ + "image/avif", + (b) => { + const ftyp = ftypBrands(b); + if (!ftyp) return false; + return ( + ["avif", "avis"].includes(ftyp.major) || + ftyp.brands.some((brand) => brand === "avif" || brand === "avis") + ); + }, + ], + [ + "image/jxl", + (b) => + (b.length > 2 && eq(b, 0, [0xff, 0x0a])) || + (b.length > 12 && + eq( + b, + 0, + [0, 0, 0, 0x0c, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a], + )), + ], + [ + "image/openraster", + (b) => + b.length > 57 && eq(b, 0, ZIP) && eq(b, 30, "mimetypeimage/openraster"), + ], + [ + "image/vnd.djvu", + (b) => b.length > 14 && eq(b, 0, "AT&TFORM") && eq(b, 12, "DJV"), + ], + [ + "video/mp4", + (b) => + b.length > 11 && + eq(b, 4, "ftyp") && + MP4_FTYP.some((brand) => eq(b, 8, brand)), + ], + ["video/x-m4v", is(10, 4, "ftypM4V")], + [ + "video/x-matroska", + (b) => + (b.length > 15 && + eq(b, 0, [ + 0x1a, + 0x45, + 0xdf, + 0xa3, + 0x93, + 0x42, + 0x82, + 0x88, + ...[..."matroska"].map((c) => c.charCodeAt(0)), + ])) || + (b.length > 38 && eq(b, 31, "matroska")), + ], + ["video/webm", is(3, 0, [0x1a, 0x45, 0xdf, 0xa3])], + [ + "video/quicktime", + (b) => + b.length > 15 && + ((eq(b, 4, "ftyp") && eq(b, 8, "qt ")) || + eq(b, 4, "moov") || + eq(b, 4, "mdat") || + eq(b, 12, "mdat")), + ], + [ + "video/x-msvideo", + (b) => b.length > 10 && eq(b, 0, "RIFF") && eq(b, 8, "AVI"), + ], + [ + "video/x-ms-wmv", + is(9, 0, [0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66, 0xcf, 0x11, 0xa6, 0xd9]), + ], + [ + "video/mpeg", + (b) => + b.length > 3 && eq(b, 0, [0, 0, 1]) && b.at(3) >= 0xb0 && b.at(3) <= 0xbf, + ], + ["video/x-flv", is(3, 0, [0x46, 0x4c, 0x56, 0x01])], + ["audio/midi", is(3, 0, "MThd")], + [ + "audio/mpeg", + (b) => b.length > 2 && (eq(b, 0, "ID3") || eq(b, 0, [0xff, 0xfb])), + ], + [ + "audio/m4a", + (b) => b.length > 10 && (eq(b, 4, "ftypM4A") || eq(b, 0, "M4A ")), + ], + [ + "audio/opus", + (b) => + b.length > 3 && + eq(b, 0, "OggS") && + b.length > 35 && + eq(b, 28, "OpusHead"), + ], + ["audio/ogg", is(3, 0, "OggS")], + ["audio/x-flac", is(3, 0, "fLaC")], + ["audio/x-wav", (b) => b.length > 11 && eq(b, 0, "RIFF") && eq(b, 8, "WAVE")], + ["audio/amr", is(11, 0, "#!AMR\n")], + [ + "audio/aac", + (b) => + b.length > 1 && + b.at(0) === 0xff && + (b.at(1) === 0xf1 || b.at(1) === 0xf9), + ], + [ + "audio/x-aiff", + (b) => b.length > 11 && eq(b, 0, "FORM") && eq(b, 8, "AIFF"), + ], + ["audio/x-dsf", is(4, 0, "DSD ")], + ["audio/x-ape", is(4, 0, "MAC ")], + ["application/font-woff", is(7, 0, [0x77, 0x4f, 0x46, 0x46, 0, 1, 0, 0])], + ["application/font-woff", is(7, 0, [0x77, 0x4f, 0x46, 0x32, 0, 1, 0, 0])], + ["application/font-sfnt", is(4, 0, [0, 1, 0, 0, 0])], + ["application/font-sfnt", is(4, 0, [0x4f, 0x54, 0x54, 0x4f, 0])], + ["application/msword", (b) => ole2(b) === "doc"], + [ + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + (b) => msooxml(b) === "docx", + ], + ["application/vnd.ms-excel", (b) => ole2(b) === "xls"], + [ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + (b) => msooxml(b) === "xlsx", + ], + ["application/vnd.ms-powerpoint", (b) => ole2(b) === "ppt"], + [ + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + (b) => msooxml(b) === "pptx", + ], + [ + "application/vnd.oasis.opendocument.text", + (b) => + eq(b, 0, ZIP) && + eq(b, 0x1e, "mimetype") && + eq(b, 0x32, "vnd.oasis.opendocument.text"), + ], + [ + "application/vnd.oasis.opendocument.spreadsheet", + (b) => + eq(b, 0, ZIP) && + eq(b, 0x1e, "mimetype") && + !eq(b, 0x32, "vnd.oasis.opendocument.text") && + eq(b, 0x32, "vnd.oasis.opendocument.spreadsheet"), + ], + [ + "application/vnd.oasis.opendocument.presentation", + (b) => + eq(b, 0, ZIP) && + eq(b, 0x1e, "mimetype") && + !eq(b, 0x32, "vnd.oasis.opendocument.text") && + !eq(b, 0x32, "vnd.oasis.opendocument.spreadsheet") && + eq(b, 0x32, "vnd.oasis.opendocument.presentation"), + ], + [ + "application/epub+zip", + (b) => + b.length > 57 && + eq(b, 0, ZIP) && + eq(b, 30, "mimetypeapplication/epub+zip"), + ], + [ + "application/zip", + (b) => + b.length > 3 && + b.at(0) === 0x50 && + b.at(1) === 0x4b && + ((b.at(2) === 3 && b.at(3) === 4) || + (b.at(2) === 5 && b.at(3) === 6) || + (b.at(2) === 7 && b.at(3) === 8) || + (b.length > 7 && eq(b, 2, [0x30, 0x30, 0x50, 0x4b, 3, 4]))), + ], + ["application/x-tar", (b) => b.length > 261 && eq(b, 257, "ustar")], + ["application/x-par2", is(8, 0, "PAR2\0PKT")], + [ + "application/vnd.rar", + (b) => + b.length > 6 && + eq(b, 0, [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07]) && + (b.at(6) === 0 || b.at(6) === 1), + ], + ["application/gzip", is(2, 0, [0x1f, 0x8b, 0x08])], + ["application/x-bzip2", is(2, 0, "BZh")], + ["application/vnd.bzip3", is(4, 0, "BZ3v1")], + [ + "application/x-7z-compressed", + is(5, 0, [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c]), + ], + ["application/x-xz", is(5, 0, [0xfd, 0x37, 0x7a, 0x58, 0x5a, 0])], + ["application/pdf", is(3, 0, "%PDF")], + [ + "application/x-shockwave-flash", + (b) => + b.length > 2 && (b.at(0) === 0x43 || b.at(0) === 0x46) && eq(b, 1, "WS"), + ], + ["application/rtf", is(4, 0, "{\\rtf")], + [ + "application/octet-stream", + (b) => + b.length > 35 && + eq(b, 34, "LP") && + (eq(b, 8, [2, 0, 1]) || eq(b, 8, [1, 0, 0]) || eq(b, 8, [2, 0, 2])), + ], + ["application/postscript", is(1, 0, "%!")], + ["application/vnd.sqlite3", is(3, 0, "SQLi")], + ["application/x-nintendo-nes-rom", is(3, 0, [0x4e, 0x45, 0x53, 0x1a])], + ["application/x-google-chrome-extension", is(3, 0, "Cr24")], + [ + "application/vnd.ms-cab-compressed", + (b) => b.length > 3 && (eq(b, 0, "MSCF") || eq(b, 0, "ISc(")), + ], + [ + "application/vnd.debian.binary-package", + is(20, 0, "!\ndebian-binary"), + ], + ["application/x-unix-archive", is(6, 0, "!")], + [ + "application/x-compress", + (b) => + b.length > 1 && + b.at(0) === 0x1f && + (b.at(1) === 0xa0 || b.at(1) === 0x9d), + ], + ["application/x-lzip", is(3, 0, "LZIP")], + ["application/x-rpm", is(96, 0, [0xed, 0xab, 0xee, 0xdb])], + ["application/dicom", is(131, 128, "DICM")], + [ + "application/zstd", + (b) => + skippableFrames( + b, + (f) => f.length > 3 && eq(f, 0, [0x28, 0xb5, 0x2f, 0xfd]), + ), + ], + [ + "application/x-lz4", + (b) => + skippableFrames( + b, + (f) => f.length > 3 && eq(f, 0, [0x04, 0x22, 0x4d, 0x18]), + ), + ], + ["application/x-ole-storage", is(7, 0, OLE)], + [ + "application/x-cpio", + (b) => + (b.length > 1 && + ((b.at(0) === 0xc7 && b.at(1) === 0x71) || + (b.at(0) === 0x71 && b.at(1) === 0xc7))) || + (b.length > 6 && eq(b, 0, "070701")), + ], + [ + "text/html", + (b) => { + const rest = trimmed(b); + return HTML.some( + (tag) => + startsWithIgnoreCase(rest, tag) && + rest.length > tag.length && + [0x20, 0x3e].includes(rest.at(tag.length)), + ); + }, + ], + [ + "text/xml", + (b) => { + let rest = trimmed(b); + for (;;) { + if (rest.length < 3) break; + if (eq(rest, 0, [0xef, 0xbb, 0xbf])) rest = slice(rest, 3); + else if (eq(rest, 0, [0xfe, 0xff]) || eq(rest, 0, [0xff, 0xfe])) + rest = slice(rest, 2); + else break; + } + return startsWithIgnoreCase(rest, " b.length > 2 && eq(b, 0, "#!")], +]; + +function infer(buf: Bytes) { + for (const [mime, matches] of MATCHERS) if (matches(buf)) return mime; + return undefined; +} + +const BLOCKED = new Set([ + "application/xhtml+xml", + "image/svg+xml", + "application/javascript", + "text/javascript", + "application/x-msdownload", + "application/x-executable", + "application/vnd.microsoft.portable-executable", + "application/x-mach-binary", + "application/x-sharedlib", + "application/x-elf", + "application/x-msi", + "application/vnd.android.package-archive", + "application/x-apple-diskimage", +]); + +function decide(head: Uint8Array, size: number) { + const sniff = bytes(head, head.length); + if (infer(sniff) === "video/mp4" || isoBmffPayload(sniff)) + return looksLikeMp4(sniff) ? "video/mp4" : undefined; + const whole = bytes(head, size); + const mime = infer(whole); + if (mime && IMAGE_PATH.has(mime)) return mime; + if (isoBmffPayload(whole)) return undefined; + if (!mime) return "application/octet-stream"; + if (/^(image|video|audio)\//.test(mime) || BLOCKED.has(mime)) return; + return mime in MEDIA_EXTENSIONS ? mime : undefined; +} + +/** `head` is the file's first `SNIFF_BYTES` bytes, or the whole file when + * shorter. Throws `UNSUPPORTED_FILE` for a type the relay refuses or stores + * under an extension outside `MEDIA_EXTENSIONS`. */ +export function relayMediaType(head: Uint8Array, size: number) { + if (!(head instanceof Uint8Array)) + throw new Error("The file head must be the file's first bytes."); + if (!Number.isSafeInteger(size) || size < 1) + throw new Error("The file size must be a positive whole number of bytes."); + if (head.length !== Math.min(size, SNIFF_BYTES)) + throw new Error( + `The file head must be the first ${SNIFF_BYTES} bytes, or the whole file when shorter.`, + ); + let mime: string | undefined; + try { + mime = decide(head, size); + } catch (error) { + if (error !== UNKNOWN) throw error; + mime = undefined; + } + if (!mime) throw new Error(UNSUPPORTED_FILE); + return { + mime, + ext: MEDIA_EXTENSIONS[mime] ?? "bin", + } as const; +} diff --git a/src/features/conversation-import/reviews.ts b/src/features/conversation-import/reviews.ts new file mode 100644 index 0000000000..9a75a1aed9 --- /dev/null +++ b/src/features/conversation-import/reviews.ts @@ -0,0 +1,92 @@ +import type { VerifiedProfileView } from "./types"; + +export type ReviewMember = Readonly<{ + pubkey: string; + verified?: VerifiedProfileView; + /** Shown beside the member, such as a message count. */ + note?: string; +}>; + +export type ImportReview = Readonly<{ + id: string; + type: "propose" | "consent" | "direct-message" | "channel"; + title: string; + description: string; + facts: readonly Readonly<{ label: string; value: string }>[]; + members: readonly ReviewMember[]; + /** A statement the person confirms by approving. */ + statement?: string; + /** Why this request cannot be approved. The dialog then offers no approval. */ + refusal?: string; + confirmLabel: string; + destructive?: boolean; +}>; + +const issued = new WeakSet(); + +/** Whether `value` came from `createImportReviews`, not a lookalike. */ +export function isImportReviews(value: unknown): value is ImportReviews { + return typeof value === "object" && value !== null && issued.has(value); +} + +/** The human gate for conversation import. Requests resolve only from the + * host-mounted dialog; plugins never receive this object. */ +export function createImportReviews() { + type Pending = { review: ImportReview; resolve(approved: boolean): void }; + let queue: readonly Pending[] = []; + let snapshot: readonly ImportReview[] = []; + const listeners = new Set<() => void>(); + const publish = (next: readonly Pending[]) => { + queue = next; + snapshot = Object.freeze(next.map((item) => item.review)); + for (const listener of [...listeners]) listener(); + }; + const settle = (id: string, approved: boolean) => { + const item = queue.find((entry) => entry.review.id === id); + if (!item) return; + publish(queue.filter((entry) => entry !== item)); + item.resolve(approved && !item.review.refusal); + }; + const reviews = Object.freeze({ + snapshot: () => snapshot, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + /** Resolves true only when the person approves this exact request. */ + request( + review: Omit, + signal?: AbortSignal, + ): Promise { + signal?.throwIfAborted(); + const id = crypto.randomUUID(); + return new Promise((resolve) => { + const abort = () => settle(id, false); + signal?.addEventListener("abort", abort, { once: true }); + publish([ + ...queue, + { + review: Object.freeze({ ...review, id }), + resolve: (approved) => { + signal?.removeEventListener("abort", abort); + resolve(approved); + }, + }, + ]); + }); + }, + approve: (id: string) => settle(id, true), + dismiss: (id: string) => settle(id, false), + dispose() { + for (const item of queue) item.resolve(false); + publish([]); + listeners.clear(); + }, + }); + issued.add(reviews); + return reviews; +} + +export type ImportReviews = ReturnType; diff --git a/src/features/conversation-import/service.test.ts b/src/features/conversation-import/service.test.ts new file mode 100644 index 0000000000..f0b44b09f8 --- /dev/null +++ b/src/features/conversation-import/service.test.ts @@ -0,0 +1,1318 @@ +import { Context } from "@deepseek-ai/cordis"; +import { getEventHash } from "nostr-tools"; +import { afterEach, expect, it, vi } from "vitest"; +import { eventDto, type RelayEvent, type ReadFilter } from "../relay/events"; +import { registerImportWriter } from "../relay/import-writes"; +import type { OutgoingEvent } from "../relay/outbox"; +import type { RelayData } from "../relay/service"; +import { keypair, signed } from "../relay/testing"; +import { proposalTemplate } from "./protocol"; +import { createImportReviews, type ImportReview } from "./reviews"; +import { createConversationImportHost } from "./service"; +import type { + ConversationImportService, + ImportProposalInput, + PreparedImportEvent, +} from "./types"; + +const authority = keypair(); +const viewer = "a".repeat(64); +const partner = "b".repeat(64); +const outsider = "9".repeat(64); +const channel = "f0".repeat(16); +const now = 1_740_000_000; +const origin = "https://relay.example"; + +const proposalInput: ImportProposalInput = { + channelId: channel, + source: { + type: "slack", + conversation: "e".repeat(64), + kind: "dm", + label: "Direct message", + }, + range: { from: 1_735_689_600, to: 1_735_776_000 }, + participants: [ + { pubkey: viewer, source_user: "2".repeat(64), messages: 3, reactions: 0 }, + { pubkey: partner, source_user: "3".repeat(64), messages: 1, reactions: 0 }, + ], + excluded_authors: 0, + manifest: "d".repeat(64), + expires_at: now + 86_400, +}; + +function stamp( + pubkey: string, + template: { kind: number; content: string; tags: string[][] }, + created_at = now - 60, +) { + const unsigned = { ...template, pubkey, created_at }; + return { + ...unsigned, + id: getEventHash(unsigned), + sig: "0".repeat(128), + } as RelayEvent; +} + +function proposalFor(kind: ImportProposalInput["source"]["kind"]) { + return stamp( + viewer, + proposalTemplate({ + ...proposalInput, + source: { ...proposalInput.source, kind }, + }), + ); +} + +const proposal = proposalFor("dm"); + +function verifiedRecord(pubkey: string, username: string, displayName: string) { + return eventDto( + signed(authority, { + kind: 30382, + content: "", + tags: [ + ["d", pubkey], + ["p", pubkey], + ["active", "true"], + ["display_name", displayName], + ["username", username], + ["issuer_label", "Example Directory"], + ["verified_at", "1699999000"], + ], + }), + ); +} + +function snapshotRecord(proposalId: string, status: string) { + return eventDto( + signed(authority, { + kind: 30623, + content: JSON.stringify({ + v: 1, + status, + required: [viewer, partner], + consents: { [viewer]: "accept", [partner]: "accept" }, + published: {}, + completed: [], + expires_at: now + 86_400, + }), + tags: [ + ["d", proposalId], + ["e", proposalId], + ["h", channel], + ["p", viewer], + ["p", partner], + ], + }), + ); +} + +function rosterRecord(channelId: string, members: readonly string[]) { + return eventDto( + signed(authority, { + kind: 39002, + content: "", + tags: [["d", channelId], ...members.map((key) => ["p", key])], + }), + ); +} + +type Decision = Pick & { + error?: string; + reason?: string; +}; + +type Channel = { + id: string; + name: string; + channelType: "dm" | "stream" | "forum"; + members: string[]; + archived: boolean; + visibility?: "private" | "public"; + viewerRole?: string; +}; + +function setup( + options: { + verified?: readonly string[]; + status?: string; + proposal?: RelayEvent; + decide?: (event: RelayEvent) => Decision | Promise; + existing?: (id: string, reads: number) => boolean; + supported?: boolean; + channel?: Partial; + roster?: (channelId: string) => readonly string[] | undefined; + } = {}, +) { + const current = options.proposal ?? proposal; + const items: OutgoingEvent[] = []; + const listeners = new Set<() => void>(); + const notify = () => { + for (const listener of [...listeners]) listener(); + }; + const decide = options.decide ?? (() => ({ delivery: "accepted" as const })); + const settle = (event: RelayEvent) => { + queueMicrotask(async () => { + const outcome = await decide(event); + const index = items.findIndex((item) => item.event.id === event.id); + if (index < 0) return; + items[index] = { ...(items[index] as OutgoingEvent), ...outcome }; + notify(); + }); + }; + const enqueue = (event: RelayEvent) => { + if (items.some((item) => item.event.id === event.id)) return event.id; + items.push({ event, delivery: "sending" } as OutgoingEvent); + settle(event); + return event.id; + }; + const sent: RelayEvent[] = []; + const records: RelayEvent[] = []; + const writer = { + sendAt: vi.fn((input: PreparedImportEvent) => { + const event = stamp( + viewer, + { ...input, tags: input.tags.map((tag) => [...tag]) }, + input.created_at, + ); + sent.push(event); + return enqueue(event); + }), + sendRecord: vi.fn( + (input: { kind: number; content: string; tags: string[][] }) => { + const event = stamp(viewer, input, now); + records.push(event); + return enqueue(event); + }, + ), + retry: vi.fn((id: string) => { + const item = items.find((entry) => entry.event.id === id); + if (item) { + Object.assign(item, { delivery: "sending" }); + settle(item.event as RelayEvent); + } + }), + dismiss: vi.fn(async (id: string) => { + const index = items.findIndex((item) => item.event.id === id); + if (index >= 0) items.splice(index, 1); + notify(); + }), + local: { + snapshot: () => items, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }, + }; + const verified = options.verified ?? [viewer, partner]; + const target: Channel = { + id: channel, + name: "dm", + channelType: "dm", + members: [viewer, partner], + archived: false, + ...options.channel, + }; + const channels: Channel[] = [target]; + const parentReads = new Map(); + const snapshotRead = vi.fn(async (filters: readonly ReadFilter[]) => { + const filter = filters[0] as ReadFilter & Record; + if (filter.kinds?.includes(30382)) + return verified + .filter((key) => (filter["#d"] as string[]).includes(key)) + .map((key) => + verifiedRecord( + key, + key === viewer ? "viewer" : "partner", + key === viewer ? "Viewer Person" : "Partner Person", + ), + ); + if (filter.kinds?.includes(30623)) + return options.status + ? [snapshotRecord((filter["#d"] as string[])[0] ?? "", options.status)] + : []; + if (filter.kinds?.includes(39002)) { + const id = (filter["#d"] as string[])[0] ?? ""; + const members = + options.roster?.(id) ?? + channels.find((item) => item.id === id)?.members; + return members ? [rosterRecord(id, members)] : []; + } + if (filter.ids?.includes(current.id)) return [current]; + if (filter.kinds?.includes(42110)) return [current]; + if (filter.kinds?.includes(9)) return []; + const id = filter.ids?.[0]; + if (id) { + const reads = (parentReads.get(id) ?? 0) + 1; + parentReads.set(id, reads); + return options.existing?.(id, reads) + ? [ + stamp(partner, { kind: 9, content: "x", tags: [["h", channel]] }), + ].map((event) => ({ ...event, id })) + : []; + } + return []; + }); + const uploads: File[] = []; + const upload = vi.fn( + async (file: File, _channelId: string, _signal: AbortSignal) => { + uploads.push(file); + return { + name: file.name, + url: `${origin}/media/${"c".repeat(64)}.png`, + type: file.type, + size: file.size, + sha256: "c".repeat(64), + }; + }, + ); + const session = { + viewer, + relayAuthor: authority.pubkey, + scope: `${origin}:${viewer}`, + conversationImport: options.supported ?? true, + snapshotRead, + subscribeLive: () => () => {}, + searchProfiles: vi.fn(async () => []), + channels: { list: () => ({ channels }) }, + profiles: { + snapshot: () => new Map(), + ensure: async () => {}, + subscribe: () => () => {}, + }, + attachments: { upload }, + directMessages: { + open: vi.fn(async () => { + const id = "d0".repeat(16); + channels.push({ + id, + name: "dm", + channelType: "dm", + members: [viewer, outsider], + archived: false, + }); + return id; + }), + }, + channelCreation: { + create: vi.fn(async () => { + const id = "c0".repeat(16); + channels.push({ + id, + name: "imported", + channelType: "stream", + members: [viewer], + archived: false, + visibility: "private", + }); + return id; + }), + }, + memberAdditions: { + add: vi.fn(async (id: string, pubkey: string) => { + channels.find((item) => item.id === id)?.members.push(pubkey); + }), + }, + }; + registerImportWriter(session, writer as never); + const relay = { + snapshot: () => ({ session, status: "ready", viewer }), + subscribe: () => () => {}, + } as unknown as RelayData; + const reviews = createImportReviews(); + const waits: number[] = []; + const expiries: (() => void)[] = []; + const ctx = new Context(); + const service = createConversationImportHost(ctx, relay, reviews, { + now: () => now, + clock: () => 0, + wait: async (ms, signal) => { + waits.push(ms); + // The give-up wait after a stop resolves only when a test expires it. + if (ms === 30_000) + await new Promise((resolve, reject) => { + expiries.push(resolve); + signal?.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }); + }, + }); + contexts.push(ctx); + return { + ctx, + service, + relay, + reviews, + writer, + items, + listeners, + expiries, + sent, + records, + waits, + snapshotRead, + target, + channels, + session, + upload, + uploads, + proposal: current, + }; +} + +const contexts: Context[] = []; +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose(); +}); + +function message( + created_at: number, + ref: string, + parent?: string, + proposalId = proposal.id, +): PreparedImportEvent { + return { + kind: 9, + created_at, + tags: [ + ["h", channel], + ...(parent ? [["e", parent, "", "reply"]] : []), + ["import", proposalId], + ["source", "slack", ref], + ], + content: `Message ${ref}`, + }; +} + +async function nextReview(reviews: ReturnType) { + await vi.waitFor(() => expect(reviews.snapshot()).toHaveLength(1)); + return reviews.snapshot()[0] as ImportReview; +} + +it("computes NIP-01 ids for plugin-derived parents", () => { + const { service } = setup(); + expect( + service.eventId({ + pubkey: viewer, + created_at: 1_735_732_800, + kind: 9, + tags: [ + ["h", channel], + ["import", "1".repeat(64)], + ["source", "slack", "1735732800.000100"], + ], + content: 'Hello "world"\nline two é 😀', + }), + ).toBe("8700e9d79a391c7bde29babf26fd2167e00335bafa08abfc8e21ea34b68268e4"); +}); + +it("gives an injected plugin no path to the host state or dialogs", async () => { + const { ctx, relay, reviews, service } = setup(); + let injected!: ConversationImportService; + await ctx.plugin({ + inject: ["conversationImport"], + apply(plugin: Context) { + injected = plugin.conversationImport; + }, + }); + expect(injected).toBeDefined(); + const reachable = new Set(); + const visit = (value: unknown, depth: number) => { + if (!value || (typeof value !== "object" && typeof value !== "function")) + return; + if (reachable.has(value) || depth > 2) return; + reachable.add(value); + for (const key of Reflect.ownKeys(value)) { + let child: unknown; + try { + child = (value as Record)[key]; + } catch { + continue; + } + visit(child, depth + 1); + } + }; + let object: object | null = injected as object; + while (object && object !== Object.prototype) { + for (const key of Reflect.ownKeys(object)) { + let value: unknown; + try { + value = (injected as unknown as Record)[key]; + } catch { + continue; + } + if (key === "constructor" && typeof value === "function") { + const Host = value as new (...args: unknown[]) => unknown; + const lookalike = { + request: async () => true, + snapshot: () => [], + subscribe: () => () => {}, + }; + const fake = { reflect: { provide() {} }, effect() {} }; + expect(() => new Host(fake, relay, lookalike)).toThrow( + "Conversation import is provided by the host.", + ); + expect(() => new Host(fake, relay, reviews, {})).toThrow( + "Conversation import is provided by the host.", + ); + expect(() => Reflect.construct(Host, [fake, relay, reviews])).toThrow( + "Conversation import is provided by the host.", + ); + } else if (typeof value === "function" && value.length === 0) + try { + visit(Reflect.apply(value, injected, []), 0); + } catch {} + visit(value, 0); + } + object = Object.getPrototypeOf(object); + } + expect(reachable.has(reviews)).toBe(false); + for (const value of reachable) + expect(value && typeof value === "object" && "reviews" in value).toBe( + false, + ); + expect("state" in injected).toBe(false); + expect((service as unknown as { state?: unknown }).state).toBeUndefined(); +}); + +it("publishes paced events in order and reports their ids", async () => { + const { service, sent, waits } = setup({ status: "active" }); + const events = [ + message(1_735_732_800, "1"), + message(1_735_732_801, "2"), + message(1_735_732_802, "3"), + ]; + const progress = vi.fn(); + const report = await service.publish(proposal.id, events, { + onProgress: progress, + }); + expect(report.status).toBe("done"); + expect(report.ids).toEqual(sent.map((event) => event.id)); + expect(report.ids[0]).toBe( + service.eventId({ ...(events[0] as PreparedImportEvent), pubkey: viewer }), + ); + expect(waits).toEqual([125, 125]); + expect(progress).toHaveBeenLastCalledWith({ published: 3, total: 3 }); +}); + +it("stops on the first rejection, surfaces the relay text verbatim and dismisses the refused event", async () => { + let count = 0; + const { service, sent, writer, items } = setup({ + status: "active", + decide: () => + ++count === 2 + ? { + delivery: "failed", + error: "invalid: import per-author message count exceeded", + } + : { delivery: "accepted" }, + }); + const report = await service.publish( + proposal.id, + [ + message(1_735_732_800, "1"), + message(1_735_732_801, "2"), + message(1_735_732_802, "3"), + ], + {}, + ); + expect(report).toMatchObject({ + status: "rejected", + published: 1, + stoppedAt: 1, + reason: "invalid: import per-author message count exceeded", + }); + expect(sent).toHaveLength(2); + expect(writer.dismiss).toHaveBeenCalledWith(sent[1]?.id); + expect(items.map((item) => item.event.id)).toEqual([sent[0]?.id]); +}); + +it("waits out a rate limit and retries through the host writer", async () => { + let count = 0; + const { service, writer, waits } = setup({ + status: "active", + decide: () => + ++count === 1 + ? { delivery: "failed", error: "rate-limited: slow down" } + : { delivery: "accepted" }, + }); + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + ); + expect(report.status).toBe("done"); + expect(writer.retry).toHaveBeenCalledOnce(); + expect(waits).toContain(15_000); +}); + +it("waits for another participant's parent, polling every five seconds", async () => { + const parent = "9".repeat(64); + const { service, waits, sent } = setup({ + status: "active", + existing: (id, reads) => id === parent && reads >= 3, + }); + const progress = vi.fn(); + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1"), message(1_735_732_900, "2", parent)], + { onProgress: progress }, + ); + expect(report.status).toBe("done"); + expect(sent).toHaveLength(2); + expect(waits.filter((ms) => ms === 5_000)).toHaveLength(2); + expect(progress).toHaveBeenCalledWith( + expect.objectContaining({ waitingFor: expect.any(String) }), + ); +}); + +it("rejects events that break the import rules before publishing any", async () => { + const { service, sent } = setup({ status: "active" }); + const bad = { + ...message(1_735_732_801, "2"), + tags: [ + ["h", channel], + ["source", "slack", "2"], + ], + }; + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1"), bad], + {}, + ); + expect(report.status).toBe("rejected"); + expect(report.stoppedAt).toBe(1); + expect(sent).toHaveLength(0); + const future = await service.publish( + proposal.id, + [message(now + 10, "3")], + {}, + ); + expect(future.status).toBe("rejected"); +}); + +it("does not publish when the relay says the session is not active", async () => { + const { service, sent } = setup({ status: "withdrawn" }); + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + ); + expect(report).toMatchObject({ + status: "stopped", + reason: "This import is withdrawn.", + }); + expect(sent).toHaveLength(0); +}); + +it("does not publish without a relay snapshot", async () => { + const { service, sent } = setup(); + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + ); + expect(report).toMatchObject({ + status: "stopped", + published: 0, + reason: "The relay has not confirmed that this import is active.", + }); + expect(sent).toHaveLength(0); +}); + +it("refuses to propose on a relay that does not advertise NIP-CI", async () => { + const { service, reviews, writer } = setup({ supported: false }); + await expect(service.propose(proposalInput)).rejects.toThrow( + "This community's relay does not support conversation import.", + ); + expect(reviews.snapshot()).toHaveLength(0); + expect(writer.sendRecord).not.toHaveBeenCalled(); +}); + +it("refuses consent on a relay that does not advertise NIP-CI", async () => { + const { service, reviews, writer } = setup({ + supported: false, + status: "proposed", + }); + await expect( + service.consent(proposal.id, "accept", "2".repeat(64)), + ).rejects.toThrow( + "This community's relay does not support conversation import.", + ); + expect(reviews.snapshot()).toHaveLength(0); + expect(writer.sendRecord).not.toHaveBeenCalled(); +}); + +it("gives a session's writer only to the first host, and refuses lookalike reviews", async () => { + const { relay, reviews, writer, service } = setup({ status: "proposed" }); + service.membership(channel); + const second = new Context(); + contexts.push(second); + const rival = createConversationImportHost( + second, + relay, + createImportReviews(), + ); + await expect( + rival.consent(proposal.id, "accept", "2".repeat(64)), + ).rejects.toThrow("This connection cannot publish conversation imports."); + expect(writer.sendRecord).not.toHaveBeenCalled(); + expect(reviews.snapshot()).toHaveLength(0); + expect(() => + createConversationImportHost(new Context(), relay, { + ...reviews, + } as typeof reviews), + ).toThrow("Conversation import is provided by the host."); +}); + +it("refuses a proposal when a participant has no verified identity", async () => { + const { service, reviews, writer } = setup({ verified: [viewer] }); + const pending = service.propose(proposalInput); + const review = await nextReview(reviews); + expect(review.type).toBe("propose"); + expect(review.refusal).toMatch("no verified Buzz identity"); + reviews.approve(review.id); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); + expect(writer.sendRecord).not.toHaveBeenCalled(); +}); + +it("refuses a direct message proposal whose participants differ from the members", async () => { + const { service, reviews } = setup(); + const pending = service.propose({ + ...proposalInput, + participants: [proposalInput.participants[0] as never], + }); + const review = await nextReview(reviews); + expect(review.refusal).toBeDefined(); + reviews.dismiss(review.id); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); +}); + +it("refuses private and public channel proposals into the wrong destination", async () => { + const privateSource = { + ...proposalInput, + source: { ...proposalInput.source, kind: "private_channel" as const }, + }; + const wrong = setup({ + channel: { channelType: "stream", visibility: "public", name: "general" }, + }); + const pending = wrong.service.propose(privateSource); + const review = await nextReview(wrong.reviews); + expect(review.refusal).toBe( + "A private channel can only be imported into a private channel.", + ); + wrong.reviews.dismiss(review.id); + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); + + const extra = setup({ + channel: { + channelType: "stream", + visibility: "private", + members: [viewer, partner, outsider], + }, + }); + const extraPending = extra.service.propose(privateSource); + const extraReview = await nextReview(extra.reviews); + expect(extraReview.refusal).toBe( + "One member of the destination is not in the source channel.", + ); + extra.reviews.dismiss(extraReview.id); + await expect(extraPending).rejects.toMatchObject({ name: "AbortError" }); + + const publicSource = { + ...proposalInput, + source: { ...proposalInput.source, kind: "public_channel" as const }, + }; + const closed = setup({ + channel: { channelType: "stream", visibility: "private" }, + }); + const closedPending = closed.service.propose(publicSource); + const closedReview = await nextReview(closed.reviews); + expect(closedReview.refusal).toBe( + "A public channel can only be imported into a public channel.", + ); + closed.reviews.dismiss(closedReview.id); + await expect(closedPending).rejects.toMatchObject({ name: "AbortError" }); + + const open = setup({ + channel: { + channelType: "stream", + visibility: "public", + name: "general", + members: [viewer, partner, outsider], + }, + }); + const openPending = open.service.propose(publicSource); + const openReview = await nextReview(open.reviews); + expect(openReview.refusal).toBeUndefined(); + expect( + openReview.facts.find((fact) => fact.label === "Destination")?.value, + ).toBe("#general (public channel)"); + open.reviews.dismiss(openReview.id); + await expect(openPending).rejects.toMatchObject({ name: "AbortError" }); +}); + +it("publishes a proposal only after the dialog is approved", async () => { + const { service, reviews, writer } = setup(); + const pending = service.propose(proposalInput); + const review = await nextReview(reviews); + expect(review.refusal).toBeUndefined(); + expect(review.members.map((item) => item.verified?.username)).toEqual([ + "viewer", + "partner", + ]); + expect(review.facts.find((fact) => fact.label === "Manifest")?.value).toBe( + "dddddddd dddddddd dddddddd dddddddd dddddddd dddddddd dddddddd dddddddd", + ); + expect(review.facts.find((fact) => fact.label === "Destination")?.value).toBe( + "Direct message with Partner Person", + ); + expect(writer.sendRecord).not.toHaveBeenCalled(); + reviews.approve(review.id); + const { proposalId } = await pending; + expect(writer.sendRecord).toHaveBeenCalledOnce(); + expect(writer.sendRecord.mock.calls[0]?.[0]).toEqual( + proposalTemplate(proposalInput), + ); + expect(proposalId).toMatch(/^[0-9a-f]{64}$/); +}); + +it("sends nothing when the destination changes while the dialog is open", async () => { + const { service, reviews, writer, target } = setup({ status: "proposed" }); + const pending = service.propose(proposalInput); + const review = await nextReview(reviews); + target.members.push(outsider); + reviews.approve(review.id); + await expect(pending).rejects.toThrow( + "The destination conversation changed while the dialog was open. Nothing was sent.", + ); + target.members.pop(); + const consent = service.consent(proposal.id, "accept", "2".repeat(64)); + const consentReview = await nextReview(reviews); + target.channelType = "stream"; + reviews.approve(consentReview.id); + await expect(consent).rejects.toThrow("Nothing was sent."); + expect(writer.sendRecord).not.toHaveBeenCalled(); +}); + +it("shows the consent statement, destination and time, and binds the source identity", async () => { + const { service, reviews, writer } = setup({ status: "proposed" }); + await expect( + service.consent(proposal.id, "accept", "9".repeat(64)), + ).rejects.toThrow("does not match"); + const pending = service.consent(proposal.id, "accept", "2".repeat(64)); + const review = await nextReview(reviews); + expect(review.statement).toBe( + "Your own messages from this source will be published by you, at their original times.", + ); + expect(review.facts.find((fact) => fact.label === "Destination")?.value).toBe( + "Direct message with Partner Person", + ); + expect( + review.facts.find((fact) => fact.label === "Estimated time")?.value, + ).toBe("under a minute"); + reviews.approve(review.id); + await pending; + const record = writer.sendRecord.mock.calls[0]?.[0]; + expect(record?.kind).toBe(42111); + expect(JSON.parse(record?.content ?? "")).toEqual({ + v: 1, + decision: "accept", + source_user: "2".repeat(64), + }); +}); + +it("lets a channel admin approve for a non-participant, and nobody else", async () => { + const outside = stamp( + partner, + proposalTemplate({ + ...proposalInput, + source: { ...proposalInput.source, kind: "public_channel" }, + participants: [proposalInput.participants[1] as never], + }), + ); + const member = setup({ + status: "proposed", + proposal: outside, + channel: { channelType: "stream", visibility: "public", name: "general" }, + }); + await expect( + member.service.consent(outside.id, "accept", "admin"), + ).rejects.toThrow("You are not a participant in this import."); + const admin = setup({ + status: "proposed", + proposal: outside, + channel: { + channelType: "stream", + visibility: "public", + name: "general", + viewerRole: "admin", + }, + }); + const pending = admin.service.consent(outside.id, "accept", "admin"); + const review = await nextReview(admin.reviews); + expect(review.statement).toBeUndefined(); + admin.reviews.approve(review.id); + await pending; + expect( + JSON.parse(admin.writer.sendRecord.mock.calls[0]?.[0]?.content ?? ""), + ).toMatchObject({ decision: "accept", source_user: "admin" }); +}); + +it("withdraws and completes with host-signed records", async () => { + const { service, writer } = setup({ status: "active" }); + await service.withdraw(proposal.id, "Changed my mind"); + await service.complete(proposal.id, { messages: 3, reactions: 0 }); + const [withdrawn, completed] = writer.sendRecord.mock.calls.map( + (call) => call[0], + ); + expect(withdrawn?.kind).toBe(42112); + expect(withdrawn?.tags).toContainEqual(["e", proposal.id]); + expect(completed?.kind).toBe(42113); + expect(JSON.parse(completed?.content ?? "")).toMatchObject({ + v: 1, + published: { messages: 3, reactions: 0 }, + }); +}); + +it("finds verified profiles by username only", async () => { + const { service } = setup(); + await expect( + service.findVerified({ email: "someone@example.com" }), + ).rejects.toThrow("no email"); +}); + +it("stops before signing once someone else joins the destination", async () => { + let accepted = 0; + const harness = setup({ + status: "active", + decide: () => { + if (++accepted === 1) harness.target.members.push(outsider); + return { delivery: "accepted" }; + }, + }); + const report = await harness.service.publish( + proposal.id, + [message(1_735_732_800, "1"), message(1_735_732_801, "2")], + {}, + ); + expect(report).toMatchObject({ + status: "stopped", + published: 1, + stoppedAt: 1, + reason: "The destination's members changed. Nothing more was imported.", + }); + expect(harness.sent).toHaveLength(1); +}); + +it("stops before signing once the destination's visibility changes", async () => { + const privateProposal = proposalFor("private_channel"); + let accepted = 0; + const harness = setup({ + status: "active", + proposal: privateProposal, + channel: { channelType: "stream", visibility: "private" }, + decide: () => { + if (++accepted === 1) harness.target.visibility = "public"; + return { delivery: "accepted" }; + }, + }); + const report = await harness.service.publish( + privateProposal.id, + [ + message(1_735_732_800, "1", undefined, privateProposal.id), + message(1_735_732_801, "2", undefined, privateProposal.id), + ], + {}, + ); + expect(report).toMatchObject({ + status: "stopped", + published: 1, + stoppedAt: 1, + reason: + "The destination's type or visibility changed. Nothing more was imported.", + }); +}); + +it("bounds an explicit expected member set by the participants", async () => { + const { service, sent } = setup({ status: "active" }); + const superset = await service.publish( + proposal.id, + [message(1_735_732_800, "1")], + { expectedMembers: [viewer, partner, outsider] }, + ); + expect(superset).toMatchObject({ + status: "rejected", + reason: "The expected members must match the import's participants.", + }); + const subset = await service.publish( + proposal.id, + [message(1_735_732_800, "1")], + { expectedMembers: [viewer] }, + ); + expect(subset.status).toBe("rejected"); + expect(sent).toHaveLength(0); + const ok = await service.publish(proposal.id, [message(1_735_732_800, "1")], { + expectedMembers: [partner, viewer], + }); + expect(ok.status).toBe("done"); + + const privateProposal = proposalFor("private_channel"); + const narrowed = setup({ + status: "active", + proposal: privateProposal, + channel: { + channelType: "stream", + visibility: "private", + members: [viewer], + }, + }); + const left = await narrowed.service.publish( + privateProposal.id, + [message(1_735_732_800, "1", undefined, privateProposal.id)], + { expectedMembers: [viewer] }, + ); + expect(left.status).toBe("done"); + const widened = await narrowed.service.publish( + privateProposal.id, + [message(1_735_732_800, "1", undefined, privateProposal.id)], + { expectedMembers: [viewer, outsider] }, + ); + expect(widened.reason).toBe( + "The expected members must match the import's participants.", + ); +}); + +it("counts an event that lands after the caller stops, and only then", async () => { + const controller = new AbortController(); + let release!: (decision: Decision) => void; + const { service, sent } = setup({ + status: "active", + decide: () => + new Promise((resolve) => { + release = resolve; + controller.abort(); + }), + }); + const pending = service.publish( + proposal.id, + [message(1_735_732_800, "1"), message(1_735_732_801, "2")], + {}, + controller.signal, + ); + await vi.waitFor(() => expect(release).toBeTypeOf("function")); + release({ delivery: "accepted" }); + const report = await pending; + expect(report).toMatchObject({ status: "stopped", published: 1 }); + expect(report.ids).toEqual([sent[0]?.id]); + + const refusedController = new AbortController(); + let refuse!: (decision: Decision) => void; + const refused = setup({ + status: "active", + decide: () => + new Promise((resolve) => { + refuse = resolve; + refusedController.abort(); + }), + }); + const stopped = refused.service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + refusedController.signal, + ); + await vi.waitFor(() => expect(refuse).toBeTypeOf("function")); + refuse({ delivery: "failed", error: "invalid: import event malformed" }); + expect(await stopped).toMatchObject({ status: "stopped", published: 0 }); + expect(refused.items).toHaveLength(0); +}); + +it("gives up on an attempt that never settles after a stop, dismisses it and stops listening", async () => { + const controller = new AbortController(); + const { service, writer, sent, listeners, expiries } = setup({ + status: "active", + decide: () => + new Promise(() => { + controller.abort(); + }), + }); + const pending = service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + controller.signal, + ); + await vi.waitFor(() => expect(expiries).toHaveLength(1)); + expect(listeners.size).toBeGreaterThan(0); + expiries[0]?.(); + expect(await pending).toMatchObject({ status: "stopped", published: 0 }); + expect(writer.dismiss).toHaveBeenCalledWith(sent[0]?.id); + expect(listeners.size).toBe(0); +}); + +it("finds or opens a direct message and returns the relay's member list", async () => { + const found = setup(); + await expect( + found.service.ensureDirectMessage([partner], { createIfMissing: false }), + ).resolves.toEqual({ + channelId: channel, + created: false, + members: [viewer, partner], + }); + const stale = setup({ roster: () => [viewer, partner, outsider] }); + await expect( + stale.service.ensureDirectMessage([partner], { createIfMissing: false }), + ).rejects.toThrow("could not be confirmed"); + + const created = setup({ verified: [viewer, partner, outsider] }); + const pending = created.service.ensureDirectMessage([outsider], { + createIfMissing: true, + }); + const review = await nextReview(created.reviews); + expect(review.type).toBe("direct-message"); + created.reviews.approve(review.id); + await expect(pending).resolves.toEqual({ + channelId: "d0".repeat(16), + created: true, + members: [viewer, outsider], + }); +}); + +it("checks an existing channel against the relay's member list", async () => { + const input = { + name: "general", + visibility: "private" as const, + members: [partner], + existingChannelId: channel, + }; + const dm = setup(); + await expect(dm.service.ensureChannel(input)).rejects.toThrow( + "That channel is unavailable.", + ); + const archived = setup({ + channel: { channelType: "stream", visibility: "private", archived: true }, + }); + await expect(archived.service.ensureChannel(input)).rejects.toThrow( + "archived", + ); + const gone = setup({ + channel: { channelType: "stream", visibility: "private" }, + roster: () => [partner], + }); + await expect(gone.service.ensureChannel(input)).rejects.toThrow( + "You are not a member of that channel.", + ); + // The cached list looks right; the relay's roster has someone else too. + const crowded = setup({ + channel: { channelType: "stream", visibility: "private" }, + roster: () => [viewer, partner, outsider], + }); + await expect(crowded.service.ensureChannel(input)).rejects.toThrow( + "One member of that channel is not in the source conversation.", + ); + const ok = setup({ + channel: { channelType: "stream", visibility: "private" }, + }); + await expect(ok.service.ensureChannel(input)).resolves.toEqual({ + channelId: channel, + created: false, + members: [viewer, partner], + }); +}); + +it("creates a private channel and returns its read-back members", async () => { + const { service, reviews, session } = setup(); + const pending = service.ensureChannel({ + name: "imported", + visibility: "private", + members: [partner], + }); + const review = await nextReview(reviews); + expect(review.type).toBe("channel"); + reviews.approve(review.id); + await expect(pending).resolves.toEqual({ + channelId: "c0".repeat(16), + created: true, + members: [viewer, partner], + }); + expect(session.memberAdditions.add).toHaveBeenCalledWith( + "c0".repeat(16), + partner, + ); +}); + +it("reads back only this import's events, oldest first", async () => { + const { service, snapshotRead } = setup({ status: "active" }); + const mine = stamp( + viewer, + { + kind: 9, + content: "x", + tags: [ + ["h", channel], + ["import", proposal.id], + ["source", "slack", "2"], + ], + }, + 1_735_732_900, + ); + const earlier = stamp( + partner, + { + kind: 7, + content: "+", + tags: [ + ["h", channel], + ["e", mine.id], + ["import", proposal.id], + ["source", "slack", "1"], + ], + }, + 1_735_732_800, + ); + const other = stamp(viewer, { + kind: 9, + content: "y", + tags: [["h", channel]], + }); + snapshotRead.mockImplementation(async (filters: readonly ReadFilter[]) => { + const filter = filters[0]; + if (filter?.kinds?.includes(9)) return [mine, earlier, other]; + if (filter?.ids?.includes(proposal.id)) return [proposal]; + return []; + }); + const report = await service.readBack(proposal.id); + expect(report.events).toEqual([ + { + id: earlier.id, + pubkey: partner, + kind: 7, + source_ref: "1", + created_at: 1_735_732_800, + }, + { + id: mine.id, + pubkey: viewer, + kind: 9, + source_ref: "2", + created_at: 1_735_732_900, + }, + ]); + expect(service.exists(channel, mine.id)).toBe(true); +}); + +it("predicts attachment tags every participant can reproduce from the file's bytes, and checks the upload against them", async () => { + const { service, upload } = setup(); + const hash = "c".repeat(64); + const png = new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, + ]); + const input = { sha256Hex: hash, name: "diagram.png", size: 9, head: png }; + const predicted = service.attachmentTags(input); + expect(predicted).toEqual({ + url: `${origin}/media/${hash}.png`, + tags: [ + [ + "imeta", + `url ${origin}/media/${hash}.png`, + "m image/png", + "size 9", + `x ${hash}`, + "filename diagram.png", + ], + ], + markdown: `![diagram.png](<${origin}/media/${hash}.png>)`, + }); + const pdf = new TextEncoder().encode("%PDF-1.7\n"); + expect( + service.attachmentTags({ ...input, name: "a.pdf", size: 9, head: pdf }), + ).toMatchObject({ + url: `${origin}/media/${hash}.pdf`, + tags: [expect.arrayContaining(["m application/pdf"])], + }); + const text = new TextEncoder().encode("name,count\nalpha,1\n"); + expect( + service.attachmentTags({ + ...input, + name: "data.csv", + size: text.length, + head: text, + }), + ).toMatchObject({ + url: `${origin}/media/${hash}.bin`, + tags: [expect.arrayContaining(["m application/octet-stream"])], + }); + const audio = new TextEncoder().encode("ID3\u0004\u0000\u0000\u0000\u0000"); + expect(() => + service.attachmentTags({ + ...input, + name: "voice.mp3", + size: audio.length, + head: audio, + }), + ).toThrow("This file type cannot be imported as an attachment."); + expect(() => service.attachmentTags({ ...input, size: 5000 })).toThrow( + "first 4096 bytes", + ); + + const file = new Blob([png], { type: "image/png" }); + await expect( + service.uploadAttachment(file, "diagram.png", hash, undefined, { + channelId: channel, + }), + ).resolves.toEqual(predicted); + const csv = new Blob([text], { type: "text/csv" }); + upload.mockResolvedValueOnce({ + name: "data.csv", + url: `${origin}/media/${hash}.bin`, + type: "application/octet-stream", + size: text.length, + sha256: hash, + }); + await expect( + service.uploadAttachment(csv, "data.csv", hash, undefined, { + channelId: channel, + }), + ).resolves.toMatchObject({ url: `${origin}/media/${hash}.bin` }); + upload.mockResolvedValueOnce({ + name: "diagram.png", + url: `${origin}/media/${hash}.bin`, + type: "image/png", + size: 9, + sha256: hash, + }); + await expect( + service.uploadAttachment(file, "diagram.png", hash, undefined, { + channelId: channel, + }), + ).rejects.toThrow("cannot be attached"); + upload.mockResolvedValueOnce({ + name: "diagram.png", + url: `${origin}/media/${"e".repeat(64)}.png`, + type: "image/png", + size: 9, + sha256: "e".repeat(64), + }); + await expect( + service.uploadAttachment(file, "diagram.png", hash, undefined, { + channelId: channel, + }), + ).rejects.toThrow("cannot be attached"); + const uploadsBefore = upload.mock.calls.length; + await expect( + service.uploadAttachment( + new Blob([audio], { type: "audio/mpeg" }), + "voice.mp3", + hash, + undefined, + { channelId: channel }, + ), + ).rejects.toThrow("cannot be imported as an attachment"); + expect(upload.mock.calls.length).toBe(uploadsBefore); +}); diff --git a/src/features/conversation-import/service.ts b/src/features/conversation-import/service.ts new file mode 100644 index 0000000000..d09c55fc4c --- /dev/null +++ b/src/features/conversation-import/service.ts @@ -0,0 +1,1713 @@ +import { Service, type Context } from "@deepseek-ai/cordis"; +import { getEventHash } from "nostr-tools"; +import type {} from "../communities/service"; +import { attachmentMarkdown, attachmentName } from "../relay/attachments"; +import type { RelayEvent, ReadFilter } from "../relay/events"; +import { claimImportWriter, type ImportWriter } from "../relay/import-writes"; +import type { OutgoingEvent } from "../relay/outbox"; +import { splitPartition } from "../relay/partition"; +import type { RelayData } from "../relay/service"; +import type { RelaySession } from "../relay/session"; +import { + VERIFIED_PROFILE_BATCH, + VERIFIED_PROFILE_KIND, + verifiedProfile as readVerifiedProfile, + type VerifiedProfile, +} from "../relay/verified-profile"; +import { + completeTemplate, + consentTemplate, + fingerprint, + IMPORT_PROPOSAL_KIND, + IMPORT_SNAPSHOT_KIND, + parseProposal, + parseSnapshot, + preparedProblem, + proposalProblem, + proposalTemplate, + SOURCE_KIND_LABELS, + sourceLabel, + withdrawTemplate, + type ParsedProposal, + type ParsedSnapshot, +} from "./protocol"; +import { + isImportReviews, + type ImportReview, + type ImportReviews, + type ReviewMember, +} from "./reviews"; +import { relayMediaType, SNIFF_BYTES } from "./relay-media-type"; +import type { + AttachmentTagsInput, + ConversationImportService, + ImportCounts, + ImportedAttachment, + ImportProposalInput, + ImportSessionView, + ImportSourceKind, + MembershipView, + PreparedImportEvent, + PublishProgress, + PublishReport, + ReadBackEvent, + ReadBackReport, + UnsignedImportEvent, + VerifiedProfileView, +} from "./types"; + +const HEX64 = /^[0-9a-f]{64}$/; +/** At most 8 events per second, under the relay's 10 per second socket limit. */ +const PACE_MS = 125; +const PARENT_POLL_MS = 5_000; +/** How long a missing parent may wait without any partner progress. */ +const PARENT_STALL_MS = 10 * 60_000; +const RATE_LIMIT_WAIT_MS = 15_000; +/** Above the outbox's own delivery timeout. */ +const SETTLE_AFTER_STOP_MS = 30_000; +const READ_PAGE = 200; +const ROSTER_KIND = 39002; +const ROSTER_ATTEMPTS = 5; +const ROSTER_RETRY_MS = 1_000; + +const NO_RELAY_SUPPORT = + "This community's relay does not support conversation import."; +const DESTINATION_CHANGED = + "The destination conversation changed while the dialog was open. Nothing was sent."; +const EXPECTED_MEMBERS_INVALID = + "The expected members must match the import's participants."; +const MEMBERS_UNCONFIRMED = + "The conversation's members could not be confirmed with the relay. Try again."; +const NOT_CONFIRMED = "The relay has not confirmed that this import is active."; + +export type ConversationImportOptions = { + /** Test seam for pacing and polling delays. */ + wait?: (ms: number, signal?: AbortSignal) => Promise; + /** Current time in seconds. */ + now?: () => number; + /** Current time in milliseconds, for pacing. */ + clock?: () => number; +}; + +type Entry = { proposal: ParsedProposal; snapshot?: ParsedSnapshot }; +type HostState = { + relay: RelayData; + reviews: ImportReviews; + wait: (ms: number, signal?: AbortSignal) => Promise; + now: () => number; + clock: () => number; + session?: RelaySession; + stopLive?: () => void; + loaded: boolean; + entries: Map; + orphans: Map; + known: Map>; + views: readonly ImportSessionView[]; + listeners: Set<(sessions: readonly ImportSessionView[]) => void>; +}; + +/** Plugins reach the service object, including through cordis's proxy, so + * host state is keyed by an opaque token and resolved only in this module. */ +const HOST: unique symbol = Symbol("conversationImport"); +const hosts = new WeakMap(); +/** Only `createConversationImportHost` holds this, so a plugin reaching the + * class through `constructor` cannot build a host of its own. */ +const MINT: unique symbol = Symbol("conversationImportMint"); + +function stateOf(host: ConversationImportHost): HostState { + const state = hosts.get(host[HOST]); + if (!state) throw new Error("Conversation import is unavailable"); + return state; +} + +const defaultWait = (ms: number, signal?: AbortSignal) => + new Promise((resolve, reject) => { + signal?.throwIfAborted(); + const timer = setTimeout(() => { + signal?.removeEventListener("abort", abort); + resolve(); + }, ms); + const abort = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + signal?.addEventListener("abort", abort, { once: true }); + }); + +const declined = () => + new DOMException("The request was not approved", "AbortError"); + +function verifiedView( + pubkey: string, + verified: VerifiedProfile, +): VerifiedProfileView { + return Object.freeze({ + pubkey, + displayName: verified.displayName, + username: verified.username, + ...(verified.fullName !== undefined ? { fullName: verified.fullName } : {}), + issuerLabel: verified.issuerLabel, + verifiedAt: verified.verifiedAt, + fingerprint: fingerprint(pubkey), + }); +} + +function sessionView(entry: Entry, now: number): ImportSessionView { + const { proposal, snapshot } = entry; + const expired = !snapshot && proposal.content.expires_at <= now; + return Object.freeze({ + proposalId: proposal.id, + channelId: proposal.channelId, + proposer: proposal.proposer, + proposedAt: proposal.createdAt, + proposal: proposal.content, + status: snapshot?.status ?? (expired ? "expired" : "proposed"), + required: + snapshot?.required ?? + Object.freeze(proposal.content.participants.map((item) => item.pubkey)), + consents: snapshot?.consents ?? Object.freeze({}), + published: snapshot?.published ?? Object.freeze({}), + completed: snapshot?.completed ?? Object.freeze([]), + expires_at: snapshot?.expires_at ?? proposal.content.expires_at, + confirmed: !!snapshot, + }); +} + +/** Publishing needs the relay's own word that the session is active. */ +function inactiveReason(entry: Entry, now: number, viewer: string) { + if (!entry.snapshot) return NOT_CONFIRMED; + const status = sessionView(entry, now).status; + if (status !== "active") return `This import is ${status}.`; + if (entry.snapshot.completed.includes(viewer)) + return "You already completed this import."; +} + +function formatDate(seconds: number) { + return new Date(seconds * 1000).toLocaleDateString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + }); +} + +function formatDuration(events: number) { + const seconds = Math.ceil((events * PACE_MS) / 1000); + if (seconds < 60) return "under a minute"; + const minutes = Math.ceil(seconds / 60); + return minutes < 60 + ? `about ${minutes} ${minutes === 1 ? "minute" : "minutes"}` + : `about ${Math.ceil(minutes / 60)} hours`; +} + +function formatList(names: readonly string[]) { + if (names.length <= 1) return names[0] ?? ""; + return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`; +} + +const totalCounts = (proposal: ParsedProposal["content"]) => + proposal.participants.reduce( + (sum, item) => ({ + messages: sum.messages + item.messages, + reactions: sum.reactions + item.reactions, + }), + { messages: 0, reactions: 0 }, + ); + +const sameSet = (members: readonly string[], expected: ReadonlySet) => + new Set(members).size === expected.size && + members.every((key) => expected.has(key)); + +function sameView(a: MembershipView, b: MembershipView) { + return ( + a.channelType === b.channelType && + a.visibility === b.visibility && + sameSet(a.members, new Set(b.members)) + ); +} + +/** Whether the destination's type and visibility can hold this source. */ +function shapeMatches(kind: ImportSourceKind, view: MembershipView) { + if (kind === "dm" || kind === "group_dm") return view.channelType === "dm"; + return ( + view.channelType === "channel" && + view.visibility === (kind === "private_channel" ? "private" : "public") + ); +} + +/** Direct messages must name exactly the participants; private channels at + * most the participants. Public channels may pin any member set. */ +function expectedMembersProblem( + kind: ImportSourceKind, + participants: ReadonlySet, + expected: readonly string[] | undefined, +) { + if (!expected) return; + if ( + !Array.isArray(expected) || + new Set(expected).size !== expected.length || + expected.some((key) => typeof key !== "string" || !HEX64.test(key)) + ) + return EXPECTED_MEMBERS_INVALID; + if ( + (kind === "dm" || kind === "group_dm") && + !sameSet(expected, participants) + ) + return EXPECTED_MEMBERS_INVALID; + if ( + kind === "private_channel" && + expected.some((key) => !participants.has(key)) + ) + return EXPECTED_MEMBERS_INVALID; +} + +/** Waits for the journal to settle one delivery attempt. With `vanish`, an + * entry that is no longer in the journal settles as undefined. */ +function settled( + writer: ImportWriter, + id: string, + signal?: AbortSignal, + vanish = false, +): Promise { + return new Promise((resolve, reject) => { + let stop = () => {}; + const finish = (item: OutgoingEvent | undefined) => { + stop(); + signal?.removeEventListener("abort", abort); + resolve(item); + }; + const abort = () => { + stop(); + reject(signal?.reason); + }; + const check = () => { + const item = writer.local + .snapshot() + .find((entry) => entry.event.id === id); + if (!item) { + if (vanish) finish(undefined); + return; + } + if (item.delivery !== "sending") finish(item); + }; + if (signal?.aborted) return abort(); + signal?.addEventListener("abort", abort, { once: true }); + stop = writer.local.subscribe(check); + check(); + }); +} + +/** `settled` for an attempt the caller no longer waits on. A closed journal + * never settles, so this gives up after `ms` and dismisses the entry, which + * then can neither publish later nor go uncounted. */ +async function settledWithin( + state: HostState, + writer: ImportWriter, + id: string, + ms: number, +) { + const stop = new AbortController(); + let expired = false; + try { + const item = await Promise.race([ + settled(writer, id, stop.signal, true), + state.wait(ms, stop.signal).then( + () => { + expired = true; + }, + () => {}, + ), + ]); + if (!expired) return item || undefined; + void writer.dismiss(id).catch(() => {}); + return undefined; + } finally { + stop.abort(); + } +} + +const failure = (item: OutgoingEvent | undefined) => + item?.reason ?? item?.error ?? "Delivery could not be confirmed"; + +const deliveredOk = (item: OutgoingEvent | undefined) => + item?.delivery === "accepted" || item?.delivery === "seen"; + +/** Host service for consented conversation import (NIP-CI). Plugins get read + * models and request writes; every consent-bearing write goes through a + * host-owned dialog, and the host signs. */ +export class ConversationImportHost + extends Service + implements ConversationImportService +{ + declare readonly [HOST]: object; + constructor( + ctx: Context, + relay: RelayData, + reviews: ImportReviews, + options: ConversationImportOptions, + mint: typeof MINT, + ) { + if (mint !== MINT || !isImportReviews(reviews)) + throw new Error("Conversation import is provided by the host."); + super(ctx, "conversationImport"); + const state: HostState = { + relay, + reviews, + wait: options.wait ?? defaultWait, + now: options.now ?? (() => Math.floor(Date.now() / 1000)), + clock: options.clock ?? Date.now, + loaded: false, + entries: new Map(), + orphans: new Map(), + known: new Map(), + views: Object.freeze([]), + listeners: new Set(), + }; + const key = Object.freeze({}); + Object.defineProperty(this, HOST, { value: key }); + hosts.set(key, state); + const sync = () => bind(state); + sync(); + const stop = relay.subscribe(sync); + ctx.effect(() => () => { + stop(); + state.stopLive?.(); + state.listeners.clear(); + }); + } + + verifiedProfile(pubkey: string): VerifiedProfileView | undefined { + const session = stateOf(this).session; + if (!session || !HEX64.test(pubkey)) return; + const profile = session.profiles.snapshot().get(pubkey); + if (!profile) void session.profiles.ensure([pubkey]).catch(() => {}); + return profile?.verified && verifiedView(pubkey, profile.verified); + } + + async findVerified( + query: { email?: string; username?: string }, + signal?: AbortSignal, + ): Promise { + const session = current(stateOf(this)); + const username = query.username?.trim().toLowerCase(); + if (!username) + throw new Error( + "Verified profiles carry no email address. Search by username instead.", + ); + if (!/^[a-z0-9._-]{1,64}$/.test(username)) + throw new Error("That is not a valid username."); + const active = signal ?? new AbortController().signal; + const candidates = new Set(); + for (const [pubkey, profile] of session.profiles.snapshot()) + if (profile.verified?.username === username) candidates.add(pubkey); + for (const event of await session.searchProfiles(username, { + limit: 100, + signal: active, + })) + candidates.add(event.pubkey); + const verified = await readVerified(session, [...candidates], active); + return [...verified.values()].filter( + (profile) => profile.username === username, + ); + } + + membership(channelId: string): MembershipView | undefined { + return membershipOf(stateOf(this), channelId); + } + + async ensureDirectMessage( + otherPubkeys: string[], + opts: { createIfMissing: boolean }, + signal?: AbortSignal, + ) { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const others = [...new Set(otherPubkeys)]; + if ( + !others.length || + others.length > 8 || + others.length !== otherPubkeys.length || + others.some((key) => !HEX64.test(key) || key === viewer) + ) + throw new Error("Choose between one and eight other people."); + const expected = new Set([viewer, ...others]); + const existing = session.channels + .list() + .channels.find( + (channel) => + channel.channelType === "dm" && + !channel.archived && + channel.members?.length === expected.size && + channel.members.every((key) => expected.has(key)), + ); + if (existing) { + const members = await readMembers(state, session, existing.id, signal); + if (!sameSet(members, expected)) throw new Error(MEMBERS_UNCONFIRMED); + return { channelId: existing.id, created: false, members }; + } + if (!opts.createIfMissing) + throw new Error("No direct message with exactly these people exists."); + const verified = await readVerified(session, others, signal); + const missing = others.filter((key) => !verified.has(key)); + const approved = await state.reviews.request( + { + type: "direct-message", + title: "Start a direct message for the import?", + description: + "Buzz will open a direct message with exactly these people so their shared history can be imported into it.", + facts: [{ label: "Members", value: String(expected.size) }], + members: [viewer, ...others].map((pubkey) => + member(pubkey, verified.get(pubkey) ?? selfVerified(session, pubkey)), + ), + ...(missing.length + ? { + refusal: `${missing.length === 1 ? "One person has" : `${missing.length} people have`} no verified Buzz identity.`, + } + : {}), + confirmLabel: "Start direct message", + }, + signal, + ); + if (!approved) throw declined(); + const channelId = await session.directMessages.open( + others, + signal ?? new AbortController().signal, + ); + const members = await readMembers( + state, + session, + channelId, + signal, + (found) => sameSet(found, expected), + ); + if (!sameSet(members, expected)) throw new Error(MEMBERS_UNCONFIRMED); + return { channelId, created: true, members }; + } + + async ensureChannel( + input: { + name: string; + visibility: "private" | "public"; + members: string[]; + existingChannelId?: string; + }, + signal?: AbortSignal, + ) { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const requested = [...new Set([viewer, ...input.members])]; + if ( + requested.some((key) => !HEX64.test(key)) || + (input.visibility !== "private" && input.visibility !== "public") + ) + throw new Error("The channel members or visibility are invalid."); + const visibilityText = + input.visibility === "private" ? "private" : "public"; + if (input.existingChannelId) { + const channelId = input.existingChannelId; + const channel = session.channels + .list() + .channels.find((item) => item.id === channelId); + if (channel?.channelType !== "stream") + throw new Error("That channel is unavailable."); + if (channel.archived) throw new Error("That channel is archived."); + const view = membershipOf(state, channelId); + if (view?.visibility !== input.visibility) + throw new Error(`That channel is not ${visibilityText}.`); + const members = await readMembers(state, session, channelId, signal); + if (!members.includes(viewer)) + throw new Error("You are not a member of that channel."); + const outsiders = members.filter((key) => !requested.includes(key)); + if (input.visibility === "private" && outsiders.length) + throw new Error( + `${outsiders.length === 1 ? "One member" : `${outsiders.length} members`} of that channel ${outsiders.length === 1 ? "is" : "are"} not in the source conversation.`, + ); + return { channelId, created: false, members }; + } + const name = input.name.trim(); + if (!name) throw new Error("The channel needs a name."); + const verified = await readVerified(session, requested, signal); + const missing = requested.filter( + (key) => key !== viewer && !verified.has(key), + ); + const approved = await state.reviews.request( + { + type: "channel", + title: `Create #${name} for the import?`, + description: + input.visibility === "private" + ? "Buzz will create a private channel with exactly these members." + : "Buzz will create a public channel and add these members.", + facts: [ + { + label: "Visibility", + value: input.visibility === "private" ? "Private" : "Public", + }, + { label: "Members", value: String(requested.length) }, + ], + members: requested.map((pubkey) => + member(pubkey, verified.get(pubkey) ?? selfVerified(session, pubkey)), + ), + ...(missing.length + ? { + refusal: `${missing.length === 1 ? "One member has" : `${missing.length} members have`} no verified Buzz identity.`, + } + : {}), + confirmLabel: "Create channel", + }, + signal, + ); + if (!approved) throw declined(); + const channelId = await session.channelCreation.create({ + name, + visibility: input.visibility === "public" ? "open" : "private", + }); + for (const pubkey of requested) + if (pubkey !== viewer) + await session.memberAdditions.add(channelId, pubkey); + const expected = new Set(requested); + const members = await readMembers( + state, + session, + channelId, + signal, + (found) => + input.visibility === "private" + ? sameSet(found, expected) + : requested.every((key) => found.includes(key)), + ); + if (input.visibility === "private" && !sameSet(members, expected)) + throw new Error(MEMBERS_UNCONFIRMED); + return { channelId, created: true, members }; + } + + async propose(input: ImportProposalInput, signal?: AbortSignal) { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const writer = writerOf(state, session); + if (!session.conversationImport) throw new Error(NO_RELAY_SUPPORT); + const { channelId, ...content } = input; + const problem = proposalProblem(content, state.now()); + if (problem) throw new Error(problem); + const channel = session.channels + .list() + .channels.find((item) => item.id === channelId); + const view = membershipOf(state, channelId); + if (!channel || !view?.members.includes(viewer)) + throw new Error("You are not a member of that conversation."); + const pubkeys = content.participants.map((item) => item.pubkey); + const verified = await readVerified(session, pubkeys, signal); + const refusal = destinationRefusal(content, view, pubkeys, verified); + const totals = totalCounts(content); + const approved = await state.reviews.request( + { + type: "propose", + title: `Import ${content.source.label} from ${sourceLabel(content.source.type)}?`, + description: + "Each participant must accept before anything is imported. Each person then publishes their own messages at their original times.", + facts: [ + { + label: "Destination", + value: destinationText(session, channel.name, view, verified), + }, + { label: "Source", value: SOURCE_KIND_LABELS[content.source.kind] }, + { + label: "Date range", + value: `${formatDate(content.range.from)} to ${formatDate(content.range.to)}`, + }, + { + label: "Messages", + value: `${totals.messages} messages, ${totals.reactions} reactions`, + }, + ...excludedFact(content), + { + label: "Estimated time", + value: formatDuration(totals.messages + totals.reactions), + }, + { label: "Manifest", value: fingerprint(content.manifest) }, + ], + members: content.participants.map((item) => + member( + item.pubkey, + verified.get(item.pubkey), + `${item.messages} messages, ${item.reactions} reactions`, + ), + ), + ...(refusal ? { refusal } : {}), + confirmLabel: "Propose import", + }, + signal, + ); + if (!approved) throw declined(); + const after = membershipOf(state, channelId); + if ( + !after || + !sameView(view, after) || + destinationRefusal(content, after, pubkeys, verified) + ) + throw new Error(DESTINATION_CHANGED); + const id = writer.sendRecord(proposalTemplate(input)); + await delivered(writer, id, signal); + const event = writer.local + .snapshot() + .find((item) => item.event.id === id)?.event; + if (event) ingest(state, [event as RelayEvent]); + return { proposalId: id }; + } + + async consent( + proposalId: string, + decision: "accept" | "decline", + sourceUserHash: string, + signal?: AbortSignal, + ) { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const writer = writerOf(state, session); + if (!session.conversationImport) throw new Error(NO_RELAY_SUPPORT); + if (decision !== "accept" && decision !== "decline") + throw new Error("Choose accept or decline."); + const entry = await entryFor(state, proposalId, signal); + const { content, channelId } = entry.proposal; + const participant = content.participants.find( + (item) => item.pubkey === viewer, + ); + const channel = session.channels + .list() + .channels.find((item) => item.id === channelId); + const admin = + sourceUserHash === "admin" && + ["owner", "admin"].includes(channel?.viewerRole ?? ""); + if (!participant && !admin) + throw new Error("You are not a participant in this import."); + if (participant && !admin && participant.source_user !== sourceUserHash) + throw new Error( + "That source identity does not match your entry in the proposal.", + ); + const status = sessionView(entry, state.now()).status; + if (status !== "proposed" && status !== "active") + throw new Error(`This import is ${status}.`); + const pubkeys = content.participants.map((item) => item.pubkey); + const view = membershipOf(state, channelId); + const verified = await readVerified(session, pubkeys, signal); + const refusal = + decision === "accept" + ? view + ? destinationRefusal(content, view, pubkeys, verified) + : "The destination conversation is unavailable." + : undefined; + const totals = totalCounts(content); + const approved = await state.reviews.request( + { + type: "consent", + title: + decision === "accept" + ? `Accept importing ${content.source.label} from ${sourceLabel(content.source.type)}?` + : `Decline importing ${content.source.label}?`, + description: + decision === "accept" + ? "Check that the manifest fingerprint matches the one shown to the proposer before accepting." + : "Declining ends this import for the conversation.", + facts: [ + ...(view + ? [ + { + label: "Destination", + value: destinationText( + session, + channel?.name ?? "", + view, + verified, + ), + }, + ] + : []), + { label: "Source", value: SOURCE_KIND_LABELS[content.source.kind] }, + { + label: "Date range", + value: `${formatDate(content.range.from)} to ${formatDate(content.range.to)}`, + }, + { + label: "Messages", + value: `${totals.messages} messages, ${totals.reactions} reactions`, + }, + ...(participant + ? [ + { + label: "Yours", + value: `${participant.messages} messages, ${participant.reactions} reactions`, + }, + ] + : []), + ...excludedFact(content), + { + label: "Estimated time", + value: formatDuration(totals.messages + totals.reactions), + }, + { label: "Manifest", value: fingerprint(content.manifest) }, + ], + members: content.participants.map((item) => + member( + item.pubkey, + verified.get(item.pubkey), + `${item.messages} messages, ${item.reactions} reactions`, + ), + ), + ...(decision === "accept" && participant + ? { + statement: + "Your own messages from this source will be published by you, at their original times.", + } + : {}), + ...(refusal ? { refusal } : {}), + confirmLabel: + decision === "accept" ? "Accept import" : "Decline import", + ...(decision === "decline" ? { destructive: true } : {}), + }, + signal, + ); + if (!approved) throw declined(); + if (decision === "accept") { + const after = membershipOf(state, channelId); + if ( + !view || + !after || + !sameView(view, after) || + destinationRefusal(content, after, pubkeys, verified) + ) + throw new Error(DESTINATION_CHANGED); + } + const id = writer.sendRecord( + consentTemplate( + { + id: proposalId, + channelId, + manifest: content.manifest, + proposer: entry.proposal.proposer, + }, + decision, + admin ? "admin" : sourceUserHash, + ), + ); + await delivered(writer, id, signal); + void refreshSnapshot(state, entry, signal).catch(() => {}); + } + + async withdraw(proposalId: string, reason?: string) { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const writer = writerOf(state, session); + const entry = await entryFor(state, proposalId); + const { proposal } = entry; + if ( + proposal.proposer !== viewer && + !proposal.content.participants.some((item) => item.pubkey === viewer) + ) + throw new Error("Only the proposer or a participant can withdraw."); + const id = writer.sendRecord( + withdrawTemplate(proposalId, proposal.channelId, reason), + ); + await delivered(writer, id); + void refreshSnapshot(state, entry).catch(() => {}); + } + + async complete(proposalId: string, published: ImportCounts) { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const writer = writerOf(state, session); + const entry = await entryFor(state, proposalId); + if ( + !entry.proposal.content.participants.some( + (item) => item.pubkey === viewer, + ) + ) + throw new Error("You are not a participant in this import."); + const id = writer.sendRecord( + completeTemplate(proposalId, entry.proposal.channelId, published), + ); + await delivered(writer, id); + void refreshSnapshot(state, entry).catch(() => {}); + } + + session(proposalId: string): ImportSessionView | undefined { + return stateOf(this).views.find((view) => view.proposalId === proposalId); + } + + async refresh( + proposalId: string, + signal?: AbortSignal, + ): Promise { + const state = stateOf(this); + const known = state.entries.get(proposalId); + const entry = known ?? (await entryFor(state, proposalId, signal)); + if (known) await refreshSnapshot(state, entry, signal); + return sessionView(entry, state.now()); + } + + subscribe(cb: (sessions: readonly ImportSessionView[]) => void) { + const state = stateOf(this); + state.listeners.add(cb); + cb(state.views); + return () => { + state.listeners.delete(cb); + }; + } + + eventId(unsigned: UnsignedImportEvent): string { + return eventIdOf(unsigned); + } + + exists(channelId: string, eventId: string): boolean { + return existsIn(stateOf(this), channelId, eventId); + } + + async publish( + proposalId: string, + events: readonly PreparedImportEvent[], + opts: { + onProgress?: (p: PublishProgress) => void; + expectedMembers?: readonly string[]; + }, + signal?: AbortSignal, + ): Promise { + const state = stateOf(this); + const session = current(state); + const viewer = viewerOf(session); + const writer = writerOf(state, session); + const entry = await entryFor(state, proposalId, signal); + const { proposal } = entry; + const channelId = proposal.channelId; + const ids: string[] = []; + const report = ( + status: PublishReport["status"], + stoppedAt?: number, + reason?: string, + ): PublishReport => + Object.freeze({ + status, + published: ids.length, + ids: Object.freeze([...ids]), + ...(stoppedAt !== undefined ? { stoppedAt } : {}), + ...(reason !== undefined ? { reason } : {}), + }); + const participants = new Set( + proposal.content.participants.map((item) => item.pubkey), + ); + if (!participants.has(viewer)) + return report("rejected", 0, "You are not a participant in this import."); + const kind = proposal.content.source.kind; + const invalid = expectedMembersProblem( + kind, + participants, + opts.expectedMembers, + ); + if (invalid) return report("rejected", 0, invalid); + const expected = events.map((event) => + eventIdOf({ ...event, pubkey: viewer }), + ); + const own = new Map(expected.map((id, index) => [id, index])); + const rules = { + proposalId, + channelId, + sourceType: proposal.content.source.type, + range: proposal.content.range, + }; + for (const [index, event] of events.entries()) { + const problem = preparedProblem(event, rules, state.now()); + if (problem) return report("rejected", index, problem); + for (const reference of references(event)) { + const at = own.get(reference); + if (at !== undefined && at >= index) + return report( + "rejected", + index, + "An event is listed before the event it refers to.", + ); + } + } + // Direct messages and private channels hold exactly the source's people; + // anyone added later must not receive the rest of the history. + const exact = opts.expectedMembers + ? new Set(opts.expectedMembers) + : kind === "public_channel" + ? undefined + : participants; + const destinationProblem = (view: MembershipView | undefined) => { + if (!view?.members.includes(viewer)) + return "You are no longer a member of the destination conversation."; + if (!shapeMatches(kind, view)) + return "The destination's type or visibility changed. Nothing more was imported."; + if (exact && !sameSet(view.members, exact)) + return "The destination's members changed. Nothing more was imported."; + }; + const before = destinationProblem(membershipOf(state, channelId)); + if (before) return report("stopped", 0, before); + await refreshSnapshot(state, entry, signal).catch(() => {}); + const total = events.length; + let lastSend = 0; + let pending: string | undefined; + try { + for (const [index, event] of events.entries()) { + signal?.throwIfAborted(); + const stopped = inactiveReason(entry, state.now(), viewer); + if (stopped) return report("stopped", index, stopped); + for (const reference of references(event)) { + if (own.has(reference) || existsIn(state, channelId, reference)) + continue; + const waited = await waitForEvent( + state, + session, + entry, + channelId, + reference, + (waitingFor) => + opts.onProgress?.({ + published: ids.length, + total, + waitingFor, + }), + signal, + ); + if (waited !== true) return report("waiting", index, waited); + } + const gap = state.clock() - lastSend; + if (index && gap < PACE_MS) await state.wait(PACE_MS - gap, signal); + // Checked after every wait, immediately before signing. + const changed = destinationProblem(membershipOf(state, channelId)); + if (changed) return report("stopped", index, changed); + lastSend = state.clock(); + const id = expected[index] as string; + pending = id; + const result = await sendImported(state, writer, event, signal); + pending = undefined; + if (result !== id) + return report("rejected", index, result ?? "Delivery failed"); + ids.push(id); + rememberIds(state, channelId, [id]); + opts.onProgress?.({ published: ids.length, total }); + } + } catch (error) { + if (pending) { + // An event already handed to the relay may still land; the report + // counts it only if it did, and a refusal leaves no journal entry. + const item = await settledWithin( + state, + writer, + pending, + SETTLE_AFTER_STOP_MS, + ); + if (deliveredOk(item)) { + ids.push(pending); + rememberIds(state, channelId, [pending]); + } else if (item) void writer.dismiss(pending).catch(() => {}); + } + if (signal?.aborted) return report("stopped", ids.length, "Stopped"); + return report( + "rejected", + ids.length, + error instanceof Error ? error.message : String(error), + ); + } + return report("done"); + } + + attachmentTags(input: AttachmentTagsInput): ImportedAttachment { + return predictAttachment(current(stateOf(this)), input).attachment; + } + + async uploadAttachment( + file: Blob, + name: string, + sha256Hex: string, + signal?: AbortSignal, + options?: { channelId?: string }, + ): Promise { + const session = current(stateOf(this)); + const active = signal ?? new AbortController().signal; + const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer()); + active.throwIfAborted(); + const predicted = predictAttachment(session, { + sha256Hex, + name, + size: file.size, + head, + }); + const attachments = session.attachments; + if (!attachments) + throw new Error("Uploads are unavailable on this connection."); + const type = file.type || predicted.mime; + const upload = new File([file], attachmentName(name), { type }); + const result = options?.channelId + ? await attachments.upload(upload, options.channelId, active) + : attachments.uploadForNewChat + ? await attachments.uploadForNewChat(upload, active) + : undefined; + if (!result) + throw new Error("Choose the destination conversation before uploading."); + if ( + result.sha256 !== sha256Hex || + result.url !== predicted.url || + result.type !== predicted.mime || + result.size !== file.size + ) + throw new Error( + "The server stored this file differently than other participants will expect, so it cannot be attached. Import it without the file instead.", + ); + return predicted.attachment; + } + + async readBack( + proposalId: string, + signal?: AbortSignal, + ): Promise { + const state = stateOf(this); + const session = current(state); + const entry = await entryFor(state, proposalId, signal); + const { proposal } = entry; + const events = await readAll( + session, + { + kinds: [9, 7], + "#h": [proposal.channelId], + authors: proposal.content.participants.map((item) => item.pubkey), + since: proposal.content.range.from, + until: proposal.content.range.to + 1, + limit: READ_PAGE, + }, + signal, + ); + const imported: ReadBackEvent[] = []; + for (const event of events) { + if ( + !event.tags.some((tag) => tag[0] === "import" && tag[1] === proposalId) + ) + continue; + const source = event.tags.find((tag) => tag[0] === "source"); + imported.push( + Object.freeze({ + id: event.id, + pubkey: event.pubkey, + kind: event.kind, + source_ref: source?.[2] ?? "", + created_at: event.created_at, + }), + ); + } + rememberIds( + state, + proposal.channelId, + imported.map((item) => item.id), + ); + return Object.freeze({ + events: Object.freeze( + imported.sort( + (a, b) => a.created_at - b.created_at || a.id.localeCompare(b.id), + ), + ), + }); + } +} + +/** The host's conversation import service; `reviews` must come from + * `createImportReviews`. */ +export function createConversationImportHost( + ctx: Context, + relay: RelayData, + reviews: ImportReviews, + options: ConversationImportOptions = {}, +) { + return new ConversationImportHost(ctx, relay, reviews, options, MINT); +} + +function current(state: HostState): RelaySession { + const session = state.relay.snapshot().session; + if (state.session !== session) bind(state); + return session; +} + +function viewerOf(session: RelaySession) { + const viewer = session.viewer; + if (!viewer) throw new Error("Sign in to import conversations."); + return viewer; +} + +function writerOf(state: HostState, session: RelaySession) { + const writer = claimImportWriter(session, state); + if (!writer) + throw new Error("This connection cannot publish conversation imports."); + return writer; +} + +function membershipOf( + state: HostState, + channelId: string, +): MembershipView | undefined { + const channel = state.session?.channels + .list() + .channels.find((item) => item.id === channelId); + if (!channel?.members) return; + return Object.freeze({ + members: [...channel.members], + channelType: channel.channelType === "dm" ? "dm" : "channel", + visibility: channel.visibility ?? (channel.private ? "private" : "unknown"), + }); +} + +function eventIdOf(unsigned: UnsignedImportEvent) { + if (!HEX64.test(unsigned.pubkey)) + throw new Error("The event author must be a 64-character hex key."); + return getEventHash({ + pubkey: unsigned.pubkey, + created_at: unsigned.created_at, + kind: unsigned.kind, + tags: unsigned.tags.map((tag) => [...tag]), + content: unsigned.content, + }); +} + +function existsIn(state: HostState, channelId: string, eventId: string) { + if (state.known.get(channelId)?.has(eventId)) return true; + const session = state.session; + const writer = session && claimImportWriter(session, state); + return !!writer?.local + .snapshot() + .some( + (item) => + item.event.id === eventId && + deliveredOk(item) && + item.event.tags.some(([name, id]) => name === "h" && id === channelId), + ); +} + +function member( + pubkey: string, + verified: VerifiedProfileView | undefined, + note?: string, +): ReviewMember { + return Object.freeze({ + pubkey, + ...(verified ? { verified } : {}), + ...(note ? { note } : {}), + }); +} + +function selfVerified(session: RelaySession, pubkey: string) { + const verified = session.profiles.snapshot().get(pubkey)?.verified; + return verified && verifiedView(pubkey, verified); +} + +function displayName( + session: RelaySession, + verified: ReadonlyMap, + pubkey: string, +) { + const profile = session.profiles.snapshot().get(pubkey); + return ( + verified.get(pubkey)?.displayName ?? + profile?.verified?.displayName ?? + profile?.name ?? + fingerprint(pubkey).slice(0, 8) + ); +} + +function destinationText( + session: RelaySession, + name: string, + view: MembershipView, + verified: ReadonlyMap, +) { + if (view.channelType === "dm") + return `Direct message with ${formatList( + view.members + .filter((key) => key !== session.viewer) + .map((key) => displayName(session, verified, key)), + )}`; + const type = + view.visibility === "private" + ? "private channel" + : view.visibility === "public" + ? "public channel" + : "channel"; + return `#${name} (${type})`; +} + +function excludedFact(content: ParsedProposal["content"]) { + return content.excluded_authors + ? [ + { + label: "Not imported", + value: `Messages from ${content.excluded_authors} ${content.excluded_authors === 1 ? "person" : "people"} without a verified Buzz identity`, + }, + ] + : []; +} + +/** Destination refusals: the human gate offers no approval for these. */ +function destinationRefusal( + content: ParsedProposal["content"], + view: MembershipView, + pubkeys: readonly string[], + verified: ReadonlyMap, +): string | undefined { + const unverified = pubkeys.filter((key) => !verified.has(key)); + if (unverified.length) + return `${unverified.length === 1 ? "One participant has" : `${unverified.length} participants have`} no verified Buzz identity.`; + const outside = pubkeys.filter((key) => !view.members.includes(key)); + if (outside.length) + return `${outside.length === 1 ? "One participant is" : `${outside.length} participants are`} not a member of the destination.`; + const direct = + content.source.kind === "dm" || content.source.kind === "group_dm"; + if (direct !== (view.channelType === "dm")) + return direct + ? "A direct message can only be imported into a direct message." + : "A channel can only be imported into a channel."; + if ( + direct && + (view.members.length !== pubkeys.length || + view.members.some((key) => !pubkeys.includes(key))) + ) + return "The direct message members differ from the source conversation's."; + if (content.source.kind === "private_channel") { + if (view.visibility !== "private") + return "A private channel can only be imported into a private channel."; + const extra = view.members.filter((key) => !pubkeys.includes(key)); + if (extra.length) + return `${extra.length === 1 ? "One member" : `${extra.length} members`} of the destination ${extra.length === 1 ? "is" : "are"} not in the source channel.`; + } + if (content.source.kind === "public_channel" && view.visibility !== "public") + return "A public channel can only be imported into a public channel."; +} + +/** The URL the relay assigns a file: `/media/.` on the + * community origin, with the type and extension the relay sniffs from the + * file's first bytes. */ +function predictAttachment(session: RelaySession, input: AttachmentTagsInput) { + const { sha256Hex, name, size } = input; + if (typeof sha256Hex !== "string" || !HEX64.test(sha256Hex)) + throw new Error("The file hash must be 64 lowercase hex characters."); + if (typeof name !== "string") throw new Error("The file needs a name."); + const { mime, ext } = relayMediaType(input.head, size); + const origin = splitPartition(session.scope)?.communityOrigin; + let base: URL | undefined; + try { + base = origin ? new URL(origin) : undefined; + } catch { + base = undefined; + } + if (!base || (base.protocol !== "https:" && base.protocol !== "http:")) + throw new Error("Uploads are unavailable on this connection."); + const url = new URL(`/media/${sha256Hex}.${ext}`, base).href; + const label = attachmentName(name); + const attachment: ImportedAttachment = Object.freeze({ + url, + tags: [ + [ + "imeta", + `url ${url}`, + `m ${mime}`, + `size ${size}`, + `x ${sha256Hex}`, + `filename ${label}`, + ], + ], + markdown: attachmentMarkdown(label, { url, type: mime }), + }); + return { attachment, mime, url }; +} + +/** The relay-signed member list (kind 39002) for a conversation. `settle` + * retries a short while for a roster that has not caught up yet. */ +async function readMembers( + state: HostState, + session: RelaySession, + channelId: string, + signal?: AbortSignal, + settle?: (members: readonly string[]) => boolean, +): Promise { + const read = session.snapshotRead; + const authority = session.relayAuthor; + if (!read || !authority) throw new Error(MEMBERS_UNCONFIRMED); + let members: string[] | undefined; + for (let attempt = 0; attempt < (settle ? ROSTER_ATTEMPTS : 1); attempt++) { + if (attempt) await state.wait(ROSTER_RETRY_MS, signal); + const events = await read( + [ + { + kinds: [ROSTER_KIND], + authors: [authority], + "#d": [channelId], + limit: 1, + consistency: "strong", + }, + ], + { signal }, + ); + const roster = events + .filter( + (event) => + event.kind === ROSTER_KIND && + event.pubkey === authority && + event.tags.some((tag) => tag[0] === "d" && tag[1] === channelId), + ) + .sort((a, b) => b.created_at - a.created_at)[0]; + if (!roster) continue; + members = [ + ...new Set( + roster.tags + .filter((tag) => tag[0] === "p" && HEX64.test(tag[1] ?? "")) + .map((tag) => tag[1] as string), + ), + ]; + if (!settle || settle(members)) break; + } + if (!members) throw new Error(MEMBERS_UNCONFIRMED); + return members; +} + +async function readVerified( + session: RelaySession, + pubkeys: readonly string[], + signal?: AbortSignal, +): Promise> { + const result = new Map(); + const unique = [...new Set(pubkeys)].filter((key) => HEX64.test(key)); + const authority = session.relayAuthor; + if (!unique.length) return result; + if (!session.snapshotRead || !authority) { + for (const pubkey of unique) { + const view = selfVerified(session, pubkey); + if (view) result.set(pubkey, view); + } + return result; + } + for (let start = 0; start < unique.length; start += VERIFIED_PROFILE_BATCH) { + const batch = unique.slice(start, start + VERIFIED_PROFILE_BATCH); + const events = await session.snapshotRead( + [ + { + kinds: [VERIFIED_PROFILE_KIND], + authors: [authority], + "#d": batch, + limit: batch.length, + }, + ], + { signal }, + ); + const newest = new Map(); + for (const event of events) { + const subject = event.tags.find((tag) => tag[0] === "d")?.[1]; + if (!subject || !batch.includes(subject)) continue; + const prior = newest.get(subject); + if (!prior || event.created_at > prior.created_at) + newest.set(subject, event); + } + for (const [subject, event] of newest) { + const verified = readVerifiedProfile( + event, + { pubkey: authority, multipleIssuers: false }, + true, + ); + if (verified) result.set(subject, verifiedView(subject, verified)); + } + } + return result; +} + +/** Every page of a filter, newest first, by the relay's composite cursor. */ +async function readAll( + session: RelaySession, + filter: ReadFilter, + signal?: AbortSignal, +): Promise { + const read = session.snapshotRead; + if (!read) throw new Error("This connection cannot read import history."); + const seen = new Map(); + let cursor: { until: number; before_id: string } | undefined; + for (;;) { + const page = await read([{ ...filter, ...(cursor ?? {}) }], { signal }); + let added = 0; + for (const event of page) + if (!seen.has(event.id)) { + seen.set(event.id, event); + added++; + } + const oldest = [...page].sort( + (a, b) => a.created_at - b.created_at || b.id.localeCompare(a.id), + )[0]; + if (page.length < filter.limit || !added || !oldest) break; + cursor = { until: oldest.created_at, before_id: oldest.id }; + } + return [...seen.values()]; +} + +function references(event: PreparedImportEvent) { + return event.tags + .filter((tag) => tag[0] === "e" && HEX64.test(tag[1] ?? "")) + .map((tag) => tag[1] as string); +} + +function rememberIds( + state: HostState, + channelId: string, + ids: readonly string[], +) { + let known = state.known.get(channelId); + if (!known) { + known = new Set(); + state.known.set(channelId, known); + } + for (const id of ids) known.add(id); +} + +async function delivered( + writer: ImportWriter, + id: string, + signal?: AbortSignal, +) { + const item = await settled(writer, id, signal); + if (deliveredOk(item)) return; + void writer.dismiss(id).catch(() => {}); + throw new Error(failure(item)); +} + +/** Publishes one prepared event at its original time. Returns its id, or the + * relay's refusal text verbatim. A rate limit waits and retries; any other + * outcome is final for this run and leaves no journal entry behind. */ +async function sendImported( + state: HostState, + writer: ImportWriter, + event: PreparedImportEvent, + signal?: AbortSignal, +): Promise { + const id = writer.sendAt(event); + const existing = writer.local.snapshot().find((item) => item.event.id === id); + if (existing?.delivery === "failed" || existing?.delivery === "unknown") + writer.retry(id); + for (;;) { + const item = await settled(writer, id, signal); + if (deliveredOk(item)) return id; + const reason = failure(item); + if (item?.delivery === "failed" && /rate-limited:/.test(reason)) { + await state.wait(RATE_LIMIT_WAIT_MS, signal); + writer.retry(id); + continue; + } + void writer.dismiss(id).catch(() => {}); + return reason; + } +} + +/** NIP-CI parent wait: poll for another participant's parent every 5 seconds + * while their published counters move; give up after 10 minutes without + * progress. */ +async function waitForEvent( + state: HostState, + session: RelaySession, + entry: Entry, + channelId: string, + id: string, + progress: (waitingFor: string) => void, + signal?: AbortSignal, +): Promise { + const viewer = session.viewer; + const others = entry.proposal.content.participants.filter( + (item) => + item.pubkey !== viewer && + !entry.snapshot?.completed.includes(item.pubkey), + ); + const names = others.map((item) => + displayName(session, new Map(), item.pubkey), + ); + const waitingFor = + names.length === 1 ? (names[0] ?? "") : "other participants"; + const counted = () => + others.reduce((sum, item) => { + const counts = entry.snapshot?.published[item.pubkey]; + return sum + (counts ? counts.messages + counts.reactions : 0); + }, 0); + let last = counted(); + let lastProgress = state.clock(); + for (;;) { + progress(waitingFor); + const found = session.snapshotRead + ? await session.snapshotRead( + [{ ids: [id], "#h": [channelId], limit: 1 }], + { signal }, + ) + : []; + if (found.some((event) => event.id === id)) { + rememberIds(state, channelId, [id]); + return true; + } + if (state.known.get(channelId)?.has(id)) return true; + await refreshSnapshot(state, entry, signal).catch(() => {}); + const stopped = inactiveReason(entry, state.now(), ""); + if (stopped) return stopped; + const now = counted(); + if (now > last) { + last = now; + lastProgress = state.clock(); + } + if (state.clock() - lastProgress >= PARENT_STALL_MS) + return `waiting for ${waitingFor} to import`; + await state.wait(PARENT_POLL_MS, signal); + } +} + +async function entryFor( + state: HostState, + proposalId: string, + signal?: AbortSignal, +): Promise { + if (!HEX64.test(proposalId)) throw new Error("Unknown import proposal."); + const known = state.entries.get(proposalId); + if (known) return known; + const session = current(state); + const events = session.snapshotRead + ? await session.snapshotRead( + [{ ids: [proposalId], kinds: [IMPORT_PROPOSAL_KIND], limit: 1 }], + { signal }, + ) + : []; + ingest(state, events); + const entry = state.entries.get(proposalId); + if (!entry) throw new Error("Unknown import proposal."); + await refreshSnapshot(state, entry, signal).catch(() => {}); + return entry; +} + +async function refreshSnapshot( + state: HostState, + entry: Entry, + signal?: AbortSignal, +) { + const session = state.session; + if (!session?.snapshotRead || !session.relayAuthor) return; + const events = await session.snapshotRead( + [ + { + kinds: [IMPORT_SNAPSHOT_KIND], + authors: [session.relayAuthor], + "#d": [entry.proposal.id], + limit: 1, + }, + ], + { signal }, + ); + ingest(state, events); +} + +function ingest(state: HostState, events: readonly RelayEvent[]) { + const session = state.session; + let changed = false; + for (const event of events) { + if (event.kind === IMPORT_PROPOSAL_KIND) { + if (state.entries.has(event.id)) continue; + const proposal = parseProposal(event); + if (!proposal) continue; + const entry: Entry = { proposal }; + const orphan = state.orphans.get(event.id); + if (orphan?.channelId === proposal.channelId) entry.snapshot = orphan; + state.orphans.delete(event.id); + state.entries.set(event.id, entry); + changed = true; + } else if (event.kind === IMPORT_SNAPSHOT_KIND) { + const snapshot = parseSnapshot(event, session?.relayAuthor); + if (!snapshot) continue; + const entry = state.entries.get(snapshot.proposalId); + if (!entry) { + const prior = state.orphans.get(snapshot.proposalId); + if (!prior || snapshot.createdAt >= prior.createdAt) + state.orphans.set(snapshot.proposalId, snapshot); + continue; + } + if ( + entry.proposal.channelId === snapshot.channelId && + (!entry.snapshot || snapshot.createdAt >= entry.snapshot.createdAt) + ) { + entry.snapshot = snapshot; + changed = true; + } + } else if (event.kind === 9 || event.kind === 7) { + const channelId = event.tags.find((tag) => tag[0] === "h")?.[1]; + if (channelId) rememberIds(state, channelId, [event.id]); + } + } + if (changed) publishViews(state); +} + +function publishViews(state: HostState) { + const now = state.now(); + state.views = Object.freeze( + [...state.entries.values()] + .map((entry) => sessionView(entry, now)) + .sort( + (a, b) => + b.proposedAt - a.proposedAt || + a.proposalId.localeCompare(b.proposalId), + ), + ); + for (const listener of [...state.listeners]) { + try { + listener(state.views); + } catch (error) { + console.error("Conversation import listener failed", error); + } + } +} + +/** Follows the relay session: a new session starts a new read model. */ +function bind(state: HostState) { + const snapshot = state.relay.snapshot(); + const session = snapshot.session; + if (state.session !== session) { + claimImportWriter(session, state); + state.stopLive?.(); + state.session = session; + state.loaded = false; + state.entries.clear(); + state.orphans.clear(); + state.known.clear(); + state.stopLive = session.subscribeLive((batch) => + ingest(state, batch.events), + ); + publishViews(state); + } + if (!state.loaded && snapshot.status === "ready" && session.viewer) { + state.loaded = true; + void load(state, session).catch(() => { + if (state.session === session) state.loaded = false; + }); + } +} + +async function load(state: HostState, session: RelaySession) { + const viewer = session.viewer; + if (!viewer || !session.snapshotRead) return; + const filters: ReadFilter[] = [ + { kinds: [IMPORT_PROPOSAL_KIND], "#p": [viewer], limit: READ_PAGE }, + { kinds: [IMPORT_PROPOSAL_KIND], authors: [viewer], limit: READ_PAGE }, + ...(session.relayAuthor + ? [ + { + kinds: [IMPORT_SNAPSHOT_KIND], + authors: [session.relayAuthor], + "#p": [viewer], + limit: READ_PAGE, + }, + ] + : []), + ]; + for (const filter of filters) { + const events = await readAll(session, filter); + if (state.session !== session) return; + ingest(state, events); + } +} + +export type { ImportReview }; diff --git a/src/plugins/author.ts b/src/plugins/author.ts index e0d1f74a3a..db7349be30 100644 --- a/src/plugins/author.ts +++ b/src/plugins/author.ts @@ -161,3 +161,23 @@ export type { SessionSnapshot, AuthenticatedRequest, } from "../features/federated-identity/service"; + +export type { + ConversationImportService, + ImportSourceKind, + VerifiedProfileView, + ProposalParticipant, + ImportProposalInput, + ImportStatus, + ImportCounts, + ImportSessionView, + PreparedImportEvent, + UnsignedImportEvent, + PublishProgress, + PublishReport, + ReadBackEvent, + ReadBackReport, + MembershipView, + ImportedAttachment, + AttachmentTagsInput, +} from "../features/conversation-import/types"; diff --git a/tests/fixtures/message-gallery/examples.ts b/tests/fixtures/message-gallery/examples.ts index 163866a35d..47e1e17fe4 100644 --- a/tests/fixtures/message-gallery/examples.ts +++ b/tests/fixtures/message-gallery/examples.ts @@ -1,6 +1,12 @@ import { eventDto } from "../../../src/features/relay/events"; import { foldMessages } from "../../../src/features/relay/fold"; import { keypair, signed } from "../../../src/features/relay/testing"; +import { + importedMessages, + importProposal, + importRecords, + importRelayKey, +} from "./import-examples"; import type { ChannelMessage, Profile, @@ -931,4 +937,32 @@ export const groups: Group[] = [ }, ], }, + { + id: "conversation-import", + title: "Conversation import", + description: + "A consented import from another tool: the proposal card, its system lines, and imported history.", + examples: [ + { + id: "import-proposal", + title: "Import proposal", + description: + "Verified names, usernames and fingerprints for each participant, the counts and the manifest fingerprint.", + rows: foldMessages("studio", importRelayKey, [importProposal]), + }, + { + id: "import-records", + title: "Consent and completion", + description: "Import records render as quiet system lines.", + rows: foldMessages("studio", importRelayKey, importRecords), + }, + { + id: "imported-messages", + title: "Imported messages", + description: + "Imported history shows its source and original time; a source edit shows the edited marker.", + rows: foldMessages("studio", importRelayKey, importedMessages), + }, + ], + }, ]; diff --git a/tests/fixtures/message-gallery/import-examples.ts b/tests/fixtures/message-gallery/import-examples.ts new file mode 100644 index 0000000000..5bc04bf5e7 --- /dev/null +++ b/tests/fixtures/message-gallery/import-examples.ts @@ -0,0 +1,168 @@ +import { getEventHash } from "nostr-tools"; +import { + completeTemplate, + consentTemplate, + proposalTemplate, +} from "../../../src/features/conversation-import/protocol"; +import type { + ConversationImportService, + ImportProposalInput, + ImportSessionView, +} from "../../../src/features/conversation-import/types"; +import type { Profile } from "../../../src/features/relay/contracts"; +import type { RelayData } from "../../../src/features/relay/service"; + +// Synthetic identities shared with the other gallery examples. +const reader = "a".repeat(64); +const teammate = "b".repeat(64); +const relayKey = "e".repeat(64); +const channel = "studio"; +const proposedAt = 1_790_078_400; + +const input: ImportProposalInput = { + channelId: channel, + source: { + type: "slack", + conversation: "1".repeat(64), + kind: "private_channel", + label: "#design-review", + }, + range: { from: 1_788_000_000, to: 1_790_000_000 }, + participants: [ + { + pubkey: reader, + source_user: "2".repeat(64), + messages: 214, + reactions: 58, + }, + { + pubkey: teammate, + source_user: "3".repeat(64), + messages: 167, + reactions: 41, + }, + ], + excluded_authors: 1, + manifest: "4f9c2a1e7b3d8c60".repeat(4), + expires_at: proposedAt + 30 * 86_400, +}; + +function stamp( + pubkey: string, + template: { kind: number; content: string; tags: string[][] }, + created_at: number, +) { + const unsigned = { ...template, pubkey, created_at }; + return { ...unsigned, id: getEventHash(unsigned), sig: "0".repeat(128) }; +} + +export const importProposal = stamp( + teammate, + proposalTemplate(input), + proposedAt, +); +const record = { + id: importProposal.id, + channelId: channel, + manifest: input.manifest, + proposer: teammate, +}; +export const importRecords = [ + stamp( + reader, + consentTemplate(record, "accept", "2".repeat(64)), + proposedAt + 60, + ), + stamp( + reader, + completeTemplate(importProposal.id, channel, { + messages: 214, + reactions: 58, + }), + proposedAt + 120, + ), +]; +export const importedMessages = [ + stamp( + teammate, + { + kind: 9, + content: "Here is the second pass on the onboarding flow.", + tags: [ + ["h", channel], + ["import", importProposal.id], + ["source", "slack", "1789990000.000100"], + ], + }, + 1_789_990_000, + ), + stamp( + reader, + { + kind: 9, + content: "Looks good. I tightened the copy on step two.", + tags: [ + ["h", channel], + ["import", importProposal.id], + ["source", "slack", "1789990120.000200"], + ["source-edited", "1"], + ], + }, + 1_789_990_120, + ), +]; +export { relayKey as importRelayKey }; + +const verified = (displayName: string, username: string): Profile => ({ + name: displayName, + verified: { + displayName, + username, + issuerLabel: "Example Directory", + verifiedAt: 1_780_000_000, + status: "checked", + multipleIssuers: false, + }, +}); +const importProfiles = new Map([ + [reader, verified("Alex Morgan", "alex.morgan")], + [teammate, verified("Sam Rivera", "sam.rivera")], +]); +const session = { + profiles: { + snapshot: () => importProfiles, + subscribe: () => () => {}, + ensure: async () => {}, + }, + channels: { list: () => ({ channels: [] }) }, +}; +const connection = { session, viewer: reader, status: "ready" }; +export const importRelay = { + snapshot: () => connection, + subscribe: () => () => {}, +} as unknown as RelayData; + +const view: ImportSessionView = { + proposalId: importProposal.id, + channelId: channel, + proposer: teammate, + proposedAt, + proposal: (({ channelId: _, ...rest }) => rest)(input), + status: "proposed", + required: [reader, teammate], + consents: { [teammate]: "accept" }, + published: {}, + completed: [], + expires_at: input.expires_at, + confirmed: true, +}; +const views = [view]; +export const importService = { + session: (id: string) => (id === view.proposalId ? view : undefined), + subscribe: (cb: (sessions: readonly ImportSessionView[]) => void) => { + cb(views); + return () => {}; + }, + consent: async () => {}, + withdraw: async () => {}, +} as unknown as ConversationImportService; diff --git a/tests/fixtures/message-gallery/main.tsx b/tests/fixtures/message-gallery/main.tsx index 345449409e..c8d8231087 100644 --- a/tests/fixtures/message-gallery/main.tsx +++ b/tests/fixtures/message-gallery/main.tsx @@ -7,6 +7,9 @@ import { createRoot } from "react-dom/client"; import { continuesMessageGroup } from "../../../src/features/messages/message-grouping"; import { MessageRow } from "../../../src/features/messages/MessageRow"; import { MembershipRow } from "../../../src/features/messages/MembershipRow"; +import { ImportNoticeRow } from "../../../src/features/messages/ImportNoticeRow"; +import { ImportConsentCard } from "../../../src/features/conversation-import/ImportCards"; +import { importRelay, importService } from "./import-examples"; import { Button } from "../../../src/shared/design-system/ui/Button"; import { LinkLabel, linkKind } from "../../../src/bundled/links/InlineLink"; import { DiffMessage } from "../../../src/bundled/diffs/DiffMessage"; @@ -86,6 +89,21 @@ const messages: readonly Contribution[] = [ matches: (row) => !!row.diff, component: DiffMessage, }, + { + id: "import-proposal", + key: "gallery/import-proposal", + pluginId: "gallery", + revision: "1", + title: "Conversation import proposal", + matches: (row) => row.importRecord?.type === "proposal", + component: ({ message }) => ( + + ), + }, ]; const codeBlocks: readonly Contribution[] = [ { @@ -138,6 +156,14 @@ function Specimen({ example }: { example: Example }) { agentPubkeys={agentPubkeys} day={!!example.day && index === 0} /> + ) : row.importRecord && row.importRecord.type !== "proposal" ? ( + ) : ( Date: Mon, 2 Nov 2026 19:54:37 -0600 Subject: [PATCH 6/6] feat(import): wait out the relay's import session warm-up The relay refuses imported events for a short time after a session turns active and states when it will accept them in the snapshot's accepts_after tag. The snapshot read model carries it as acceptsAfter on this device's clock, moved earlier when the snapshot shows the relay's clock running ahead. publish waits until then before signing the first event, reporting progress phase "starting", and a cancel during the wait stops the run. A "session warming" refusal backs off to acceptsAfter, or 5 seconds without one, and publishes the same event again. The consent card counts down to the start while the import is active. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- .../conversation-import/ImportCards.test.tsx | 45 +++++ .../conversation-import/ImportCards.tsx | 31 +++- .../conversation-import/protocol.test.ts | 26 +++ src/features/conversation-import/protocol.ts | 10 ++ .../conversation-import/service.test.ts | 157 +++++++++++++++++- src/features/conversation-import/service.ts | 56 ++++++- src/features/conversation-import/types.ts | 11 +- 7 files changed, 327 insertions(+), 9 deletions(-) diff --git a/src/features/conversation-import/ImportCards.test.tsx b/src/features/conversation-import/ImportCards.test.tsx index a304674b25..58c28791d2 100644 --- a/src/features/conversation-import/ImportCards.test.tsx +++ b/src/features/conversation-import/ImportCards.test.tsx @@ -1,5 +1,6 @@ // @vitest-environment jsdom import { + act, cleanup, fireEvent, render, @@ -236,6 +237,50 @@ it("counts people done against every participant", () => { expect(screen.getByText(/1 of 2 people done/)).toBeTruthy(); }); +it("counts down to the relay's start time while the import warms up", () => { + vi.useFakeTimers({ toFake: ["Date", "setInterval", "clearInterval"] }); + try { + vi.setSystemTime(now * 1000); + const { row, relay, service } = harness({ + status: "active", + acceptsAfter: now + 65, + }); + render(); + expect(screen.getByText(/^Starting at .+ \(in 1:05\)$/)).toBeTruthy(); + act(() => vi.advanceTimersByTime(6_000)); + expect(screen.getByText(/\(in 0:59\)$/)).toBeTruthy(); + act(() => vi.advanceTimersByTime(59_000)); + expect(screen.getByText("Importing")).toBeTruthy(); + } finally { + vi.useRealTimers(); + } +}); + +it("shows no countdown without a start time or before the import is active", () => { + const active = harness({ status: "active" }); + render( + , + ); + expect(screen.getByText("Importing")).toBeTruthy(); + cleanup(); + const proposed = harness({ + status: "proposed", + acceptsAfter: Date.now() / 1000 + 60, + }); + render( + , + ); + expect(screen.queryByText(/Starting at/)).toBeNull(); +}); + it("shows a compact imported marker on continuation rows", () => { render( Date.now() / 1000); + useEffect(() => { + if (at === undefined) return; + const tick = () => { + const current = Date.now() / 1000; + setNow(current); + if (current >= at) clearInterval(timer); + }; + const timer = setInterval(tick, 1000); + tick(); + return () => clearInterval(timer); + }, [at]); + return at === undefined ? 0 : Math.max(0, Math.ceil(at - now)); +} + /** The live read model, seeded by one relay read so that members outside * the session still see its current status. */ function useImportSession( @@ -98,6 +123,8 @@ export function ImportConsentCard({ () => session?.profiles.snapshot() ?? emptyProfiles, ); const view = useImportSession(service, proposal?.id ?? ""); + const startsAt = view?.status === "active" ? view.acceptsAfter : undefined; + const startsIn = useSecondsUntil(startsAt); const [pending, setPending] = useState(false); const [error, setError] = useState(); const participantKeys = @@ -178,7 +205,9 @@ export function ImportConsentCard({ Import {content.source.label} from {sourceLabel(content.source.type)}

- {STATUS_TEXT[status]} + {startsAt !== undefined && startsIn > 0 + ? `Starting at ${formatTime(startsAt)} (in ${Math.floor(startsIn / 60)}:${String(startsIn % 60).padStart(2, "0")})` + : STATUS_TEXT[status]} {status === "proposed" && view?.confirmed ? ` (${accepted} of ${content.participants.length} accepted)` : ""} diff --git a/src/features/conversation-import/protocol.test.ts b/src/features/conversation-import/protocol.test.ts index 2f4bc8e5c6..ebe3b07020 100644 --- a/src/features/conversation-import/protocol.test.ts +++ b/src/features/conversation-import/protocol.test.ts @@ -253,6 +253,32 @@ describe("records", () => { ); expect(parseSnapshot(signedFrom(alice, snapshot), relay)).toBeUndefined(); }); + + it("reads the warm-up time from a snapshot and ignores a malformed one", () => { + const snapshot = (value?: string) => ({ + kind: 30623, + content: JSON.stringify({ + v: 1, + status: "active", + required: [alice], + consents: { [alice]: "accept" }, + published: {}, + completed: [], + expires_at: now + 60, + }), + tags: [ + ["d", proposalId], + ["h", channel], + ...(value === undefined ? [] : [["accepts_after", value]]), + ], + }); + const read = (value?: string) => + parseSnapshot(signedFrom(relay, snapshot(value)), relay); + expect(read(String(now + 90))?.accepts_after).toBe(now + 90); + expect(read()).not.toHaveProperty("accepts_after"); + for (const value of ["soon", "-5", "1.5", ""]) + expect(read(value)).not.toHaveProperty("accepts_after"); + }); }); describe("imported events", () => { diff --git a/src/features/conversation-import/protocol.ts b/src/features/conversation-import/protocol.ts index 27f563948a..e05030a80c 100644 --- a/src/features/conversation-import/protocol.ts +++ b/src/features/conversation-import/protocol.ts @@ -455,6 +455,9 @@ export type ParsedSnapshot = Readonly<{ published: Readonly>; completed: readonly string[]; expires_at: number; + /** Relay-clock Unix seconds before which the relay refuses imported events + * while the session warms up. */ + accepts_after?: number; }>; /** Only the community's relay key may state session status. */ @@ -506,6 +509,12 @@ export function parseSnapshot( reactions: value.reactions, }); } + // A malformed value is ignored: a warming refusal still says when to retry. + const acceptsAfter = tagValue(event.tags, "accepts_after"); + const accepts_after = + acceptsAfter && /^\d{1,15}$/.test(acceptsAfter) + ? Number(acceptsAfter) + : undefined; return Object.freeze({ proposalId, channelId, @@ -516,6 +525,7 @@ export function parseSnapshot( published: Object.freeze(published), completed: Object.freeze(body.completed.map(String)), expires_at: body.expires_at, + ...(accepts_after !== undefined ? { accepts_after } : {}), }); } diff --git a/src/features/conversation-import/service.test.ts b/src/features/conversation-import/service.test.ts index f0b44b09f8..007c11d4e9 100644 --- a/src/features/conversation-import/service.test.ts +++ b/src/features/conversation-import/service.test.ts @@ -84,9 +84,19 @@ function verifiedRecord(pubkey: string, username: string, displayName: string) { ); } -function snapshotRecord(proposalId: string, status: string) { +function snapshotRecord( + proposalId: string, + status: string, + warmUp: { + acceptsAfter?: number | undefined; + createdAt?: number | undefined; + } = {}, +) { return eventDto( signed(authority, { + ...(warmUp.createdAt !== undefined + ? { created_at: warmUp.createdAt } + : {}), kind: 30623, content: JSON.stringify({ v: 1, @@ -103,6 +113,9 @@ function snapshotRecord(proposalId: string, status: string) { ["h", channel], ["p", viewer], ["p", partner], + ...(warmUp.acceptsAfter !== undefined + ? [["accepts_after", String(warmUp.acceptsAfter)]] + : []), ], }), ); @@ -143,6 +156,10 @@ function setup( supported?: boolean; channel?: Partial; roster?: (channelId: string) => readonly string[] | undefined; + acceptsAfter?: number; + snapshotAt?: number; + /** Waits of this length block until aborted. */ + hold?: (ms: number) => boolean; } = {}, ) { const current = options.proposal ?? proposal; @@ -233,7 +250,16 @@ function setup( ); if (filter.kinds?.includes(30623)) return options.status - ? [snapshotRecord((filter["#d"] as string[])[0] ?? "", options.status)] + ? [ + snapshotRecord( + (filter["#d"] as string[])[0] ?? "", + options.status, + { + acceptsAfter: options.acceptsAfter, + createdAt: options.snapshotAt, + }, + ), + ] : []; if (filter.kinds?.includes(39002)) { const id = (filter["#d"] as string[])[0] ?? ""; @@ -332,6 +358,13 @@ function setup( clock: () => 0, wait: async (ms, signal) => { waits.push(ms); + if (options.hold?.(ms)) + await new Promise((_, reject) => { + if (signal?.aborted) reject(signal.reason); + signal?.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }); // The give-up wait after a stop resolves only when a test expires it. if (ms === 30_000) await new Promise((resolve, reject) => { @@ -498,6 +531,126 @@ it("publishes paced events in order and reports their ids", async () => { ); expect(waits).toEqual([125, 125]); expect(progress).toHaveBeenLastCalledWith({ published: 3, total: 3 }); + // Without a warm-up time from the relay, publishing starts at once. + expect(progress).not.toHaveBeenCalledWith( + expect.objectContaining({ phase: "starting" }), + ); + expect(service.session(proposal.id)).not.toHaveProperty("acceptsAfter"); +}); + +it("waits for the relay's warm-up time before signing the first event", async () => { + const { service, sent, waits } = setup({ + status: "active", + acceptsAfter: now + 90, + }); + const progress = vi.fn((update: { phase?: string }) => { + if (update.phase) expect(sent).toHaveLength(0); + }); + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1"), message(1_735_732_801, "2")], + { onProgress: progress }, + ); + expect(report.status).toBe("done"); + expect(waits).toEqual([90_000, 125]); + expect(progress).toHaveBeenNthCalledWith(1, { + phase: "starting", + published: 0, + total: 2, + }); + expect(service.session(proposal.id)?.acceptsAfter).toBe(now + 90); +}); + +it("moves the start earlier by how far the relay's clock runs ahead", async () => { + const { service, waits } = setup({ + status: "active", + acceptsAfter: now + 90, + snapshotAt: now + 20, + }); + const report = await service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + ); + expect(report.status).toBe("done"); + expect(waits).toEqual([70_000]); + expect(service.session(proposal.id)?.acceptsAfter).toBe(now + 70); +}); + +it("stops without signing when cancelled during the warm-up wait", async () => { + const { service, sent, waits } = setup({ + status: "active", + acceptsAfter: now + 90, + hold: (ms) => ms === 90_000, + }); + const controller = new AbortController(); + const run = service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + controller.signal, + ); + await vi.waitFor(() => expect(waits).toContain(90_000)); + controller.abort(); + expect(await run).toMatchObject({ status: "stopped", published: 0 }); + expect(sent).toHaveLength(0); +}); + +it("retries the same event after a warming refusal and never skips it", async () => { + let count = 0; + const warming = () => + ++count === 2 + ? { + delivery: "failed" as const, + error: "invalid: import session warming", + } + : { delivery: "accepted" as const }; + const { service, sent, waits } = setup({ status: "active", decide: warming }); + const progress = vi.fn(); + const events = [ + message(1_735_732_800, "1"), + message(1_735_732_801, "2"), + message(1_735_732_802, "3"), + ]; + const report = await service.publish(proposal.id, events, { + onProgress: progress, + }); + expect(report.status).toBe("done"); + const ids = events.map((event) => + service.eventId({ ...event, pubkey: viewer }), + ); + expect(report.ids).toEqual(ids); + expect(sent.map((event) => event.id)).toEqual([ + ids[0], + ids[1], + ids[1], + ids[2], + ]); + expect(waits).toContain(5_000); + expect(progress).toHaveBeenCalledWith({ + phase: "starting", + published: 1, + total: 3, + }); + + count = 0; + const later = setup({ + status: "active", + acceptsAfter: now + 40, + decide: () => + ++count === 1 + ? { delivery: "failed", error: "invalid: import session warming" } + : { delivery: "accepted" }, + }); + const retried = await later.service.publish( + proposal.id, + [message(1_735_732_800, "1")], + {}, + ); + expect(retried.status).toBe("done"); + // Backs off to the snapshot's start time rather than the fixed delay. + expect(later.waits).toEqual([40_000, 40_000]); + expect(later.sent).toHaveLength(2); }); it("stops on the first rejection, surfaces the relay text verbatim and dismisses the refused event", async () => { diff --git a/src/features/conversation-import/service.ts b/src/features/conversation-import/service.ts index d09c55fc4c..952c219067 100644 --- a/src/features/conversation-import/service.ts +++ b/src/features/conversation-import/service.ts @@ -63,6 +63,10 @@ const PARENT_POLL_MS = 5_000; /** How long a missing parent may wait without any partner progress. */ const PARENT_STALL_MS = 10 * 60_000; const RATE_LIMIT_WAIT_MS = 15_000; +/** Retry delay for a warming refusal when the snapshot gives no later time. */ +const WARMING_RETRY_MS = 5_000; +/** The relay's refusal while a newly active session's replica catches up. */ +const WARMING = /\bimport session warming\b/; /** Above the outbox's own delivery timeout. */ const SETTLE_AFTER_STOP_MS = 30_000; const READ_PAGE = 200; @@ -101,6 +105,8 @@ type HostState = { loaded: boolean; entries: Map; orphans: Map; + /** Each snapshot's `accepts_after` on this device's clock. */ + starts: WeakMap; known: Map>; views: readonly ImportSessionView[]; listeners: Set<(sessions: readonly ImportSessionView[]) => void>; @@ -152,7 +158,11 @@ function verifiedView( }); } -function sessionView(entry: Entry, now: number): ImportSessionView { +function sessionView( + entry: Entry, + now: number, + acceptsAfter?: number, +): ImportSessionView { const { proposal, snapshot } = entry; const expired = !snapshot && proposal.content.expires_at <= now; return Object.freeze({ @@ -169,10 +179,17 @@ function sessionView(entry: Entry, now: number): ImportSessionView { published: snapshot?.published ?? Object.freeze({}), completed: snapshot?.completed ?? Object.freeze([]), expires_at: snapshot?.expires_at ?? proposal.content.expires_at, + ...(acceptsAfter !== undefined ? { acceptsAfter } : {}), confirmed: !!snapshot, }); } +const startOf = (state: HostState, entry: Entry) => + entry.snapshot && state.starts.get(entry.snapshot); + +const viewOf = (state: HostState, entry: Entry) => + sessionView(entry, state.now(), startOf(state, entry)); + /** Publishing needs the relay's own word that the session is active. */ function inactiveReason(entry: Entry, now: number, viewer: string) { if (!entry.snapshot) return NOT_CONFIRMED; @@ -358,6 +375,7 @@ export class ConversationImportHost loaded: false, entries: new Map(), orphans: new Map(), + starts: new WeakMap(), known: new Map(), views: Object.freeze([]), listeners: new Set(), @@ -687,7 +705,7 @@ export class ConversationImportHost throw new Error( "That source identity does not match your entry in the proposal.", ); - const status = sessionView(entry, state.now()).status; + const status = viewOf(state, entry).status; if (status !== "proposed" && status !== "active") throw new Error(`This import is ${status}.`); const pubkeys = content.participants.map((item) => item.pubkey); @@ -846,7 +864,7 @@ export class ConversationImportHost const known = state.entries.get(proposalId); const entry = known ?? (await entryFor(state, proposalId, signal)); if (known) await refreshSnapshot(state, entry, signal); - return sessionView(entry, state.now()); + return viewOf(state, entry); } subscribe(cb: (sessions: readonly ImportSessionView[]) => void) { @@ -951,8 +969,18 @@ export class ConversationImportHost const total = events.length; let lastSend = 0; let pending: string | undefined; + const starting = async (ms: number) => { + opts.onProgress?.({ phase: "starting", published: ids.length, total }); + await state.wait(ms, signal); + }; try { - for (const [index, event] of events.entries()) { + const inactive = total && inactiveReason(entry, state.now(), viewer); + if (inactive) return report("stopped", 0, inactive); + const ready = startOf(state, entry); + if (total && ready !== undefined && ready > state.now()) + await starting((ready - state.now()) * 1000); + for (let index = 0; index < total; ) { + const event = events[index] as PreparedImportEvent; signal?.throwIfAborted(); const stopped = inactiveReason(entry, state.now(), viewer); if (stopped) return report("stopped", index, stopped); @@ -985,11 +1013,20 @@ export class ConversationImportHost pending = id; const result = await sendImported(state, writer, event, signal); pending = undefined; + if (result !== id && result && WARMING.test(result)) { + // Nothing was stored, so the same event goes again once warm. + await refreshSnapshot(state, entry, signal).catch(() => {}); + const until = startOf(state, entry); + const ms = until === undefined ? 0 : (until - state.now()) * 1000; + await starting(ms > 0 ? ms : WARMING_RETRY_MS); + continue; + } if (result !== id) return report("rejected", index, result ?? "Delivery failed"); ids.push(id); rememberIds(state, channelId, [id]); opts.onProgress?.({ published: ids.length, total }); + index++; } } catch (error) { if (pending) { @@ -1619,6 +1656,15 @@ function ingest(state: HostState, events: readonly RelayEvent[]) { } else if (event.kind === IMPORT_SNAPSHOT_KIND) { const snapshot = parseSnapshot(event, session?.relayAuthor); if (!snapshot) continue; + // A snapshot stamped ahead of this device shows the relay's clock runs + // ahead by at least that much. A relay clock running behind cannot be + // seen here; its warming refusal covers that case. + if (snapshot.accepts_after !== undefined) + state.starts.set( + snapshot, + snapshot.accepts_after - + Math.max(0, snapshot.createdAt - state.now()), + ); const entry = state.entries.get(snapshot.proposalId); if (!entry) { const prior = state.orphans.get(snapshot.proposalId); @@ -1645,7 +1691,7 @@ function publishViews(state: HostState) { const now = state.now(); state.views = Object.freeze( [...state.entries.values()] - .map((entry) => sessionView(entry, now)) + .map((entry) => sessionView(entry, now, startOf(state, entry))) .sort( (a, b) => b.proposedAt - a.proposedAt || diff --git a/src/features/conversation-import/types.ts b/src/features/conversation-import/types.ts index 08c1b77eca..88cced32ec 100644 --- a/src/features/conversation-import/types.ts +++ b/src/features/conversation-import/types.ts @@ -69,6 +69,9 @@ export type ImportSessionView = Readonly<{ published: Readonly>; completed: readonly string[]; expires_at: number; + /** Unix seconds on this device's clock from which the relay accepts + * imported events. Absent when the relay has not set a warm-up time. */ + acceptsAfter?: number; /** False until a relay-signed snapshot for this proposal has been read. */ confirmed: boolean; }>; @@ -84,6 +87,9 @@ export type UnsignedImportEvent = PreparedImportEvent & Readonly<{ pubkey: string }>; export type PublishProgress = Readonly<{ + /** `starting`: waiting for the relay to finish warming up the session, + * until the session's `acceptsAfter` when it has one. */ + phase?: "starting"; published: number; total: number; /** Display name of the participant whose parent event is awaited. */ @@ -195,7 +201,10 @@ export interface ConversationImportService { * `expectedMembers` exactly. For direct message and private channel sources * it defaults to the proposal's participants; for direct messages it must * equal them, and for private channels it must be a subset of them. A - * change stops the run with status `stopped`. */ + * change stops the run with status `stopped`. + * Before the session's `acceptsAfter`, and whenever the relay answers that + * the session is still warming up, it waits (progress phase `starting`) + * and then publishes the same event. */ publish( proposalId: string, events: readonly PreparedImportEvent[],