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
+2029 -192
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -12,6 +12,7 @@
<body>
<header class="top">
<a class="brand" href="#/">Allmende</a>
<nav id="nav" class="nav"></nav>
<span id="status" class="status"></span>
</header>
<main id="app"></main>
+24
View File
@@ -212,3 +212,27 @@ pre {
.detail-head { flex-direction: column; }
.kv { grid-template-columns: 1fr; }
}
/* Messages */
.nav { margin-left: auto; }
textarea {
width: 100%;
box-sizing: border-box;
padding: 8px 10px;
font: inherit;
color: var(--text);
background: var(--bg);
border: 1px solid var(--line);
border-radius: 8px;
resize: vertical;
}
textarea:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.compose .actions { margin-top: 8px; align-items: center; }
.small { font-size: 0.85rem; }
.pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; }
.thread, .convs { list-style: none; margin: 0 0 16px; padding: 0; display: grid; gap: 10px; }
.msg { max-width: 85%; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
.msg.out { justify-self: end; border-color: var(--accent); }
.msg .who { color: var(--muted); font-size: 0.85rem; margin-bottom: 4px; }
.grant { border: 2px solid var(--accent); border-radius: 8px; padding: 10px 12px; margin: 4px 0; }
input[readonly] { width: 100%; box-sizing: border-box; }
+13
View File
@@ -7,6 +7,7 @@
"name": "allmende-web",
"license": "AGPL-3.0-only",
"dependencies": {
"@noble/ciphers": "2.4.0",
"@noble/curves": "2.4.0",
"@noble/hashes": "2.4.0"
},
@@ -478,6 +479,18 @@
}
}
},
"node_modules/@noble/ciphers": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz",
"integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/curves": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
+1
View File
@@ -9,6 +9,7 @@
"test": "node --test test/*.test.ts"
},
"dependencies": {
"@noble/ciphers": "2.4.0",
"@noble/curves": "2.4.0",
"@noble/hashes": "2.4.0"
},
+42 -1
View File
@@ -1,5 +1,8 @@
// Talks to the node that served this page. Everything it returns is untrusted
// until verify.ts has checked it.
// until verify.ts (listings) or message.ts (replies) has checked it.
import { canonicalize } from "./jcs.ts";
import type { Envelope } from "./message.ts";
export interface Status {
peer_id: string;
@@ -9,6 +12,8 @@ export interface Status {
peers: number;
listings: number;
difficulty: number;
/** Proof-of-work bits a message needs; absent on nodes without messaging. */
message_difficulty?: number;
}
async function getJSON(url: string): Promise<unknown> {
@@ -32,3 +37,39 @@ export async function search(params: URLSearchParams): Promise<unknown[]> {
export async function getListing(author: string, id: string): Promise<unknown | null> {
return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`);
}
/** A node refused a request. `detail` is the node's own explanation (English). */
export class HttpError extends Error {
readonly status: number;
readonly detail: string;
constructor(status: number, detail: string) {
super(`${status} ${detail}`);
this.status = status;
this.detail = detail;
}
}
/** Hands an encrypted envelope to the node, which gossips it to the listing's region. */
export async function postMessage(envelope: Envelope): Promise<void> {
const res = await fetch("/api/v1/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: canonicalize(envelope), // the node only accepts the canonical encoding
});
if (res.ok) return;
let detail = res.statusText;
try {
const body = (await res.json()) as { error?: unknown };
if (typeof body.error === "string") detail = body.error;
} catch {
// keep the status text
}
throw new HttpError(res.status, detail);
}
/** Envelopes in a mailbox created at or after `since` (unix seconds). Unverified. */
export async function pollMailbox(tag: string, since: number): Promise<unknown[]> {
const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`);
if (!Array.isArray(data)) throw new Error("unexpected response");
return data;
}
+422
View File
@@ -0,0 +1,422 @@
// The buyer's side of messaging: the contact form on a listing, a conversation
// and the list of conversations. Everything from the network is shown as text
// only, and owner messages only after message.ts verified them.
import { HttpError, getListing, pollMailbox, postMessage } from "./api.ts";
import { append, clear, h } from "./dom.ts";
import { date } from "./format.ts";
import { t, type Key } from "./i18n.ts";
import {
DEFAULT_MESSAGE_DIFFICULTY,
InputError,
MAX_FIRST_TEXT,
MAX_TEXT,
buildToOwner,
checkBuyerText,
envelopeHash,
mailbox,
openReply,
threadPublic,
toHex,
type Plain,
} from "./message.ts";
import { nowSeconds, state, verifyOpts } from "./state.ts";
import {
conversationHash,
deleteConversation,
getConversation,
isPersistent,
listConversations,
saveConversation,
type Conversation,
type StoredMessage,
} from "./threads.ts";
import { verifyListing, type Listing } from "./verify.ts";
const POLL_MS = 20_000;
/** Re-read this much of the mailbox each time, so a clock that is a little off loses nothing. */
const OVERLAP = 3600;
const app = () => document.getElementById("app")!;
const fromHex = (s: string) => Uint8Array.from(s.match(/../g) ?? [], (b) => parseInt(b, 16));
const difficulty = () => state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY;
const utf8 = (s: string) => new TextEncoder().encode(s).length;
function describe(e: unknown): string {
if (e instanceof InputError) return t(`problem.${e.problem}` as Key);
if (e instanceof HttpError) {
if (e.status === 404) return t("send.404");
if (e.status === 429) return t("send.429");
return t("send.other", { detail: e.detail });
}
return t("send.network");
}
// --- composing ----------------------------------------------------------------
/**
* A text box with a send button. `send` does the work; errors are shown under
* the box, and the text is kept so nothing the person wrote is lost.
*/
function composer(opts: {
first: () => boolean;
button: Key;
send: (text: string) => Promise<void>;
}): HTMLElement {
const area = h("textarea", { name: "message", rows: 5, "aria-label": t("contact.label"), required: true });
const counter = h("span", { class: "muted" });
const problem = h("p", { class: "error", role: "alert" });
const button = h("button", { type: "submit", class: "btn primary" }, t(opts.button));
const update = () => {
const max = opts.first() ? MAX_FIRST_TEXT : MAX_TEXT;
counter.textContent = t("contact.counter", { used: utf8(area.value), max });
};
area.addEventListener("input", update);
update();
const form = h(
"form",
{
class: "compose",
onsubmit: (ev) => {
ev.preventDefault();
void (async () => {
problem.textContent = "";
const text = area.value.trim();
const bad = checkBuyerText(text, opts.first());
if (bad) {
problem.textContent = t(`problem.${bad}` as Key);
return;
}
button.disabled = true;
area.disabled = true;
button.textContent = t("contact.sending");
try {
await opts.send(text);
area.value = "";
update();
} catch (e) {
problem.textContent = describe(e);
} finally {
button.disabled = false;
area.disabled = false;
button.textContent = t(opts.button);
}
})();
},
},
area,
h("div", { class: "actions" }, button, counter),
problem,
);
return form;
}
/** Sends the next message of a conversation and records it. */
async function sendTo(c: Conversation, listing: Listing, text: string, first: boolean): Promise<void> {
const n = c.messages.filter((m) => m.dir === "out").length + 1;
const now = nowSeconds();
const env = await buildToOwner({
listing,
threadSecret: fromHex(c.secret),
text,
n,
now,
difficulty: difficulty(),
first,
});
await postMessage(env);
c.messages.push({ dir: "out", n, sent_at: now, t: "text", text });
c.updated = now;
saveConversation(c);
}
// --- contact form on a listing --------------------------------------------------
export function contactPanel(l: Listing): HTMLElement {
const existing = getConversation(l.author, l.id);
if (existing) {
return h(
"section",
{ class: "panel contact" },
h("h2", null, t("contact.title")),
h("p", null, t("contact.already")),
h("a", { class: "btn", href: conversationHash(l.author, l.id, existing.secret) }, t("contact.open")),
);
}
const form = composer({
first: () => true,
button: "contact.send",
send: async (text) => {
const secret = toHex(crypto.getRandomValues(new Uint8Array(32)));
const c: Conversation = {
author: l.author,
id: l.id,
secret,
title: l.title ?? "",
created: nowSeconds(),
updated: nowSeconds(),
messages: [],
since: nowSeconds() - OVERLAP,
seen: {},
};
await sendTo(c, l, text, true);
location.hash = conversationHash(l.author, l.id, secret);
},
});
return h(
"section",
{ class: "panel contact" },
h("h2", null, t("contact.title")),
h("p", null, t("contact.intro")),
h("p", { class: "muted" }, t("contact.rules")),
form,
);
}
// --- one conversation --------------------------------------------------------------
function grantCard(m: StoredMessage): HTMLElement {
const row = (k: Key, v: string | undefined) => (v ? [h("dt", null, t(k)), h("dd", { class: "pre" }, v)] : []);
return h(
"div",
{ class: "grant" },
h("strong", null, t("grant.title")),
h(
"dl",
{ class: "kv" },
...row("grant.address", m.address),
...row("grant.phone", m.phone),
...row("grant.email", m.email),
...row("grant.note", m.note),
),
h("p", { class: "muted" }, t("grant.until", { date: date(m.valid_until ?? 0) }), " · ", t("grant.privacy")),
);
}
function bubble(m: StoredMessage): HTMLElement {
const mine = m.dir === "out";
return h(
"li",
{ class: `msg ${mine ? "out" : "in"}` },
h("div", { class: "who" }, mine ? t("chat.you") : t("chat.owner"), " · ", new Date(m.sent_at * 1000).toLocaleString()),
m.t === "grant" ? grantCard(m) : h("p", { class: "pre" }, m.text ?? ""),
!mine && h("div", { class: "muted small" }, "✓ ", t("chat.verified")),
);
}
function stored(p: Plain, hash: string): StoredMessage {
const m: StoredMessage = { dir: "in", n: p.n, sent_at: p.sent_at, t: p.t, hash };
for (const k of ["text", "address", "phone", "email", "note", "valid_until"] as const) {
if (p[k] !== undefined) (m as unknown as Record<string, unknown>)[k] = p[k];
}
return m;
}
/** Fetches the mailbox once. Returns how many envelopes were not genuine. */
async function poll(c: Conversation): Promise<number> {
const secret = fromHex(c.secret);
const envs = await pollMailbox(mailbox(threadPublic(secret)), c.since);
const now = nowSeconds();
let rejected = 0;
let newest = 0;
for (const raw of envs) {
let hash: string;
try {
hash = envelopeHash(raw as never);
} catch {
rejected++;
continue;
}
if (hash in c.seen) continue;
const r = openReply(raw, secret, { author: c.author, id: c.id });
const env = raw as { created_at?: number; expires_at?: number };
c.seen[hash] = typeof env.expires_at === "number" ? env.expires_at : now + 14 * 86_400;
if (typeof env.created_at === "number") newest = Math.max(newest, env.created_at);
if (!r.ok) {
rejected++;
continue;
}
c.messages.push(stored(r.plain, hash));
c.updated = now;
}
for (const [k, exp] of Object.entries(c.seen)) if (exp < now - 86_400) delete c.seen[k];
if (newest > 0) c.since = Math.max(c.since, Math.min(newest, now) - OVERLAP);
saveConversation(c);
return rejected;
}
export async function showConversation(author: string, id: string, secret: string): Promise<void> {
const gen = state.generation;
const root = app();
clear(root);
let c = getConversation(author, id);
if (c && c.secret !== secret) c = undefined; // a link for a different thread of the same listing
if (!c) {
c = {
author, id, secret, title: "", created: nowSeconds(), updated: nowSeconds(),
messages: [], since: nowSeconds() - 14 * 86_400, seen: {},
};
}
const conv = c;
const heading = h("h1", null, conv.title ? t("chat.title", { title: conv.title }) : t("chat.untitled", { id: id.slice(0, 8) }));
const list = h("ul", { class: "thread", "aria-live": "polite" });
const notes = h("div", null);
const composeSlot = h("div", null);
const link = location.origin + location.pathname + conversationHash(author, id, secret);
append(root, [
h("a", { class: "back", href: `#/l/${author}/${id}` }, t("chat.back")),
" ",
h("a", { class: "back", href: "#/messages" }, t("chat.all")),
heading,
!isPersistent() && h("p", { class: "error" }, t("chat.noStorage")),
notes,
list,
composeSlot,
h(
"section",
{ class: "panel" },
h("h2", null, t("chat.link")),
h("p", { class: "muted" }, t("chat.linkHelp")),
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e) => (e.target as HTMLInputElement).select() }),
),
deleteControl(conv),
]);
let listing: Listing | null = null;
let listingProblem: Key | null = null;
const render = (rejected: number, pollFailed: boolean) => {
const now = nowSeconds();
clear(list);
clear(notes);
const shown = [...conv.messages]
.sort((a, b) => a.sent_at - b.sent_at || (a.dir === "out" ? -1 : 1))
.filter((m) => !(m.t === "grant" && (m.valid_until ?? 0) <= now));
const expired = conv.messages.filter((m) => m.t === "grant" && (m.valid_until ?? 0) <= now).length;
for (const m of shown) list.append(bubble(m));
if (!conv.messages.some((m) => m.dir === "in")) list.append(h("li", { class: "muted" }, t("chat.empty")));
if (expired) notes.append(h("p", { class: "muted" }, t("grant.expired")));
if (rejected) notes.append(h("p", { class: "error" }, t("chat.rejected", { n: rejected })));
if (pollFailed) notes.append(h("p", { class: "error" }, t("chat.pollError")));
if (listingProblem) notes.append(h("p", { class: "muted" }, t(listingProblem)));
if (conv.messages.some((m) => m.dir === "in")) notes.append(h("p", { class: "muted small" }, t("chat.limit")));
};
const renderComposer = () => {
clear(composeSlot);
if (!listing) return;
const repliedTo = () => conv.messages.some((m) => m.dir === "in");
composeSlot.append(
h(
"section",
{ class: "panel" },
h("h2", null, t("chat.reply")),
!repliedTo() && h("p", { class: "muted" }, t("chat.replyRules")),
composer({
first: () => !repliedTo(),
button: "contact.send",
send: async (text) => {
await sendTo(conv, listing!, text, !repliedTo());
if (gen === state.generation) {
render(0, false);
renderComposer();
}
},
}),
),
);
};
render(0, false);
// The listing gives us the device key to write to and, for a conversation
// opened from a bare link, its title. Replies can be read without it.
void (async () => {
try {
const raw = await getListing(author, id);
if (gen !== state.generation) return;
if (raw === null) {
listingProblem = "chat.gone";
} else {
const l = raw as Listing;
const v = verifyListing(raw, verifyOpts());
if (v.ok && l.author === author && l.id === id) {
listing = l;
if (!conv.title && l.title) {
conv.title = l.title;
heading.textContent = t("chat.title", { title: l.title });
if (getConversation(author, id)) saveConversation(conv);
}
} else {
listingProblem = "chat.unverified";
}
}
} catch {
if (gen !== state.generation) return;
listingProblem = "chat.unverified";
}
render(0, false);
renderComposer();
})();
const cycle = async () => {
if (gen !== state.generation) return;
let rejected = 0;
let failed = false;
try {
rejected = await poll(conv);
} catch {
failed = true;
}
if (gen !== state.generation) return;
render(rejected, failed);
setTimeout(() => void cycle(), POLL_MS);
};
await cycle();
}
function deleteControl(c: Conversation): HTMLElement {
const slot = h("p", null);
const ask = () => {
clear(slot);
append(slot, [
t("chat.deleteSure"),
" ",
h("button", { type: "button", class: "btn", onclick: () => { deleteConversation(c.author, c.id); location.hash = "#/messages"; } }, t("chat.deleteYes")),
]);
};
slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("chat.delete")));
return slot;
}
// --- all conversations ---------------------------------------------------------------
export function showInbox(): void {
const root = app();
clear(root);
const convs = listConversations();
append(root, [
h("a", { class: "back", href: "#/" }, t("detail.back")),
h("h1", null, t("inbox.title")),
!isPersistent() && h("p", { class: "error" }, t("chat.noStorage")),
convs.length === 0
? h("p", { class: "muted" }, t("inbox.none"))
: h(
"ul",
{ class: "convs" },
...convs.map((c) =>
h(
"li",
{ class: "panel" },
h("a", { href: conversationHash(c.author, c.id, c.secret) }, c.title || t("chat.untitled", { id: c.id.slice(0, 8) })),
h("div", { class: "muted small" }, t("inbox.last", { date: date(c.updated) })),
),
),
),
h("p", { class: "muted" }, t("inbox.note")),
]);
}
+120 -4
View File
@@ -46,8 +46,66 @@ const de = {
"detail.location": "Lage (ungefähr, ca. 1 km)",
"detail.map": "Auf OpenStreetMap ansehen (externe Seite)",
"detail.contact": "Kontakt",
"detail.contactSoon":
"Der Kontakt zum Anbieter läuft über dessen eigenen Knoten und ist noch nicht verfügbar. Die genaue Adresse wird nie öffentlich verteilt.",
"nav.messages": "Meine Nachrichten",
"contact.title": "Anbieter kontaktieren",
"contact.intro":
"Deine Nachricht wird verschlüsselt. Das Netzwerk sieht nur, dass jemand zu dieser Anzeige geschrieben hat, nicht wer und nicht was. Du brauchst kein Konto. Die genaue Adresse gibt der Anbieter selbst frei.",
"contact.rules":
"Die erste Nachricht muss kurz sein und darf keine Links enthalten. Das schützt vor Betrug; nach der ersten Antwort des Anbieters entfällt es.",
"contact.label": "Deine Nachricht",
"contact.counter": "{used} / {max} Bytes",
"contact.send": "Verschlüsselt senden",
"contact.sending": "Wird vorbereitet … (eine kleine Rechenaufgabe gegen Spam)",
"contact.already": "Du hast diesem Anbieter schon geschrieben.",
"contact.open": "Unterhaltung öffnen",
"problem.empty": "Bitte schreibe eine Nachricht.",
"problem.long": "Die Nachricht ist zu lang.",
"problem.control": "Die Nachricht enthält unerlaubte Sonderzeichen.",
"problem.invalid": "Die Nachricht enthält ungültige Zeichen.",
"problem.link":
"Die erste Nachricht darf keine Links oder Webadressen enthalten (auch kein „Hallo.Ich“ ohne Leerzeichen nach dem Punkt).",
"send.404":
"Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Gerät gewechselt. Lade die Anzeige neu.",
"send.429": "Zu viele Nachrichten. Bitte warte einen Moment.",
"send.other": "Senden fehlgeschlagen: {detail}",
"send.network": "Der Knoten ist nicht erreichbar.",
"chat.back": "← Zur Anzeige",
"chat.all": "← Alle Nachrichten",
"chat.title": "Unterhaltung zu: {title}",
"chat.untitled": "Anzeige {id}",
"chat.you": "Du",
"chat.owner": "Anbieter",
"chat.verified": "Vom Anbieter dieser Anzeige (Signatur geprüft)",
"chat.empty":
"Noch keine Antwort. Der Anbieter bekommt deine Nachricht, sobald sein Knoten online ist (die Nachricht bleibt bis zu 14 Tage im Netz).",
"chat.reply": "Antworten",
"chat.replyRules": "Solange der Anbieter nicht geantwortet hat, gelten die Regeln der ersten Nachricht.",
"chat.link": "Dein privater Link zu dieser Unterhaltung",
"chat.linkHelp":
"Setze ein Lesezeichen. Wer diesen Link kennt, kann die Unterhaltung lesen, gib ihn also nicht weiter. Ohne den Link und ohne die Daten dieses Browsers ist die Unterhaltung verloren.",
"chat.noStorage":
"Dieser Browser speichert hier nichts (privates Fenster?). Die Unterhaltung geht verloren, wenn du die Seite schließt, außer du merkst dir den Link unten.",
"chat.gone":
"Die Anzeige ist nicht mehr verfügbar. Antworten des Anbieters kannst du weiter empfangen, aber nicht mehr schreiben.",
"chat.unverified": "Die Anzeige konnte nicht geprüft werden, daher kannst du gerade nicht schreiben.",
"chat.pollError": "Antworten konnten nicht abgerufen werden.",
"chat.rejected": "{n} Nachricht(en) im Postfach konnten nicht als echt bestätigt werden und werden ignoriert.",
"chat.limit": "Nicht prüfbar: ob der Anbieter sein Gerät inzwischen gesperrt hat.",
"chat.delete": "Unterhaltung aus diesem Browser löschen",
"chat.deleteSure": "Wirklich löschen? Ohne den Link ist sie dann weg.",
"chat.deleteYes": "Ja, löschen",
"grant.title": "Adresse vom Anbieter freigegeben",
"grant.address": "Adresse",
"grant.phone": "Telefon",
"grant.email": "E-Mail",
"grant.note": "Hinweis des Anbieters",
"grant.until": "Angezeigt bis {date}",
"grant.expired": "Eine Adressfreigabe des Anbieters ist abgelaufen und wird nicht mehr angezeigt.",
"grant.privacy": "Gib diese Angaben nicht weiter.",
"inbox.title": "Meine Nachrichten",
"inbox.none": "Du hast noch keine Unterhaltungen. Öffne eine Anzeige und schreibe dem Anbieter.",
"inbox.last": "Zuletzt: {date}",
"inbox.note": "Diese Liste liegt nur in diesem Browser.",
"verify.title": "Prüfung in deinem Browser",
"verify.intro":
"Diese Prüfung läuft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt fälschen.",
@@ -112,8 +170,66 @@ const en: Record<keyof typeof de, string> = {
"detail.location": "Location (approximate, about 1 km)",
"detail.map": "View on OpenStreetMap (external site)",
"detail.contact": "Contact",
"detail.contactSoon":
"Contact goes through the owner's own node and is not available yet. The exact address is never distributed publicly.",
"nav.messages": "My messages",
"contact.title": "Contact the owner",
"contact.intro":
"Your message is encrypted. The network only sees that someone wrote about this listing, not who and not what. You need no account. The owner releases the exact address themselves.",
"contact.rules":
"The first message must be short and must not contain links. This protects against scams; it ends once the owner has replied.",
"contact.label": "Your message",
"contact.counter": "{used} / {max} bytes",
"contact.send": "Send encrypted",
"contact.sending": "Preparing … (a small puzzle against spam)",
"contact.already": "You have already written to this owner.",
"contact.open": "Open conversation",
"problem.empty": "Please write a message.",
"problem.long": "The message is too long.",
"problem.control": "The message contains characters that are not allowed.",
"problem.invalid": "The message contains invalid characters.",
"problem.link":
"The first message must not contain links or web addresses (that includes \"Hello.I\" without a space after the full stop).",
"send.404":
"This node does not know the listing (anymore), or the owner changed device. Reload the listing.",
"send.429": "Too many messages. Please wait a moment.",
"send.other": "Sending failed: {detail}",
"send.network": "The node is not reachable.",
"chat.back": "← Back to the listing",
"chat.all": "← All messages",
"chat.title": "Conversation about: {title}",
"chat.untitled": "Listing {id}",
"chat.you": "You",
"chat.owner": "Owner",
"chat.verified": "From the owner of this listing (signature verified)",
"chat.empty":
"No reply yet. The owner receives your message once their node is online (it stays in the network for up to 14 days).",
"chat.reply": "Reply",
"chat.replyRules": "Until the owner has replied, the rules of the first message apply.",
"chat.link": "Your private link to this conversation",
"chat.linkHelp":
"Bookmark it. Anyone who knows this link can read the conversation, so do not share it. Without the link and without this browser's data, the conversation is lost.",
"chat.noStorage":
"This browser does not store anything here (private window?). The conversation is lost when you close the page unless you keep the link below.",
"chat.gone":
"The listing is no longer available. You can still receive the owner's replies, but not write any more.",
"chat.unverified": "The listing could not be verified, so you cannot write right now.",
"chat.pollError": "Replies could not be fetched.",
"chat.rejected": "{n} message(s) in the mailbox could not be confirmed as genuine and are ignored.",
"chat.limit": "Cannot be checked: whether the owner has since revoked their device.",
"chat.delete": "Delete this conversation from this browser",
"chat.deleteSure": "Really delete? Without the link it is gone.",
"chat.deleteYes": "Yes, delete",
"grant.title": "Address released by the owner",
"grant.address": "Address",
"grant.phone": "Phone",
"grant.email": "Email",
"grant.note": "Note from the owner",
"grant.until": "Shown until {date}",
"grant.expired": "An address release from the owner has expired and is no longer shown.",
"grant.privacy": "Do not pass these details on.",
"inbox.title": "My messages",
"inbox.none": "You have no conversations yet. Open a listing and write to the owner.",
"inbox.last": "Last activity: {date}",
"inbox.note": "This list is kept only in this browser.",
"verify.title": "Checked in your browser",
"verify.intro":
"This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
+21 -23
View File
@@ -1,8 +1,10 @@
import { getListing, getStatus, search, type Status } from "./api.ts";
import { getListing, getStatus, search } from "./api.ts";
import { append, clear, h } from "./dom.ts";
import { date, price, rooms, shortKey } from "./format.ts";
import { decodeGeohash } from "./geohash.ts";
import { lang, t, type Key } from "./i18n.ts";
import { contactPanel, showConversation, showInbox } from "./chat.ts";
import { state, verifyOpts } from "./state.ts";
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
const PAGE = 20;
@@ -10,17 +12,9 @@ const GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
const app = document.getElementById("app")!;
const statusEl = document.getElementById("status")!;
// Not called `status`: that would collide with the built-in window.status.
let nodeInfo: Status | null = null;
/** Bumped on every navigation so late responses for an old view are dropped. */
let generation = 0;
// --- helpers --------------------------------------------------------------
function verifyOpts() {
return { now: Math.floor(Date.now() / 1000), minPowBits: nodeInfo?.difficulty ?? 0 };
}
/** Translates a value from a listing if it is a known one; unknown values are shown as plain text. */
function label(prefix: "kind" | "cat", value: string | undefined): string {
if (!value) return "";
@@ -78,7 +72,7 @@ function select(name: string, current: string, options: [string, string][]): HTM
function searchForm(params: URLSearchParams): HTMLFormElement {
const get = (k: string) => params.get(k) ?? "";
const regions = h("datalist", { id: "regions" }, ...(nodeInfo?.regions ?? []).map((r) => h("option", { value: r })));
const regions = h("datalist", { id: "regions" }, ...(state.node?.regions ?? []).map((r) => h("option", { value: r })));
const form = h(
"form",
{ class: "filters" },
@@ -95,7 +89,7 @@ function searchForm(params: URLSearchParams): HTMLFormElement {
),
field(
t("filter.region"),
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: nodeInfo?.regions[0] ?? "u1x" }),
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: state.node?.regions[0] ?? "u1x" }),
t("filter.regionHint"),
),
field(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
@@ -160,12 +154,12 @@ async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement):
paged.set("offset", String(offset));
items = await search(paged);
} catch {
if (gen !== generation) return;
if (gen !== state.generation) return;
clear(foot);
foot.append(h("p", { class: "error" }, t("results.error")));
return;
}
if (gen !== generation) return;
if (gen !== state.generation) return;
const opts = verifyOpts();
for (const raw of items) {
@@ -190,7 +184,7 @@ async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement):
}
function showSearch(params: URLSearchParams): void {
const gen = generation;
const gen = state.generation;
clear(app);
const results = h("div", { class: "results", "aria-live": "polite" });
app.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
@@ -288,12 +282,12 @@ function listingBody(l: Listing): HTMLElement[] {
l.features?.length
? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f))))
: h("span"),
h("section", { class: "panel contact" }, h("h2", null, t("detail.contact")), h("p", null, t("detail.contactSoon"))),
contactPanel(l),
];
}
async function showDetail(author: string, id: string): Promise<void> {
const gen = generation;
const gen = state.generation;
clear(app);
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
app.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
@@ -302,12 +296,12 @@ async function showDetail(author: string, id: string): Promise<void> {
try {
raw = await getListing(author, id);
} catch {
if (gen !== generation) return;
if (gen !== state.generation) return;
clear(body);
body.append(h("p", { class: "error" }, t("results.error")));
return;
}
if (gen !== generation) return;
if (gen !== state.generation) return;
clear(body);
if (raw === null) {
@@ -331,13 +325,16 @@ async function showDetail(author: string, id: string): Promise<void> {
// --- boot -----------------------------------------------------------------
function route(): void {
generation++;
state.generation++;
const hash = location.hash.replace(/^#/, "") || "/";
const q = hash.indexOf("?");
const path = q < 0 ? hash : hash.slice(0, q);
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
const c = /^\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(path);
if (m) void showDetail(m[1]!, m[2]!);
else if (c) void showConversation(c[1]!, c[2]!, c[3]!);
else if (path === "/messages") showInbox();
else showSearch(params);
window.scrollTo(0, 0);
}
@@ -345,12 +342,13 @@ function route(): void {
async function boot(): Promise<void> {
document.documentElement.lang = lang;
document.getElementById("foot")!.textContent = t("footer.text");
document.getElementById("nav")!.append(h("a", { href: "#/messages" }, t("nav.messages")));
try {
nodeInfo = await getStatus();
state.node = await getStatus();
statusEl.textContent = t("status.line", {
listings: nodeInfo.listings,
peers: nodeInfo.peers,
regions: nodeInfo.regions.join(", "),
listings: state.node.listings,
peers: state.node.peers,
regions: state.node.regions.join(", "),
});
} catch {
statusEl.textContent = t("status.unreachable");
+440
View File
@@ -0,0 +1,440 @@
// End-to-end encrypted messages, the browser's half. This mirrors
// internal/message in Go step for step (see "Messaging" in docs/PROTOCOL.md);
// test/message.test.ts checks it against a fixture written by the Go code,
// down to the byte.
//
// The buyer only ever *seals to* the listing's device key and *opens replies*
// with a per-conversation thread key, so that is all that is implemented here.
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 { canonicalize } from "./jcs.ts";
import {
CERT_CONTEXT,
MAX_CERT_LIFETIME,
hexBytes,
isObject,
safeInt,
signedBy,
without,
type Cert,
} from "./verify.ts";
export const VERSION = 1;
export const MAX_LIFETIME = 14 * 86_400;
/** Largest plaintext before padding; one byte is kept for the padding marker. */
export const MAX_PLAIN = 4095;
export const MAX_FIRST_TEXT = 1000;
export const MAX_TEXT = 2000;
export const MAX_ADDRESS = 300;
export const MAX_PHONE = 40;
export const MAX_EMAIL = 120;
export const MAX_NOTE = 1000;
export const MAX_GRANT_VALIDITY = 30 * 86_400;
/** What a node requires unless it says otherwise (it reports it in /status). */
export const DEFAULT_MESSAGE_DIFFICULTY = 14;
const BUCKETS = [512, 1024, 2048, 4096];
const TAG = 16;
const enc = new TextEncoder();
const SEAL_INFO = enc.encode("allmende-seal-v1");
const MAILBOX_CONTEXT = "allmende-mailbox-v1\n";
const REPLY_CONTEXT = "allmende-reply-v1\n";
export interface Ref {
author: string;
id: string;
}
export interface Envelope {
v: number;
listing: Ref;
to: "owner" | "buyer";
rcpt: string;
epk: string;
created_at: number;
expires_at: number;
ct: string;
pow: number;
}
export interface Plain {
t: "text" | "grant";
thread: string;
n: number;
sent_at: number;
text?: string;
address?: string;
phone?: string;
email?: string;
note?: string;
valid_until?: number;
listing?: Ref;
device?: string;
cert?: Cert;
sig?: string;
}
// --- bytes ------------------------------------------------------------------
export function toHex(b: Uint8Array): string {
let s = "";
for (const x of b) s += x.toString(16).padStart(2, "0");
return s;
}
function concat(...parts: Uint8Array[]): Uint8Array {
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
let at = 0;
for (const p of parts) {
out.set(p, at);
at += p.length;
}
return out;
}
const byteLength = (s: string): number => enc.encode(s).length;
// --- text rules (the same as the owner's node applies) -------------------------
export type InputProblem = "empty" | "long" | "control" | "invalid" | "link";
/** Thrown when the text of a message breaks the protocol's rules. */
export class InputError extends Error {
readonly problem: InputProblem;
constructor(problem: InputProblem) {
super(`message text rejected: ${problem}`);
this.problem = problem;
}
}
// label.tld in any script; "z. B." and "etc." do not match, "Hallo.Ich" does.
const HOSTNAME = /[\p{L}\p{N}-]+\.\p{L}{2,}/u;
/** A heuristic for URLs and addresses; a speed bump against scams, not a guarantee. */
export function containsLink(s: string): boolean {
const l = s.toLowerCase();
return l.includes("://") || l.includes("www.") || HOSTNAME.test(l);
}
/** Checks a buyer's text. `first` applies while the owner has not replied yet. */
export function checkBuyerText(text: string, first: boolean): InputProblem | null {
if (text.length === 0) return "empty";
if (/\p{Cs}/u.test(text)) return "invalid";
if (/[\p{Cc}]/u.test(text.replace(/\n/g, ""))) return "control";
if (byteLength(text) > (first ? MAX_FIRST_TEXT : MAX_TEXT)) return "long";
if (first && containsLink(text)) return "link";
return null;
}
function validField(s: unknown, maxBytes: number, min: number, newlines: boolean): boolean {
if (typeof s !== "string") return false;
if (s.length < min || byteLength(s) > maxBytes) return false;
if (/\p{Cs}/u.test(s)) return false;
return !/[\p{Cc}]/u.test(newlines ? s.replace(/\n/g, "") : s);
}
// --- keys -------------------------------------------------------------------
/** A fresh thread secret (X25519). One per conversation, never reused. */
export function newThreadSecret(): Uint8Array {
return x25519.utils.randomSecretKey();
}
export function threadPublic(secret: Uint8Array): string {
return toHex(x25519.getPublicKey(secret));
}
/** The tag replies are addressed to: the thread key itself never goes on the wire. */
export function mailbox(threadPubHex: string): string {
const pub = hexBytes(threadPubHex, 32);
if (!pub) throw new Error("bad thread key");
return toHex(sha256(concat(enc.encode(MAILBOX_CONTEXT), pub)).slice(0, 16));
}
/** The envelope's identity: sha256 of its canonical bytes, hex. */
export function envelopeHash(env: Envelope): string {
return toHex(sha256(enc.encode(canonicalize(env))));
}
// --- sealing ----------------------------------------------------------------
function pad(b: Uint8Array): Uint8Array {
if (b.length > MAX_PLAIN) throw new InputError("long");
const size = BUCKETS.find((s) => b.length + 1 <= s) ?? BUCKETS[BUCKETS.length - 1]!;
const out = new Uint8Array(size);
out.set(b);
out[b.length] = 0x80;
return out;
}
function unpad(b: Uint8Array): Uint8Array {
let end = b.length;
while (end > 0 && b[end - 1] === 0) end--;
if (end === 0 || b[end - 1] !== 0x80) throw new Error("bad padding");
return b.slice(0, end - 1);
}
function aead(shared: Uint8Array, epk: Uint8Array, rpk: Uint8Array, header: unknown) {
const key = hkdf(sha256, shared, concat(epk, rpk), SEAL_INFO, 32);
return chacha20poly1305(key, new Uint8Array(12), enc.encode(canonicalize(header)));
}
interface Header {
v: number;
listing: Ref;
to: string;
rcpt: string;
epk: string;
created_at: number;
expires_at: number;
}
function headerOf(e: Envelope): Header {
return {
v: e.v,
listing: { author: e.listing.author, id: e.listing.id },
to: e.to,
rcpt: e.rcpt,
epk: e.epk,
created_at: e.created_at,
expires_at: e.expires_at,
};
}
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
/**
* Finds a proof-of-work nonce: sha256 of the canonical envelope has at least
* `difficulty` leading zero bits. Only `pow` changes between attempts, so the
* canonical text is split once around it and the shared prefix is hashed once.
* Yields to the page now and then so it stays responsive.
*/
async function mine(env: Envelope, difficulty: number): Promise<void> {
const canon = canonicalize({ ...env, pow: 0 });
const marker = '"pow":0,';
const at = canon.indexOf(marker);
if (at < 0 || canon.indexOf(marker, at + 1) >= 0) throw new Error("unexpected envelope shape");
const prefix = sha256.create().update(enc.encode(canon.slice(0, at + 6)));
const suffix = enc.encode(canon.slice(at + 7));
for (let n = 0; n <= Number.MAX_SAFE_INTEGER; n++) {
const sum = prefix.clone().update(enc.encode(String(n))).update(suffix).digest();
if (zeroBits(sum) >= difficulty) {
env.pow = n;
return;
}
if (n % 2048 === 2047) await tick();
}
throw new Error("proof-of-work exhausted");
}
function zeroBits(b: Uint8Array): number {
let n = 0;
for (const x of b) {
if (x === 0) {
n += 8;
continue;
}
return n + Math.clz32(x) - 24;
}
return n;
}
export interface BuildArgs {
/** The listing being written about; only its author, id and device are used. */
listing: { author: string; id: string; device: string };
threadSecret: Uint8Array;
text: string;
/** This message's counter in the conversation, from 1. */
n: number;
/** Unix seconds. */
now: number;
difficulty: number;
/** True until the owner has replied: shorter, and no links. */
first: boolean;
/** Fixed ephemeral secret; only the golden tests pass this. */
esk?: Uint8Array;
}
/** Seals a buyer's message to the listing's device key and mines its proof-of-work. */
export async function buildToOwner(a: BuildArgs): Promise<Envelope> {
const problem = checkBuyerText(a.text, a.first);
if (problem) throw new InputError(problem);
const devicePub = hexBytes(a.listing.device, 32);
if (!devicePub) throw new Error("bad device key");
const plain: Plain = { t: "text", thread: threadPublic(a.threadSecret), n: a.n, sent_at: a.now, text: a.text };
return sealEnvelope({
listing: { author: a.listing.author, id: a.listing.id },
to: "owner",
rcpt: a.listing.device,
rpk: ed25519.utils.toMontgomery(devicePub),
body: enc.encode(canonicalize(plain)),
now: a.now,
difficulty: a.difficulty,
esk: a.esk,
});
}
/**
* Encrypts `body` to the X25519 key `rpk`, wraps it in an envelope and mines
* its proof-of-work. The browser only sends to owners (see buildToOwner); the
* other direction exists so tests can play the owner.
*/
export async function sealEnvelope(a: {
listing: Ref;
to: "owner" | "buyer";
rcpt: string;
rpk: Uint8Array;
body: Uint8Array;
now: number;
difficulty: number;
esk?: Uint8Array;
}): Promise<Envelope> {
const esk = a.esk ?? x25519.utils.randomSecretKey();
const epk = x25519.getPublicKey(esk);
const env: Envelope = {
v: VERSION,
listing: { author: a.listing.author, id: a.listing.id },
to: a.to,
rcpt: a.rcpt,
epk: toHex(epk),
created_at: a.now,
expires_at: a.now + MAX_LIFETIME,
ct: "",
pow: 0,
};
const shared = x25519.getSharedSecret(esk, a.rpk); // throws for a low-order key
env.ct = toHex(aead(shared, epk, a.rpk, headerOf(env)).encrypt(pad(a.body)));
await mine(env, a.difficulty);
return env;
}
// --- opening replies -----------------------------------------------------------
export type Opened = { ok: true; plain: Plain } | { ok: false; error: string };
const fail = (error: string): Opened => ({ ok: false, error });
/**
* Decrypts an envelope from the mailbox and verifies it is a genuine reply
* from the owner of `expect`'s listing: the plaintext decodes canonically, the
* certificate chains to the listing's author, and the signature covers the
* listing and this thread. Never throws.
*
* Like the listing check, it cannot know whether the owner's device was
* revoked since.
*/
export function openReply(input: unknown, threadSecret: Uint8Array, expect: Ref): Opened {
try {
return open(input, threadSecret, expect);
} catch (e) {
return fail(e instanceof Error ? e.message : "unreadable");
}
}
function open(input: unknown, threadSecret: Uint8Array, expect: Ref): Opened {
if (!isObject(input) || !isObject(input.listing)) return fail("not an envelope");
const e = input as unknown as Envelope;
const threadPub = threadPublic(threadSecret);
const epk = hexBytes(e.epk, 32);
const ct = typeof e.ct === "string" && /^[0-9a-f]*$/.test(e.ct) && e.ct.length % 2 === 0 ? hexBytes(e.ct, e.ct.length / 2) : null;
if (
e.v !== VERSION ||
e.to !== "buyer" ||
e.rcpt !== mailbox(threadPub) ||
!epk ||
!ct ||
ct.length < TAG + 1 ||
ct.length > BUCKETS[BUCKETS.length - 1]! + TAG ||
!safeInt(e.created_at) ||
!safeInt(e.expires_at)
) {
return fail("not a reply for this conversation");
}
if (e.listing.author !== expect.author || e.listing.id !== expect.id) {
return fail("reply refers to another listing");
}
const rpk = x25519.getPublicKey(threadSecret);
const shared = x25519.getSharedSecret(threadSecret, epk);
let body: Uint8Array;
try {
body = unpad(aead(shared, epk, rpk, headerOf(e)).decrypt(ct));
} catch {
return fail("cannot decrypt");
}
const text = new TextDecoder("utf-8", { fatal: true }).decode(body);
const p: unknown = JSON.parse(text);
// Canonical only: nothing unknown or oddly spelled hides in the plaintext.
if (canonicalize(p) !== text) return fail("plaintext is not canonical");
const bad = checkOwnerPlain(p);
if (bad) return fail(bad);
const plain = p as Plain;
if (plain.thread !== threadPub) return fail("reply belongs to another thread");
if (plain.listing!.author !== e.listing.author || plain.listing!.id !== e.listing.id) {
return fail("reply refers to another listing");
}
const c = plain.cert!;
const certOk =
c.v === 1 &&
hexBytes(c.author, 32) !== null &&
hexBytes(c.device, 32) !== null &&
safeInt(c.issued_at) &&
safeInt(c.expires_at) &&
c.expires_at > c.issued_at &&
c.expires_at - c.issued_at <= MAX_CERT_LIFETIME &&
signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
if (!certOk) return fail("bad certificate");
if (c.author !== plain.listing!.author || c.device !== plain.device) {
return fail("certificate does not match the listing's author and the device");
}
if (!(c.issued_at <= plain.sent_at && plain.sent_at < c.expires_at)) {
return fail("sent outside the certificate's validity");
}
if (!signedBy(REPLY_CONTEXT, without(plain, "sig"), plain.sig, plain.device)) {
return fail("bad signature");
}
return { ok: true, plain };
}
/** Structure of an owner's plaintext, as internal/message Plain.validate(ToBuyer). */
function checkOwnerPlain(p: unknown): string | null {
if (!isObject(p)) return "plaintext is not an object";
const q = p as unknown as Plain;
if (hexBytes(q.thread, 32) === null) return "bad thread";
if (!safeInt(q.n) || q.n < 1 || !safeInt(q.sent_at) || q.sent_at <= 0) return "bad counter or time";
if (
!isObject(q.listing) ||
hexBytes(q.listing.author, 32) === null ||
hexBytes(q.listing.id, 16) === null ||
hexBytes(q.device, 32) === null ||
!isObject(q.cert) ||
hexBytes(q.sig, 64) === null
) {
return "reply is not signed";
}
const grantFields = q.address !== undefined || q.phone !== undefined || q.email !== undefined ||
q.note !== undefined || q.valid_until !== undefined;
if (q.t === "text") {
if (grantFields) return "text with grant fields";
return validField(q.text, MAX_TEXT, 1, true) ? null : "bad text";
}
if (q.t === "grant") {
if (q.text !== undefined) return "a grant carries its words in note";
if (!validField(q.address, MAX_ADDRESS, 1, true)) return "bad address";
if (q.phone !== undefined && !validField(q.phone, MAX_PHONE, 1, false)) return "bad phone";
if (q.email !== undefined && !validField(q.email, MAX_EMAIL, 1, false)) return "bad email";
if (q.note !== undefined && !validField(q.note, MAX_NOTE, 1, true)) return "bad note";
if (!safeInt(q.valid_until) || q.valid_until <= q.sent_at || q.valid_until - q.sent_at > MAX_GRANT_VALIDITY) {
return "bad validity of the grant";
}
return null;
}
return "unknown type";
}
+20
View File
@@ -0,0 +1,20 @@
// State shared by the views. Kept apart from main.ts so views can live in
// their own modules without importing each other in circles.
import type { Status } from "./api.ts";
export const state = {
/** What the node that served this page says about itself; null until known. */
node: null as Status | null,
/** Bumped on every navigation so late responses for an old view are dropped. */
generation: 0,
};
export function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}
/** Options for verifying a listing against what this node says the network requires. */
export function verifyOpts(): { now: number; minPowBits: number } {
return { now: nowSeconds(), minPowBits: state.node?.difficulty ?? 0 };
}
+125
View File
@@ -0,0 +1,125 @@
// The buyer's conversations, kept in this browser only. There are no accounts:
// a conversation is its thread key, which is also in the private link the
// buyer can bookmark. Losing both loses the conversation, by design.
//
// Browser storage can be missing (private windows, blocked site data), so every
// access is guarded and the page keeps working from memory.
export interface StoredMessage {
dir: "in" | "out";
n: number;
sent_at: number;
t: "text" | "grant";
text?: string;
address?: string;
phone?: string;
email?: string;
note?: string;
valid_until?: number;
/** Envelope hash, for messages received from the owner. */
hash?: string;
}
export interface Conversation {
author: string;
id: string;
/** The thread secret, hex. */
secret: string;
title: string;
created: number;
updated: number;
messages: StoredMessage[];
/** Mailbox poll position (unix seconds). */
since: number;
/** Envelopes already looked at (hash -> their expiry), so they are not verified again. */
seen: Record<string, number>;
}
const KEY = "allmende.conversations.v1";
const cache = new Map<string, Conversation>();
let loaded = false;
let persistent = true;
const idOf = (author: string, id: string) => `${author}/${id}`;
const HEX = (n: number) => new RegExp(`^[0-9a-f]{${n}}$`);
function wellFormed(c: unknown): c is Conversation {
if (typeof c !== "object" || c === null) return false;
const x = c as Record<string, unknown>;
return (
typeof x.author === "string" && HEX(64).test(x.author) &&
typeof x.id === "string" && HEX(32).test(x.id) &&
typeof x.secret === "string" && HEX(64).test(x.secret) &&
typeof x.title === "string" &&
typeof x.created === "number" && typeof x.updated === "number" &&
Array.isArray(x.messages) && typeof x.since === "number" &&
typeof x.seen === "object" && x.seen !== null
);
}
function load(): void {
if (loaded) return;
loaded = true;
try {
const raw = localStorage.getItem(KEY);
if (!raw) return;
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return;
for (const c of Object.values(parsed)) {
if (wellFormed(c)) cache.set(idOf(c.author, c.id), c);
}
} catch {
persistent = false;
}
}
function flush(): void {
try {
localStorage.setItem(KEY, JSON.stringify(Object.fromEntries(cache)));
} catch {
persistent = false;
}
}
/** False when this browser refuses to store anything, so conversations vanish with the page. */
export function isPersistent(): boolean {
load();
if (persistent) {
try {
localStorage.setItem(KEY + ".probe", "1");
localStorage.removeItem(KEY + ".probe");
} catch {
persistent = false;
}
}
return persistent;
}
export function getConversation(author: string, id: string): Conversation | undefined {
load();
return cache.get(idOf(author, id));
}
export function saveConversation(c: Conversation): void {
load();
cache.set(idOf(c.author, c.id), c);
flush();
}
export function deleteConversation(author: string, id: string): void {
load();
cache.delete(idOf(author, id));
flush();
}
/** Most recently active first. */
export function listConversations(): Conversation[] {
load();
return [...cache.values()].sort((a, b) => b.updated - a.updated);
}
/** The private link to a conversation. The secret stays in the URL fragment, which is never sent to a server. */
export function conversationHash(author: string, id: string, secret: string): string {
return `#/c/${author}/${id}/${secret}`;
}
+7 -7
View File
@@ -11,10 +11,10 @@ import { sha256 } from "@noble/hashes/sha2.js";
import { canonicalize } from "./jcs.ts";
const LISTING_CONTEXT = "allmende-listing-v1\n";
const CERT_CONTEXT = "allmende-cert-v1\n";
export const CERT_CONTEXT = "allmende-cert-v1\n";
const DAY = 86_400;
const MAX_CERT_LIFETIME = 366 * DAY;
export const MAX_CERT_LIFETIME = 366 * DAY;
const MAX_LISTING_LIFETIME = 30 * DAY;
const MAX_CLOCK_SKEW = 10 * 60;
@@ -87,7 +87,7 @@ export interface Options {
const enc = new TextEncoder();
function hexBytes(s: unknown, bytes: number): Uint8Array | null {
export function hexBytes(s: unknown, bytes: number): Uint8Array | null {
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
return null;
}
@@ -108,21 +108,21 @@ export function leadingZeroBits(bytes: Uint8Array): number {
return n;
}
function without(o: object, key: string): Record<string, unknown> {
export function without(o: object, key: string): Record<string, unknown> {
const copy = { ...(o as Record<string, unknown>) };
delete copy[key];
return copy;
}
function isObject(v: unknown): v is Record<string, unknown> {
export function isObject(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
function safeInt(v: unknown): v is number {
export function safeInt(v: unknown): v is number {
return typeof v === "number" && Number.isSafeInteger(v);
}
function signedBy(
export function signedBy(
context: string,
signed: unknown,
sigHex: unknown,
+1
View File
@@ -12,6 +12,7 @@
<body>
<header class="top">
<a class="brand" href="#/">Allmende</a>
<nav id="nav" class="nav"></nav>
<span id="status" class="status"></span>
</header>
<main id="app"></main>
+24
View File
@@ -212,3 +212,27 @@ pre {
.detail-head { flex-direction: column; }
.kv { grid-template-columns: 1fr; }
}
/* Messages */
.nav { margin-left: auto; }
textarea {
width: 100%;
box-sizing: border-box;
padding: 8px 10px;
font: inherit;
color: var(--text);
background: var(--bg);
border: 1px solid var(--line);
border-radius: 8px;
resize: vertical;
}
textarea:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.compose .actions { margin-top: 8px; align-items: center; }
.small { font-size: 0.85rem; }
.pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; }
.thread, .convs { list-style: none; margin: 0 0 16px; padding: 0; display: grid; gap: 10px; }
.msg { max-width: 85%; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
.msg.out { justify-self: end; border-color: var(--accent); }
.msg .who { color: var(--muted); font-size: 0.85rem; margin-bottom: 4px; }
.grant { border: 2px solid var(--accent); border-radius: 8px; padding: 10px 12px; margin: 4px 0; }
input[readonly] { width: 100%; box-sizing: border-box; }
+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();
}