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:
+142
-7
@@ -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 --------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user