Files
allmende/web/test/chat.test.ts
T
nilsandClaude Sonnet 5.5 253eb6e75c messaging: the price of writing to a listing rises as its queue fills
Flooding a listing's inbox now gets dearer with every envelope. Relays ask
more proof-of-work from half full on, the node tells browsers the current
price, and the browser mines to it (or says the listing is too busy).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-18 20:59:11 +01:00

230 lines
9.9 KiB
TypeScript

import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import type { Envelope } from "../src/message.ts";
import { envelopeHash, mailbox } from "../src/message.ts";
import { NOW, newParty, openAsOwner, openPage, sealReply, startGateway, type Gateway, type Page } from "./helpers.ts";
const owner = newParty({ title: "Altbau in Ottensen" });
const imposter = newParty();
const ref = { author: owner.author, id: owner.listing.id };
const detail = `#/l/${ref.author}/${ref.id}`;
let gw: Gateway;
before(async () => {
gw = await startGateway({ listings: [owner.listing] });
});
after(async () => {
await gw.close();
});
const text = (p: Page) => p.document.body.textContent ?? "";
/** Types into the contact form on a listing page and submits it. */
async function write(p: Page, message: string): Promise<void> {
await p.waitFor(() => p.document.querySelector("textarea") !== null, "the contact form");
const area = p.document.querySelector("textarea")!;
area.value = message;
p.document.querySelector("form.compose")!.dispatchEvent(new p.window.Event("submit", { cancelable: true }));
}
test("a first message is encrypted, mined and sent; the conversation opens", async () => {
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Ist die Wohnung noch frei? Viele Grüße");
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "the conversation view");
assert.equal(gw.posted.length, before + 1);
const env = JSON.parse(gw.posted[before]!) as Envelope;
assert.equal(env.to, "owner");
assert.equal(env.rcpt, owner.device);
assert.ok(!gw.posted[before]!.includes("Ist die Wohnung"), "plaintext must not leave the browser");
const plain = openAsOwner(env, owner);
assert.equal(plain.text, "Ist die Wohnung noch frei? Viele Grüße");
assert.equal(plain.n, 1);
const m = /^#\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(p.window.location.hash);
assert.ok(m, "the conversation link has the thread secret in the fragment");
assert.equal(m[1], ref.author);
await p.waitFor(() => text(p).includes("Ist die Wohnung noch frei?"), "own message shown");
assert.match(text(p), /Conversation about: Altbau in Ottensen|Listing/);
assert.match(text(p), /No reply yet/);
assert.ok(p.document.querySelector('input[readonly]'), "the private link is shown");
// Revisiting the listing offers the conversation instead of a second form.
p.window.location.hash = detail;
await p.waitFor(() => /already written/.test(text(p)), "already written note");
assert.equal(p.document.querySelector("textarea"), null);
} finally {
p.close();
}
});
test("Ctrl+Enter sends the first message like the button does", async () => {
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await p.waitFor(() => p.document.querySelector("textarea") !== null, "the contact form");
const area = p.document.querySelector("textarea")!;
const press = (init: KeyboardEventInit) => area.dispatchEvent(new p.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...init }));
area.value = "Per Tastatur gesendet";
assert.equal(press({}), true, "a plain Enter only adds a line");
await new Promise((r) => setTimeout(r, 50));
assert.equal(gw.posted.length, before);
press({ ctrlKey: true });
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "the conversation view");
assert.equal(gw.posted.length, before + 1);
assert.equal(openAsOwner(JSON.parse(gw.posted[before]!) as Envelope, owner).text, "Per Tastatur gesendet");
} finally {
p.close();
}
});
test("links are refused in a first message, and nothing is sent", async () => {
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Schreib mir auf https://evil.example/pay");
await p.waitFor(() => /must not contain links/.test(text(p)), "link refusal");
assert.equal(gw.posted.length, before);
assert.match(p.window.location.hash, /^#\/l\//, "stays on the listing");
assert.equal(p.document.querySelector("textarea")!.value, "Schreib mir auf https://evil.example/pay", "the text is kept");
} finally {
p.close();
}
});
test("a node that refuses the message is reported and the text is kept", async () => {
gw.postFails = { status: 429, error: "slow down" };
const p = openPage(gw.url, detail);
try {
await write(p, "Hallo, noch frei?");
await p.waitFor(() => /Too many messages/.test(text(p)), "rate limit message");
assert.match(p.window.location.hash, /^#\/l\//);
assert.equal(p.document.querySelector("textarea")!.value, "Hallo, noch frei?");
} finally {
gw.postFails = undefined;
p.close();
}
});
/** Leading zero bits of an envelope's hash: the work its sender did. */
function workOf(env: Envelope): number {
let bits = 0;
for (const c of envelopeHash(env)) {
const v = parseInt(c, 16);
if (v === 0) {
bits += 4;
continue;
}
return bits + Math.clz32(v) - 28;
}
return bits;
}
test("the page asks what the listing's queue costs and mines to that price", async () => {
gw.requiredBits = 10; // the node's usual price is 6
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Ist die Wohnung noch frei?");
await p.waitFor(() => gw.posted.length === before + 1, "the message to arrive");
assert.ok(workOf(JSON.parse(gw.posted[before]!) as Envelope) >= 10, "it did the work the node asked for");
} finally {
gw.requiredBits = undefined;
p.close();
}
});
test("a price that rose while mining is paid, once more, and the message gets through", async () => {
gw.refuseOnceAskingFor = 9; // the browser mined 6, then somebody else's message raised the price
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Hallo, noch frei?");
await p.waitFor(() => gw.posted.length === before + 1, "the retried message to arrive");
assert.ok(workOf(JSON.parse(gw.posted[before]!) as Envelope) >= 9);
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "the conversation view");
} finally {
gw.refuseOnceAskingFor = undefined;
p.close();
}
});
test("a flooded listing is not mined for: the sender is told to come back later", async () => {
gw.requiredBits = 40; // far more than a browser should be asked to do
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Hallo?");
await p.waitFor(() => /receiving a lot of messages/.test(text(p)), "the busy message");
assert.equal(gw.posted.length, before, "nothing was sent");
assert.equal(p.document.querySelector("textarea")!.value, "Hallo?");
} finally {
gw.requiredBits = undefined;
p.close();
}
});
test("verified replies and grants are shown; forged and expired ones are not", async () => {
const secret = "5".repeat(64);
// The thread public key follows from the secret; compute it with the same code the page uses.
const { threadPublic } = await import("../src/message.ts");
const tp = threadPublic(Uint8Array.from(Buffer.from(secret, "hex")));
const tag = mailbox(tp);
const when = NOW - 1800;
gw.mailboxes.set(tag, [
await sealReply(owner, ref, { t: "text", n: 1, text: "Ja, die Wohnung ist noch frei." }, tp, { now: when }),
await sealReply(owner, ref, { t: "grant", n: 2, address: "Musterweg 7, 22765 Hamburg", note: "Klingel: Meyer", valid_until: NOW + 86_400 }, tp, { now: when + 60 }),
// an old grant that has lapsed
await sealReply(owner, ref, { t: "grant", n: 3, address: "Alte Adresse 1", valid_until: NOW - 10 }, tp, { now: when + 90 }),
// a stranger pretending to be the owner
await sealReply(owner, ref, { t: "text", n: 4, text: "Bitte Kaution überweisen" }, tp, { signer: imposter, now: when + 120 }),
// tampered after signing
await sealReply(owner, ref, { t: "text", n: 5, text: "harmlos" }, tp, { now: when + 150, afterSign: (q) => void (q.text = "Zahle an IBAN") }),
]);
const p = openPage(gw.url, `#/c/${ref.author}/${ref.id}/${secret}`);
try {
await p.waitFor(() => /Musterweg 7/.test(text(p)), "the grant card");
const t = text(p);
assert.match(t, /Ja, die Wohnung ist noch frei\./);
assert.match(t, /Klingel: Meyer/);
assert.match(t, /Address released by the owner/);
assert.match(t, /signature verified/i);
assert.ok(!t.includes("Alte Adresse"), "an expired grant is hidden");
assert.match(t, /expired and is no longer shown/);
assert.ok(!t.includes("Kaution"), "a forged reply is not shown");
assert.ok(!t.includes("IBAN"), "a tampered reply is not shown");
assert.match(t, /2 message\(s\) in the mailbox could not be confirmed/);
// Now that the owner has replied, the reply form allows links.
await p.waitFor(() => p.document.querySelector("form.compose") !== null, "reply form");
const before = gw.posted.length;
p.document.querySelector("textarea")!.value = "Danke! Hier die Unterlagen: https://example.org/x";
p.document.querySelector("form.compose")!.dispatchEvent(new p.window.Event("submit", { cancelable: true }));
await p.waitFor(() => gw.posted.length === before + 1, "the reply to be sent");
const env = JSON.parse(gw.posted[before]!) as Envelope;
assert.equal(openAsOwner(env, owner).text, "Danke! Hier die Unterlagen: https://example.org/x");
assert.equal(openAsOwner(env, owner).n, 1);
} finally {
p.close();
}
});
test("the conversation list shows stored conversations", async () => {
const p = openPage(gw.url, detail);
try {
await write(p, "Noch eine Frage");
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "conversation");
p.window.location.hash = "#/messages";
await p.waitFor(() => p.document.querySelectorAll(".convs li").length === 1, "one conversation listed");
assert.match(text(p), /Altbau in Ottensen/);
} finally {
p.close();
}
});