Implement end-to-end encrypted buyer/seller messaging

Wire format (internal/message): sealed boxes to the listing's device key
(X25519 + HKDF + ChaCha20-Poly1305), padded, proof-of-work stamped, with
signed owner replies and address grants. Relay validation, bounded queues,
gossip on per-region message topics and sync (store, p2p).

Owner side (internal/inbox, API): inbox with hidden link messages and a
per-day new-thread limit, replies, grants, and a private per-listing
address. Public POST/GET /api/v1/messages for buyers.

Browser: noble-based sealing and reply verification checked against a Go
fixture, contact form, conversation view, message list, de/en strings.

Docs: PROTOCOL.md messaging section matches the implementation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 19:44:59 +01:00
co-authored by Claude Sonnet 5.5
parent b9e1b0c058
commit 3b0351c774
45 changed files with 8228 additions and 292 deletions
+151
View File
@@ -0,0 +1,151 @@
import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import type { Envelope } from "../src/message.ts";
import { 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("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();
}
});
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();
}
});
+142 -7
View File
@@ -1,11 +1,14 @@
import { createServer, type Server } from "node:http";
import { readFileSync } from "node:fs";
import type { AddressInfo } from "node:net";
import { ed25519 } from "@noble/curves/ed25519.js";
import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
import { hkdf } from "@noble/hashes/hkdf.js";
import { sha256 } from "@noble/hashes/sha2.js";
import { JSDOM, type DOMWindow } from "jsdom";
import { canonicalize } from "../src/jcs.ts";
import { mailbox, sealEnvelope, type Envelope, type Plain, type Ref } from "../src/message.ts";
import { leadingZeroBits, type Listing } from "../src/verify.ts";
/** The clock the browser sees in these tests (unix seconds). */
@@ -15,8 +18,23 @@ export const DIFFICULTY = 8;
const enc = new TextEncoder();
const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");
/** An owner: identity and device keys, and the certificate between them. */
export interface Party {
idKey: Uint8Array;
devKey: Uint8Array;
cert: Record<string, unknown>;
author: string;
device: string;
listing: Listing;
}
/** Creates a validly signed listing under a brand-new identity and device. */
export function signListing(fields: Record<string, unknown> = {}): Listing {
return newParty(fields).listing;
}
/** Like signListing, but keeps the keys so a test can act as the owner. */
export function newParty(fields: Record<string, unknown> = {}, certFields: Record<string, unknown> = {}): Party {
const idKey = ed25519.utils.randomSecretKey();
const devKey = ed25519.utils.randomSecretKey();
const cert: Record<string, unknown> = {
@@ -25,6 +43,7 @@ export function signListing(fields: Record<string, unknown> = {}): Listing {
device: hex(ed25519.getPublicKey(devKey)),
issued_at: NOW - 3600,
expires_at: NOW + 90 * 86_400,
...certFields,
};
cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey));
@@ -52,7 +71,97 @@ export function signListing(fields: Record<string, unknown> = {}): Listing {
if (leadingZeroBits(sha256(enc.encode(canonicalize(l)))) >= DIFFICULTY) break;
}
l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey));
return l as unknown as Listing;
return {
idKey,
devKey,
cert,
author: cert.author as string,
device: cert.device as string,
listing: l as unknown as Listing,
};
}
// --- playing the owner -------------------------------------------------------
/** What an owner's node does with a buyer's envelope: decrypt it with the device key. */
export function openAsOwner(env: Envelope, p: Party): Plain {
const sk = ed25519.utils.toMontgomerySecret(p.devKey);
const epk = fromHex(env.epk);
const rpk = x25519.getPublicKey(sk);
const key = hkdf(sha256, x25519.getSharedSecret(sk, epk), concatBytes(epk, rpk), enc.encode("allmende-seal-v1"), 32);
const aad = enc.encode(
canonicalize({
v: env.v,
listing: env.listing,
to: env.to,
rcpt: env.rcpt,
epk: env.epk,
created_at: env.created_at,
expires_at: env.expires_at,
}),
);
const padded = chacha20poly1305(key, new Uint8Array(12), aad).decrypt(fromHex(env.ct));
let end = padded.length;
while (end > 0 && padded[end - 1] === 0) end--;
if (padded[end - 1] !== 0x80) throw new Error("bad padding");
return JSON.parse(new TextDecoder().decode(padded.slice(0, end - 1))) as Plain;
}
export interface ReplyOptions {
/** Edit the plaintext before it is signed (e.g. to build an invalid message). */
beforeSign?: (plain: Record<string, unknown>) => void;
/** Edit the plaintext after signing (e.g. to break the signature). */
afterSign?: (plain: Record<string, unknown>) => void;
/** Sign with another party's device key (a forgery). */
signer?: Party;
now?: number;
difficulty?: number;
}
/**
* Builds a reply the way an owner's node does (internal/message SealToBuyer):
* signs the plaintext with the device key and seals it to the thread key.
*/
export async function sealReply(
owner: Party,
ref: Ref,
fields: Record<string, unknown>,
threadPub: string,
opts: ReplyOptions = {},
): Promise<Envelope> {
const now = opts.now ?? NOW;
const signer = opts.signer ?? owner;
const plain: Record<string, unknown> = {
thread: threadPub,
sent_at: now,
listing: ref,
device: signer.device,
cert: signer.cert,
...fields,
};
opts.beforeSign?.(plain);
plain.sig = hex(ed25519.sign(enc.encode("allmende-reply-v1\n" + canonicalize(plain)), signer.devKey));
opts.afterSign?.(plain);
return sealEnvelope({
listing: ref,
to: "buyer",
rcpt: mailbox(threadPub),
rpk: fromHex(threadPub),
body: enc.encode(canonicalize(plain)),
now,
difficulty: opts.difficulty ?? 6,
});
}
function fromHex(s: string): Uint8Array {
return Uint8Array.from(Buffer.from(s, "hex"));
}
function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
const out = new Uint8Array(a.length + b.length);
out.set(a);
out.set(b, a.length);
return out;
}
// --- a stand-in for a node's HTTP API -------------------------------------
@@ -61,6 +170,12 @@ export interface Gateway {
url: string;
/** Query strings of every /api/v1/listings search received. */
queries: string[];
/** Bodies of every POST /api/v1/messages, as received. */
posted: string[];
/** Envelopes served from GET /api/v1/messages?mailbox=<tag>, by tag. Tests fill it. */
mailboxes: Map<string, unknown[]>;
/** Make POST /api/v1/messages answer with this status and error. */
postFails?: { status: number; error: string };
close(): Promise<void>;
}
@@ -73,12 +188,34 @@ export interface GatewayOptions {
export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
const queries: string[] = [];
const posted: string[] = [];
const mailboxes = new Map<string, unknown[]>();
const gateway: Gateway = {
url: "",
queries,
posted,
mailboxes,
close: () => new Promise((ok) => server.close(() => ok())),
};
const server: Server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://x");
const json = (code: number, body: unknown) => {
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (url.pathname === "/api/v1/messages") {
if (req.method === "POST") {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
if (gateway.postFails) return json(gateway.postFails.status, { error: gateway.postFails.error });
posted.push(body);
json(202, { hash: "x" });
});
return;
}
return json(200, mailboxes.get(url.searchParams.get("mailbox") ?? "") ?? []);
}
if (url.pathname === "/api/v1/status") {
if (opts.statusFails) return json(500, { error: "down" });
return json(200, {
@@ -89,6 +226,7 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
peers: 2,
listings: opts.listings.length,
difficulty: DIFFICULTY,
message_difficulty: 6,
});
}
if (url.pathname === "/api/v1/listings") {
@@ -105,11 +243,8 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
});
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
const { port } = server.address() as AddressInfo;
return {
url: `http://127.0.0.1:${port}`,
queries,
close: () => new Promise((ok) => server.close(() => ok())),
};
gateway.url = `http://127.0.0.1:${port}`;
return gateway;
}
// --- running the real built UI --------------------------------------------
+230
View File
@@ -0,0 +1,230 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { canonicalize } from "../src/jcs.ts";
import {
InputError,
buildToOwner,
checkBuyerText,
containsLink,
envelopeHash,
mailbox,
newThreadSecret,
openReply,
threadPublic,
toHex,
type Envelope,
} from "../src/message.ts";
import { sha256 } from "@noble/hashes/sha2.js";
import { leadingZeroBits } from "../src/verify.ts";
import { NOW, newParty, openAsOwner, sealReply } from "./helpers.ts";
// Written by the Go implementation (internal/message): the browser must
// reproduce it byte for byte and open what Go sealed.
const fx = JSON.parse(
readFileSync(new URL("../../internal/message/testdata/fixture.json", import.meta.url), "utf8"),
);
const fromHex = (s: string) => Uint8Array.from(Buffer.from(s, "hex"));
const secret = fromHex(fx.thread_secret);
const ref = fx.listing as { author: string; id: string };
const toBuyer = () => JSON.parse(fx.to_buyer.canonical) as Envelope;
test("thread key and mailbox tag match Go", () => {
assert.equal(threadPublic(secret), fx.thread_public);
assert.equal(mailbox(fx.thread_public), fx.mailbox);
});
test("a buyer's envelope is byte-identical to the one Go sealed", async () => {
const env = await buildToOwner({
listing: { ...ref, device: fx.device },
threadSecret: secret,
text: fx.to_owner.plain.text,
n: 1,
now: fx.now,
difficulty: fx.difficulty,
first: true,
esk: fromHex(fx.to_owner.esk),
});
assert.equal(canonicalize(env), fx.to_owner.canonical);
assert.equal(envelopeHash(env), fx.to_owner.hash);
assert.ok(leadingZeroBits(sha256(new TextEncoder().encode(canonicalize(env)))) >= fx.difficulty);
});
test("a reply sealed and signed by Go opens and verifies in the browser", () => {
const r = openReply(toBuyer(), secret, ref);
assert.ok(r.ok, r.ok ? "" : r.error);
assert.equal(canonicalize(r.plain), fx.to_buyer.plain_canonical);
assert.equal(r.plain.t, "grant");
assert.equal(r.plain.address, "Musterstraße 12, 20255 Hamburg");
assert.equal(r.plain.note, "Samstag 10 Uhr, bitte zweimal klingeln \u{1F514}");
});
test("tampering with a Go reply is detected", () => {
const flip = (c: string) => (c === "0" ? "1" : "0");
const cases: Record<string, (e: Envelope) => void> = {
"created_at": (e) => void (e.created_at += 1),
"expires_at": (e) => void (e.expires_at -= 1),
"listing id": (e) => void (e.listing = { ...e.listing, id: "cd".repeat(16) }),
"ciphertext": (e) => void (e.ct = flip(e.ct[0]!) + e.ct.slice(1)),
"ephemeral key": (e) => void (e.epk = flip(e.epk[0]!) + e.epk.slice(1)),
"low-order ephemeral key": (e) => void (e.epk = "00".repeat(32)),
"mailbox": (e) => void (e.rcpt = "ab".repeat(16)),
"direction": (e) => void (e.to = "owner"),
"version": (e) => void (e.v = 2),
"uppercase ct": (e) => void (e.ct = e.ct.toUpperCase()),
"empty ct": (e) => void (e.ct = ""),
};
for (const [name, mutate] of Object.entries(cases)) {
const e = toBuyer();
mutate(e);
assert.equal(openReply(e, secret, ref).ok, false, `${name} went unnoticed`);
}
// Another conversation's key, or the wrong listing, cannot open it either.
assert.equal(openReply(toBuyer(), newThreadSecret(), ref).ok, false);
assert.equal(openReply(toBuyer(), secret, { ...ref, id: "cd".repeat(16) }).ok, false);
assert.equal(openReply(toBuyer(), secret, { ...ref, author: "cd".repeat(32) }).ok, false);
for (const junk of [null, 5, "x", [], {}, { listing: 3 }]) {
assert.equal(openReply(junk, secret, ref).ok, false);
}
});
test("link detection agrees with Go on every vector", () => {
assert.ok(fx.links.length >= 10);
for (const c of fx.links as { text: string; link: boolean }[]) {
assert.equal(containsLink(c.text), c.link, JSON.stringify(c.text));
}
});
test("buyer text rules", () => {
assert.equal(checkBuyerText("Hallo, ist das noch frei?", true), null);
assert.equal(checkBuyerText("", true), "empty");
assert.equal(checkBuyerText("schaut https://x.de", true), "link");
assert.equal(checkBuyerText("schaut https://x.de", false), null, "links are fine once the owner replied");
assert.equal(checkBuyerText("a".repeat(1001), true), "long");
assert.equal(checkBuyerText("a".repeat(1001), false), null);
assert.equal(checkBuyerText("a".repeat(2001), false), "long");
assert.equal(checkBuyerText("ä".repeat(501), true), "long", "limits count UTF-8 bytes, not characters");
assert.equal(checkBuyerText("a\u0007b", true), "control");
assert.equal(checkBuyerText("a\nb
c", true), null, "newlines and U+2028 are fine");
assert.equal(checkBuyerText("a\uD800b", true), "invalid", "a lone surrogate cannot be sent");
});
test("buildToOwner refuses text that breaks the rules", async () => {
const o = newParty();
const args = { listing: o.listing, threadSecret: newThreadSecret(), n: 1, now: NOW, difficulty: 4, first: true };
await assert.rejects(buildToOwner({ ...args, text: "see https://example.com" }), (e) => e instanceof InputError && e.problem === "link");
await assert.rejects(buildToOwner({ ...args, text: "" }), (e) => e instanceof InputError && e.problem === "empty");
// Even with the owner's relaxed limit, newlines can blow the 4095-byte plaintext.
await assert.rejects(buildToOwner({ ...args, first: false, text: "\n".repeat(2000) }), InputError);
});
test("what the browser seals, the owner's device key opens", async () => {
const o = newParty();
const tk = newThreadSecret();
const env = await buildToOwner({
listing: o.listing, threadSecret: tk, text: "Ist die Wohnung noch frei? \u{1F3E0}", n: 1, now: NOW, difficulty: 10, first: true,
});
assert.equal(env.to, "owner");
assert.equal(env.rcpt, o.device);
assert.ok(leadingZeroBits(sha256(new TextEncoder().encode(canonicalize(env)))) >= 10);
assert.ok(canonicalize(env).length < 10 * 1024);
assert.ok(!canonicalize(env).includes(threadPublic(tk)), "the thread key must not appear on the wire");
const p = openAsOwner(env, o);
assert.equal(p.text, "Ist die Wohnung noch frei? \u{1F3E0}");
assert.equal(p.thread, threadPublic(tk));
// Different every time: fresh ephemeral key.
const again = await buildToOwner({
listing: o.listing, threadSecret: tk, text: "Ist die Wohnung noch frei? \u{1F3E0}", n: 1, now: NOW, difficulty: 4, first: true,
});
assert.notEqual(again.epk, env.epk);
assert.notEqual(again.ct, env.ct);
});
test("ciphertext length only reveals a size bucket", async () => {
const o = newParty();
const size = async (text: string) =>
(await buildToOwner({ listing: o.listing, threadSecret: newThreadSecret(), text, n: 1, now: NOW, difficulty: 2, first: false })).ct.length;
assert.equal(await size("hi"), await size("x".repeat(250)));
assert.equal(await size("hi"), (512 + 16) * 2);
assert.ok((await size("x".repeat(900))) > (await size("hi")));
});
// --- replies built by a TypeScript "owner" ------------------------------------
async function setup() {
const owner = newParty();
const tk = newThreadSecret();
const tp = threadPublic(tk);
const lref = { author: owner.author, id: owner.listing.id };
return { owner, tk, tp, lref };
}
test("a genuine reply and grant are accepted", async () => {
const { owner, tk, tp, lref } = await setup();
const text = await sealReply(owner, lref, { t: "text", n: 1, text: "Ja, noch frei." }, tp);
const r = openReply(text, tk, lref);
assert.ok(r.ok, r.ok ? "" : r.error);
assert.equal(r.plain.text, "Ja, noch frei.");
const grant = await sealReply(
owner, lref,
{ t: "grant", n: 2, address: "Weg 1, 20095 Hamburg", phone: "+49 40 1", note: "Samstag 10 Uhr", valid_until: NOW + 7 * 86_400 },
tp,
);
const g = openReply(grant, tk, lref);
assert.ok(g.ok, g.ok ? "" : g.error);
assert.equal(g.plain.address, "Weg 1, 20095 Hamburg");
assert.equal(g.plain.valid_until, NOW + 7 * 86_400);
});
test("forgeries and replays are rejected", async () => {
const { owner, tk, tp, lref } = await setup();
const imposter = newParty();
const base = { t: "text", n: 1, text: "Überweisen Sie die Kaution" };
const expectBad = async (name: string, env: Promise<Envelope>, why: RegExp, expect = lref, key = tk) => {
const r = openReply(await env, key, expect);
assert.equal(r.ok, false, `${name} was accepted`);
if (!r.ok) assert.match(r.error, why, name);
};
// Signed by another identity's device, claiming to be the listing's owner.
await expectBad("imposter", sealReply(owner, lref, base, tp, { signer: imposter }), /certificate/);
// The signature no longer matches after the content changed.
await expectBad("edited after signing", sealReply(owner, lref, base, tp, { afterSign: (p) => void (p.text = "Kaution an IBAN ...") }), /signature/);
// A reply for another thread, moved into this one.
const other = threadPublic(newThreadSecret());
await expectBad("replayed from another thread",
sealReply(owner, lref, base, tp, { beforeSign: (p) => void (p.thread = other), afterSign: (p) => void (p.thread = tp) }),
/signature/);
// Unsigned, or missing parts.
await expectBad("no certificate", sealReply(owner, lref, base, tp, { beforeSign: (p) => void delete p.cert }), /not signed/);
await expectBad("no listing", sealReply(owner, lref, base, tp, { beforeSign: (p) => void delete p.listing }), /not signed/);
// Unknown field: the plaintext must be exactly the canonical form of what is allowed... and signed.
await expectBad("unknown type", sealReply(owner, lref, { ...base, t: "image" }, tp), /unknown type/);
await expectBad("text with grant fields", sealReply(owner, lref, { ...base, address: "Weg 1" }, tp), /grant fields/);
// A certificate that does not cover the message's time.
const stale = newParty({}, { issued_at: NOW - 2000, expires_at: NOW - 10 });
await expectBad("certificate expired before sending", sealReply(stale, { author: stale.author, id: stale.listing.id }, base, tp),
/certificate's validity/, { author: stale.author, id: stale.listing.id });
// Referring to a listing other than the conversation's.
await expectBad("another listing", sealReply(owner, { ...lref, id: "cd".repeat(16) }, base, tp), /another listing/);
// The signed listing inside disagrees with the envelope's.
await expectBad("envelope and plaintext disagree",
sealReply(owner, lref, base, tp, { beforeSign: (p) => void (p.listing = { ...lref, id: "ee".repeat(16) }) }), /another listing/);
// Encrypted to someone else's thread key.
await expectBad("wrong key", sealReply(owner, lref, base, tp), /not a reply|decrypt/, lref, newThreadSecret());
// Grant rules.
const grant = { t: "grant", n: 2, address: "Weg 1", valid_until: NOW + 86_400 };
await expectBad("grant without address", sealReply(owner, lref, grant, tp, { beforeSign: (p) => void delete p.address }), /address/);
await expectBad("grant valid too long", sealReply(owner, lref, { ...grant, valid_until: NOW + 31 * 86_400 }, tp), /validity/);
await expectBad("grant already expired", sealReply(owner, lref, { ...grant, valid_until: NOW }, tp), /validity/);
await expectBad("grant with text", sealReply(owner, lref, { ...grant, text: "hi" }, tp), /note/);
await expectBad("control character", sealReply(owner, lref, { t: "text", n: 1, text: "a\u0007b" }, tp), /bad text/);
await expectBad("counter zero", sealReply(owner, lref, { t: "text", n: 0, text: "x" }, tp), /counter/);
});
+2 -1
View File
@@ -78,7 +78,8 @@ test("detail view shows the content and a passing verification report", async ()
assert.equal(page.document.querySelectorAll(".checks li.ok").length, 6);
assert.equal(page.document.querySelectorAll(".checks li.bad").length, 0);
assert.ok(page.document.querySelector("a[href^='https://www.openstreetmap.org/']")!.getAttribute("rel")!.includes("noopener"));
assert.match(text, /not available yet/);
assert.match(text, /Contact the owner/);
assert.ok(page.document.querySelector("form.compose textarea"), "the contact form is offered");
} finally {
page.close();
}