commit c18902ab68335fa0607a9acd8c06b106ed032219
parent 96493bcc2fd8024e14e54b6e306ba00022fbd6e7
Author: triesap <tyson@radroots.org>
Date: Wed, 7 Oct 2026 15:26:07 +0000
messages: define immutable two-party rumor identity (HCP-073)
- Compute bounded canonical unsigned rumor IDs with the qualified SDK.
- Bind local enquiry and reply participants to genuine current identity and parent plans.
- Share one immutable rumor between peer and self archive destinations.
- Reject body conversions and release memory plans on identity invalidation.
Diffstat:
4 files changed, 616 insertions(+), 0 deletions(-)
diff --git a/web/src/lib/messaging/rumor-plan.ts b/web/src/lib/messaging/rumor-plan.ts
@@ -0,0 +1,133 @@
+import { buildCanonicalPairRumor } from '../nostr/rumor-template.ts';
+import { messageFromWireParts } from '../contracts/message-v1/index.ts';
+import {
+ identityMessagingOwnership,
+ subscribeIdentityInvalidation,
+ type IdentitySession
+} from '../runtime/identity-session.ts';
+import { buildEnquiryMessage, type EnquiryContext } from './enquiry-context.ts';
+declare const rumorBrand: unique symbol;
+export type RumorPlan = Readonly<{ readonly [rumorBrand]: true }>;
+export type RumorPlanSnapshot = Readonly<{
+ owner: string;
+ peer: string;
+ id: string;
+ createdAt: number;
+ wire: string;
+}>;
+type Controller = RumorPlanSnapshot & {
+ current(): boolean;
+ unsubscribe(): void;
+};
+const plans = new WeakMap<RumorPlan, Controller>();
+// Local memory-only planning capability, not cryptographically admitted inbound
+// history, inbox readiness, CAS reservation, mounted view or encryption/Send.
+// Incoming replies later require085/092 authenticated seal/rumor/room admission.
+function capture(
+ session: IdentitySession,
+ rawMessage: string,
+ observedTime: unknown
+): RumorPlan | undefined {
+ const ownership = identityMessagingOwnership(session);
+ if (!ownership || !ownership.current()) return undefined;
+ const rumor = buildCanonicalPairRumor(
+ rawMessage,
+ ownership.owner,
+ observedTime
+ );
+ if (!rumor || !ownership.current()) return undefined;
+ const peer = rumor.tags.find((row) => row[0] === 'p')?.[1];
+ if (!peer) return undefined;
+ const token = Object.freeze({}) as RumorPlan;
+ const unsubscribe = subscribeIdentityInvalidation(session, () => {
+ if (!ownership.current()) stopRumorPlan(token);
+ });
+ plans.set(token, {
+ owner: ownership.owner,
+ peer,
+ id: rumor.id,
+ createdAt: rumor.created_at,
+ wire: JSON.stringify(rumor),
+ current: ownership.current,
+ unsubscribe
+ });
+ return token;
+}
+export function captureEnquiryRumor(
+ session: IdentitySession,
+ context: EnquiryContext,
+ text: unknown,
+ observedTime: unknown
+): RumorPlan | undefined {
+ const parts = buildEnquiryMessage(context, text);
+ const message = parts && messageFromWireParts(JSON.stringify(parts));
+ return message
+ ? capture(session, JSON.stringify(message), observedTime)
+ : undefined;
+}
+export function captureReplyRumor(
+ session: IdentitySession,
+ parent: RumorPlan,
+ text: unknown,
+ observedTime: unknown
+): RumorPlan | undefined {
+ if (typeof text !== 'string') return undefined;
+ const original = rumorPlanSnapshot(parent),
+ ownership = identityMessagingOwnership(session);
+ if (
+ !original ||
+ !ownership ||
+ !ownership.current() ||
+ (ownership.owner !== original.owner && ownership.owner !== original.peer)
+ )
+ return undefined;
+ const peer =
+ ownership.owner === original.owner ? original.peer : original.owner;
+ // The parent hash comes only from a genuine captured local rumor, never a
+ // caller-provided product ID/body/URL/detached snapshot or outer signer.
+ return capture(
+ session,
+ JSON.stringify({
+ recipients: [{ public_key: peer, relay_url: null }],
+ content: text,
+ reply_to: { id: original.id, relays: null },
+ subject: null
+ }),
+ observedTime
+ );
+}
+export function rumorPlanSnapshot(
+ plan: RumorPlan
+): RumorPlanSnapshot | undefined {
+ const value = plans.get(plan);
+ if (!value) return undefined;
+ if (!value.current()) {
+ stopRumorPlan(plan);
+ return undefined;
+ }
+ return {
+ owner: value.owner,
+ peer: value.peer,
+ id: value.id,
+ createdAt: value.createdAt,
+ wire: value.wire
+ };
+}
+export function rumorEnvelopePlan(plan: RumorPlan) {
+ const value = rumorPlanSnapshot(plan);
+ return value
+ ? [
+ { role: 'peer' as const, recipient: value.peer, rumorWire: value.wire },
+ {
+ role: 'self_archive' as const,
+ recipient: value.owner,
+ rumorWire: value.wire
+ }
+ ]
+ : undefined;
+}
+export function stopRumorPlan(plan: RumorPlan): void {
+ const value = plans.get(plan);
+ plans.delete(plan);
+ value?.unsubscribe();
+}
diff --git a/web/src/lib/nostr/rumor-template.ts b/web/src/lib/nostr/rumor-template.ts
@@ -0,0 +1,33 @@
+import { getEventHash, type UnsignedEvent } from 'applesauce-core/helpers';
+import { canonicalPublicKey } from '../contracts/public-key.ts';
+import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';
+import { messageToWireParts } from '../contracts/message-v1/index.ts';
+import { safeUnsignedInteger } from './envelope-bounds.ts';
+export type CanonicalPairRumor = Readonly<UnsignedEvent & { id: string }>;
+// Fresh detached data only, never authenticated inbound/room, signer, store or
+// Send authority. The caller supplies the observed time;074 owns clock/CAS.
+export function buildCanonicalPairRumor(
+ rawMessage: unknown,
+ author: unknown,
+ observedTime: unknown
+): CanonicalPairRumor | undefined {
+ const owner = canonicalPublicKey(author),
+ createdAt = safeUnsignedInteger(observedTime),
+ parts = messageToWireParts(rawMessage);
+ if (!owner || createdAt === undefined || !parts) return undefined;
+ const recipients = parts.tags.filter((row) => row[0] === 'p');
+ if (recipients.length !== 1 || recipients[0]?.[1] === owner) return undefined;
+ const template: UnsignedEvent = {
+ pubkey: owner,
+ created_at: createdAt,
+ kind: 14,
+ tags: parts.tags.map((row) => [...row]),
+ content: parts.content
+ };
+ try {
+ const rumor = { id: getEventHash(template), ...template };
+ return boundedUtf8(JSON.stringify(rumor), 8192) ? rumor : undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/web/tests/conformance/rumor-identity.test.ts b/web/tests/conformance/rumor-identity.test.ts
@@ -0,0 +1,171 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import test from 'node:test';
+import { getEventHash } from 'applesauce-core/helpers';
+import { buildCanonicalPairRumor } from '../../src/lib/nostr/rumor-template.ts';
+import { messageToWireParts } from '../../src/lib/contracts/message-v1/index.ts';
+import { messageCorpus } from './message-cases.ts';
+const author =
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
+ peer = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5',
+ time = 1700000100;
+const message = (content = 'A plain enquiry') => ({
+ recipients: [{ public_key: peer, relay_url: null }],
+ content,
+ reply_to: null,
+ subject: null
+});
+void test('fresh unsigned rumor uses the qualified hash and canonical NIP01 serialization', () => {
+ const value = buildCanonicalPairRumor(
+ JSON.stringify(message()),
+ author,
+ time
+ )!;
+ assert.equal(value.id, getEventHash(value));
+ assert.equal(
+ value.id,
+ createHash('sha256')
+ .update(
+ JSON.stringify([0, author, time, 14, [['p', peer]], 'A plain enquiry'])
+ )
+ .digest('hex')
+ );
+ assert.equal(value.pubkey, author);
+ assert.equal(value.created_at, time);
+ assert.equal(value.kind, 14);
+ assert.equal('sig' in value, false);
+ assert.deepEqual(Object.keys(value).sort(), [
+ 'content',
+ 'created_at',
+ 'id',
+ 'kind',
+ 'pubkey',
+ 'tags'
+ ]);
+});
+void test('body Unicode and generic Message reply/subject semantics survive canonical hashing', () => {
+ const input = {
+ ...message('Carrots 🥕\nnostr:untrusted-text'),
+ reply_to: { id: 'f'.repeat(64), relays: null },
+ subject: 'Food question'
+ };
+ const value = buildCanonicalPairRumor(JSON.stringify(input), author, time)!;
+ assert.equal(value.content, input.content);
+ assert.deepEqual(value.tags, [
+ ['p', peer],
+ ['e', input.reply_to.id],
+ ['subject', input.subject]
+ ]);
+ assert.equal(value.id, getEventHash(value));
+});
+void test('same captured fields have the same ID and changed observed timestamp/body changes it', () => {
+ const raw = JSON.stringify(message()),
+ first = buildCanonicalPairRumor(raw, author, time)!;
+ assert.equal(buildCanonicalPairRumor(raw, author, time)!.id, first.id);
+ assert.notEqual(buildCanonicalPairRumor(raw, author, time + 1)!.id, first.id);
+ assert.notEqual(
+ buildCanonicalPairRumor(
+ JSON.stringify(message('A different intention')),
+ author,
+ time
+ )!.id,
+ first.id
+ );
+ // Intentional same-second duplicate admission/clock progression belongs to074.
+});
+void test('groups, duplicate recipients and self messages are unsupported', () => {
+ for (const recipients of [
+ [],
+ [{ public_key: author }],
+ [{ public_key: peer }, { public_key: author }],
+ [{ public_key: peer }, { public_key: peer }]
+ ])
+ assert.equal(
+ buildCanonicalPairRumor(
+ JSON.stringify({ ...message(), recipients }),
+ author,
+ time
+ ),
+ undefined
+ );
+});
+void test('keys and observed numeric timestamps cannot be coerced or rounded', () => {
+ for (const owner of [
+ author.toUpperCase(),
+ '0'.repeat(64),
+ '',
+ null,
+ { toString: () => author }
+ ])
+ assert.equal(
+ buildCanonicalPairRumor(JSON.stringify(message()), owner, time),
+ undefined
+ );
+ for (const timestamp of [
+ -1,
+ -0,
+ 1.5,
+ Infinity,
+ NaN,
+ Number.MAX_SAFE_INTEGER + 1,
+ String(time),
+ null
+ ])
+ assert.equal(
+ buildCanonicalPairRumor(JSON.stringify(message()), author, timestamp),
+ undefined
+ );
+ assert.equal(
+ buildCanonicalPairRumor(JSON.stringify(message()), author, 0)!.created_at,
+ 0
+ );
+});
+void test('body and complete rumor JSON limits are separately enforced without truncation', () => {
+ assert.equal(
+ buildCanonicalPairRumor(
+ JSON.stringify(message('a'.repeat(4096))),
+ author,
+ time
+ )!.content.length,
+ 4096
+ );
+ assert.equal(
+ buildCanonicalPairRumor(
+ JSON.stringify(message('é'.repeat(2048))),
+ author,
+ time
+ )!.content.length,
+ 2048
+ );
+ for (const content of ['a'.repeat(4097), 'é'.repeat(2049), '\ud800', ' \n\t'])
+ assert.equal(
+ buildCanonicalPairRumor(JSON.stringify(message(content)), author, time),
+ undefined
+ );
+ const escaped = JSON.stringify(message('"'.repeat(4000)));
+ assert.ok(messageToWireParts(escaped), 'detached parts still fit');
+ assert.equal(
+ buildCanonicalPairRumor(escaped, author, time),
+ undefined,
+ 'full rumor overhead exceeds8KiB'
+ );
+});
+for (const vector of messageCorpus().vectors.filter((v) => v.mode === 'write'))
+ void test(
+ 'pinned Message writer projection into pair rumor: ' + vector.id,
+ () => {
+ const raw = JSON.stringify(vector.input),
+ parts = messageToWireParts(raw);
+ const recipients = parts?.tags.filter((row) => row[0] === 'p');
+ const value = buildCanonicalPairRumor(raw, author, time);
+ if (!parts || recipients?.length !== 1 || recipients[0]?.[1] === author)
+ assert.equal(value, undefined);
+ else {
+ assert.ok(value);
+ assert.deepEqual(value.tags, parts.tags);
+ assert.equal(value.content, parts.content);
+ assert.equal(value.id, getEventHash(value));
+ assert.equal(value.pubkey, author);
+ }
+ }
+ );
diff --git a/web/tests/unit/rumor-plan.test.ts b/web/tests/unit/rumor-plan.test.ts
@@ -0,0 +1,279 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { finalizeEvent, getEventHash } from 'applesauce-core/helpers';
+import { verifyEnvelope } from '../../src/lib/nostr/verified-envelope.ts';
+import {
+ captureEnquiryContext,
+ enquiryContextSnapshot,
+ type EnquiryContext
+} from '../../src/lib/messaging/enquiry-context.ts';
+import {
+ createIdentitySession,
+ connectIdentity,
+ probeIdentityMessaging,
+ disconnectIdentity,
+ type IdentitySession
+} from '../../src/lib/runtime/identity-session.ts';
+import {
+ captureEnquiryRumor,
+ captureReplyRumor,
+ rumorPlanSnapshot,
+ rumorEnvelopePlan,
+ stopRumorPlan,
+ type RumorPlan
+} from '../../src/lib/messaging/rumor-plan.ts';
+const buyer =
+ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
+ outsider = 'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5';
+const sessions: IdentitySession[] = [];
+afterEach(() => {
+ for (const session of sessions) disconnectIdentity(session);
+ sessions.length = 0;
+ vi.unstubAllGlobals();
+});
+function food() {
+ const key = crypto.getRandomValues(new Uint8Array(32));
+ try {
+ const event = finalizeEvent(
+ {
+ kind: 30402,
+ created_at: 1700000060,
+ content: 'Public carrots',
+ tags: [
+ ['d', 'carrots'],
+ ['title', 'Carrots'],
+ ['summary', 'Fresh carrots'],
+ ['published_at', '1700000000'],
+ ['location', 'Victoria'],
+ ['price', '3.5', 'CAD'],
+ ['radroots:price_unit', 'lb'],
+ ['status', 'active']
+ ]
+ },
+ key
+ );
+ const proof = verifyEnvelope(JSON.stringify(event));
+ if (!proof.ok) throw Error('invalid public test fixture');
+ const context = captureEnquiryContext(proof.value);
+ if (!context) throw Error('invalid Food context');
+ return { event, context };
+ } finally {
+ key.fill(0);
+ }
+}
+async function identity(owner = buyer) {
+ let encrypts = 0,
+ decrypts = 0,
+ signs = 0;
+ vi.stubGlobal('window', {
+ nostr: {
+ getPublicKey: () => Promise.resolve(owner),
+ signEvent: () => {
+ signs++;
+ return Promise.reject(Error('unexpected sign'));
+ },
+ nip44: {
+ encrypt: (_peer: string, text: string) => {
+ encrypts++;
+ return Promise.resolve('fixture:' + text);
+ },
+ decrypt: (_peer: string, text: string) => {
+ decrypts++;
+ return Promise.resolve(text.slice(8));
+ }
+ }
+ }
+ });
+ const session = createIdentitySession();
+ sessions.push(session);
+ await connectIdentity(session);
+ await probeIdentityMessaging(session, 'reviewed_self_copy');
+ return { session, counts: () => ({ encrypts, decrypts, signs }) };
+}
+function required(value: RumorPlan | undefined) {
+ if (!value) throw Error('expected local rumor plan');
+ return value;
+}
+it('binds current observed owner and genuine Food seller without signing/encrypting or persisting', async () => {
+ const f = food(),
+ owner = await identity(),
+ before = owner.counts();
+ const plan = required(
+ captureEnquiryRumor(owner.session, f.context, 'Tomorrow?', 1700000100)
+ );
+ const snapshot = rumorPlanSnapshot(plan)!,
+ wire = JSON.parse(snapshot.wire) as {
+ pubkey: string;
+ tags: string[][];
+ id: string;
+ kind: number;
+ created_at: number;
+ content: string;
+ };
+ expect(snapshot.owner).toBe(buyer);
+ expect(snapshot.peer).toBe(f.event.pubkey);
+ expect(wire.pubkey).toBe(buyer);
+ expect(wire.tags).toEqual([['p', f.event.pubkey]]);
+ expect(wire.id).toBe(getEventHash(wire));
+ expect(wire).not.toHaveProperty('sig');
+ expect(wire.created_at).toBe(1700000100);
+ expect(owner.counts()).toEqual(before);
+});
+it('exactly peer and self destinations share one immutable rumor including its original p', async () => {
+ const f = food(),
+ owner = await identity(),
+ plan = required(captureEnquiryRumor(owner.session, f.context, '', 100));
+ const copies = rumorEnvelopePlan(plan)!;
+ expect(copies.map((row) => [row.role, row.recipient])).toEqual([
+ ['peer', f.event.pubkey],
+ ['self_archive', buyer]
+ ]);
+ expect(copies[0].rumorWire).toBe(copies[1].rumorWire);
+ for (const row of copies)
+ expect((JSON.parse(row.rumorWire) as { tags: string[][] }).tags).toEqual([
+ ['p', f.event.pubkey]
+ ]);
+ const detached = copies as { recipient: string; rumorWire: string }[];
+ detached[0].recipient = outsider;
+ detached[0].rumorWire = '{}';
+ expect(rumorEnvelopePlan(plan)![0].recipient).toBe(f.event.pubkey);
+ expect(rumorEnvelopePlan(plan)![0].rumorWire).toBe(copies[1].rumorWire);
+});
+it('body and detached display/context cannot redirect actual recipient', async () => {
+ const f = food(),
+ owner = await identity(),
+ copy = enquiryContextSnapshot(f.context)! as { peer: string };
+ copy.peer = outsider;
+ const plan = required(
+ captureEnquiryRumor(owner.session, f.context, 'Send to ' + outsider, 100)
+ );
+ expect(rumorPlanSnapshot(plan)!.peer).toBe(f.event.pubkey);
+ expect(
+ captureEnquiryRumor(
+ owner.session,
+ copy as unknown as EnquiryContext,
+ '',
+ 100
+ )
+ ).toBeUndefined();
+});
+it('rejects own listing, guest/forged identity, forged context and invalid time', async () => {
+ const f = food(),
+ seller = await identity(f.event.pubkey);
+ expect(
+ captureEnquiryRumor(seller.session, f.context, '', 100)
+ ).toBeUndefined();
+ const guest = createIdentitySession();
+ sessions.push(guest);
+ expect(captureEnquiryRumor(guest, f.context, '', 100)).toBeUndefined();
+ expect(
+ captureEnquiryRumor({} as IdentitySession, f.context, '', 100)
+ ).toBeUndefined();
+ const owner = await identity();
+ expect(
+ captureEnquiryRumor(owner.session, {} as EnquiryContext, '', 100)
+ ).toBeUndefined();
+ expect(captureEnquiryRumor(owner.session, f.context, '', -0)).toBeUndefined();
+});
+it('reply derives opposite participant and direct rumor parent, never the public listing event', async () => {
+ const f = food(),
+ owner = await identity(),
+ parent = required(captureEnquiryRumor(owner.session, f.context, '', 100));
+ const parentId = rumorPlanSnapshot(parent)!.id,
+ seller = await identity(f.event.pubkey);
+ const reply = required(
+ captureReplyRumor(seller.session, parent, 'Yes, tomorrow works.', 101)
+ ),
+ snapshot = rumorPlanSnapshot(reply)!;
+ const wire = JSON.parse(snapshot.wire) as {
+ pubkey: string;
+ tags: string[][];
+ };
+ expect(snapshot.owner).toBe(f.event.pubkey);
+ expect(snapshot.peer).toBe(buyer);
+ expect(wire.pubkey).toBe(f.event.pubkey);
+ expect(wire.tags).toEqual([
+ ['p', buyer],
+ ['e', parentId]
+ ]);
+ expect(parentId).not.toBe(f.event.id);
+ expect(rumorEnvelopePlan(reply)!.map((row) => row.recipient)).toEqual([
+ buyer,
+ f.event.pubkey
+ ]);
+});
+it('same-owner followup keeps the opposite peer and rejects nonmember or injected parent IDs', async () => {
+ const f = food(),
+ owner = await identity(),
+ parent = required(captureEnquiryRumor(owner.session, f.context, '', 100));
+ const followup = required(
+ captureReplyRumor(owner.session, parent, 'Another question', 101)
+ );
+ expect(rumorPlanSnapshot(followup)!.peer).toBe(f.event.pubkey);
+ expect(
+ captureReplyRumor(
+ owner.session,
+ f.event.id as unknown as RumorPlan,
+ 'Injected parent',
+ 101
+ )
+ ).toBeUndefined();
+ expect(
+ captureReplyRumor(
+ owner.session,
+ rumorPlanSnapshot(parent) as unknown as RumorPlan,
+ 'Detached parent',
+ 101
+ )
+ ).toBeUndefined();
+ const other = await identity(outsider);
+ expect(
+ captureReplyRumor(other.session, parent, 'Not a room member', 101)
+ ).toBeUndefined();
+});
+it('detached plan data and forged token cannot change or acquire plaintext ownership', async () => {
+ const f = food(),
+ owner = await identity(),
+ plan = required(captureEnquiryRumor(owner.session, f.context, '', 100));
+ const before = rumorPlanSnapshot(plan)!;
+ const copy = rumorPlanSnapshot(plan)! as {
+ owner: string;
+ peer: string;
+ wire: string;
+ };
+ copy.owner = outsider;
+ copy.peer = buyer;
+ copy.wire = '{}';
+ expect(rumorPlanSnapshot(plan)).toEqual(before);
+ expect(rumorPlanSnapshot({} as RumorPlan)).toBeUndefined();
+ expect(rumorEnvelopePlan(copy as unknown as RumorPlan)).toBeUndefined();
+});
+it('explicit release and identity invalidation erase reachable plan plaintext and reject further replies', async () => {
+ const f = food(),
+ owner = await identity(),
+ first = required(captureEnquiryRumor(owner.session, f.context, '', 100)),
+ second = required(
+ captureEnquiryRumor(owner.session, f.context, 'Other', 101)
+ );
+ stopRumorPlan(first);
+ stopRumorPlan(first);
+ expect(rumorPlanSnapshot(first)).toBeUndefined();
+ expect(rumorEnvelopePlan(first)).toBeUndefined();
+ disconnectIdentity(owner.session);
+ expect(rumorPlanSnapshot(second)).toBeUndefined();
+ expect(rumorEnvelopePlan(second)).toBeUndefined();
+ expect(
+ captureReplyRumor(owner.session, second, 'After disconnect', 102)
+ ).toBeUndefined();
+});
+it('reply body objects cannot execute conversion or become trusted plain text', async () => {
+ const f = food(),
+ owner = await identity();
+ const parent = required(
+ captureEnquiryRumor(owner.session, f.context, '', 100)
+ );
+ const toJSON = vi.fn(() => 'Object-supplied private body');
+ expect(
+ captureReplyRumor(owner.session, parent, { toJSON }, 101)
+ ).toBeUndefined();
+ expect(toJSON).not.toHaveBeenCalled();
+});