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
+
+
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
- {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[],