Files
allmende/web/src/verify.ts
T
nilsandClaude Sonnet 5.5 3b0351c774 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>
2026-11-17 19:44:59 +01:00

220 lines
6.1 KiB
TypeScript

// In-browser verification of a listing. The gateway that served it is not
// trusted: everything here is checked locally, mirroring Check in
// internal/listing and Cert.Check in internal/identity.
//
// What this cannot know: whether the owner has since revoked the device. Only
// nodes that saw the revocation know that, so freshness still rests on the
// gateway.
import { ed25519 } from "@noble/curves/ed25519.js";
import { sha256 } from "@noble/hashes/sha2.js";
import { canonicalize } from "./jcs.ts";
const LISTING_CONTEXT = "allmende-listing-v1\n";
export const CERT_CONTEXT = "allmende-cert-v1\n";
const DAY = 86_400;
export const MAX_CERT_LIFETIME = 366 * DAY;
const MAX_LISTING_LIFETIME = 30 * DAY;
const MAX_CLOCK_SKEW = 10 * 60;
export interface Cert {
v: number;
author: string;
device: string;
issued_at: number;
expires_at: number;
sig: string;
}
export interface Price {
amount_cents: number;
currency: string;
period: string;
}
export interface Listing {
v: number;
id: string;
author: string;
device: string;
seq: number;
created_at: number;
expires_at: number;
tombstone?: boolean;
kind?: string;
category?: string;
geohash: string;
price?: Price;
area_m2?: number;
rooms_x2?: number;
features?: string[];
title?: string;
description?: string;
delegate?: string;
pow: number;
cert: Cert;
sig: string;
}
export type CheckId =
| "format"
| "certificate"
| "binding"
| "validity"
| "signature"
| "pow";
export interface Check {
id: CheckId;
ok: boolean;
/** Short technical reason; shown as-is, not translated. */
info: string;
}
export interface Verdict {
ok: boolean;
checks: Check[];
powBits: number;
}
export interface Options {
/** Current time in unix seconds. */
now: number;
/** Proof-of-work bits the network requires. */
minPowBits: number;
}
const enc = new TextEncoder();
export function hexBytes(s: unknown, bytes: number): Uint8Array | null {
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
return null;
}
const out = new Uint8Array(bytes);
for (let i = 0; i < bytes; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
return out;
}
export function leadingZeroBits(bytes: Uint8Array): number {
let n = 0;
for (const b of bytes) {
if (b === 0) {
n += 8;
continue;
}
return n + Math.clz32(b) - 24;
}
return n;
}
export function without(o: object, key: string): Record<string, unknown> {
const copy = { ...(o as Record<string, unknown>) };
delete copy[key];
return copy;
}
export function isObject(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
export function safeInt(v: unknown): v is number {
return typeof v === "number" && Number.isSafeInteger(v);
}
export function signedBy(
context: string,
signed: unknown,
sigHex: unknown,
pubHex: unknown,
): boolean {
const sig = hexBytes(sigHex, 64);
const pub = hexBytes(pubHex, 32);
if (!sig || !pub) return false;
try {
const msg = enc.encode(context + canonicalize(signed));
return ed25519.verify(sig, msg, pub);
} catch {
return false;
}
}
/** Verifies a listing as received from a gateway. Never throws. */
export function verifyListing(input: unknown, opts: Options): Verdict {
const checks: Check[] = [];
const add = (id: CheckId, ok: boolean, info = "") => checks.push({ id, ok, info });
let powBits = 0;
const finish = (): Verdict => ({ ok: checks.every((c) => c.ok), checks, powBits });
// 1. Shape.
if (!isObject(input) || !isObject(input.cert)) {
add("format", false, "not a listing object");
return finish();
}
const l = input as unknown as Listing;
const c = l.cert;
const shapeOk =
l.v === 1 &&
hexBytes(l.id, 16) !== null &&
hexBytes(l.author, 32) !== null &&
hexBytes(l.device, 32) !== null &&
hexBytes(l.sig, 64) !== null &&
safeInt(l.seq) &&
safeInt(l.created_at) &&
safeInt(l.expires_at) &&
safeInt(l.pow) &&
typeof l.geohash === "string";
add("format", shapeOk, shapeOk ? "" : "malformed fields");
if (!shapeOk) return finish();
// 2. Certificate: signed by the identity key, sane lifetime.
const certShape =
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;
const certSig = certShape && signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
add(
"certificate",
certSig,
!certShape ? "malformed certificate" : certSig ? "" : "bad certificate signature",
);
if (!certSig) return finish();
// 3. The certificate must be for this author and this device.
const bound = c.author === l.author && c.device === l.device;
add("binding", bound, bound ? "" : "certificate is for a different identity or device");
// 4. Time windows.
const reasons: string[] = [];
if (!(c.issued_at <= l.created_at && l.created_at < c.expires_at)) {
reasons.push("created outside certificate validity");
}
if (opts.now >= c.expires_at) reasons.push("certificate expired");
if (l.expires_at <= l.created_at) reasons.push("expires before it was created");
if (l.expires_at - l.created_at > MAX_LISTING_LIFETIME) reasons.push("lifetime over 30 days");
if (l.created_at > opts.now + MAX_CLOCK_SKEW) reasons.push("created in the future");
if (l.expires_at <= opts.now) reasons.push("expired");
add("validity", reasons.length === 0, reasons.join("; "));
// 5. Device signature over the canonical bytes.
const unsigned = without(l, "sig");
const sigOk = signedBy(LISTING_CONTEXT, unsigned, l.sig, l.device);
add("signature", sigOk, sigOk ? "" : "signature does not match the content");
// 6. Proof-of-work over the same unsigned bytes.
try {
powBits = leadingZeroBits(sha256(enc.encode(canonicalize(unsigned))));
} catch {
powBits = 0;
}
const powOk = powBits >= opts.minPowBits;
add("pow", powOk, `${powBits} bits (network requires ${opts.minPowBits})`);
return finish();
}