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
+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,