Files
allmende/web/src/api.ts
T
nilsandClaude Sonnet 5.5 dfe35b422d Renew the device certificate from the browser, with the recovery phrase
Within the last 30 days the owner page offers it. The node signs a new certificate for the same device key (peer ID and listings stay), saves it, and signs again own listings that would outlive the old certificate. The phrase is used for one request and not kept; another identity's phrase and no-phrase identities are refused. Device.Current gives the certificate to sign with while a renewal happens.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-18 23:19:30 +01:00

142 lines
5.5 KiB
TypeScript

// Talks to the node that served this page. Everything it returns is untrusted
// 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;
author: string;
device: string;
regions: string[];
peers: number;
listings: number;
difficulty: number;
/** Proof-of-work bits a message needs; absent on nodes without messaging. */
message_difficulty?: number;
/** When this node's device certificate runs out, in unix seconds; absent on older nodes. */
cert_expires_at?: number;
/** Whether the owner can renew that certificate here (it needs the recovery phrase). */
can_renew?: boolean;
}
async function getJSON(url: string): Promise<unknown> {
const res = await fetch(url, { headers: { Accept: "application/json" } });
if (res.status === 404) return null;
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
export async function getStatus(): Promise<Status> {
return (await getJSON("/api/v1/status")) as Status;
}
/** Returns raw, unverified listing objects. */
export async function search(params: URLSearchParams): Promise<unknown[]> {
const data = await getJSON(`/api/v1/listings?${params}`);
if (!Array.isArray(data)) throw new Error("unexpected response");
return data;
}
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;
/** For a refused message: the proof-of-work, in bits, the listing's queue asks right now. */
readonly requiredBits?: number;
constructor(status: number, detail: string, requiredBits?: number) {
super(`${status} ${detail}`);
this.status = status;
this.detail = detail;
this.requiredBits = requiredBits;
}
}
/**
* The proof-of-work a message to this listing needs right now. It rises while
* the listing's queue fills, so a sender asks before mining. Null if the node
* cannot say (an older node): the caller then uses the node's usual difficulty.
*/
export async function getRequiredBits(author: string, id: string): Promise<number | null> {
try {
const res = await fetch(`/api/v1/messages/required?author=${author}&id=${id}`);
if (!res.ok) return null;
const { bits } = (await res.json()) as { bits?: unknown };
return typeof bits === "number" && Number.isInteger(bits) && bits > 0 && bits < 256 ? bits : null;
} catch {
return null;
}
}
/** 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;
let requiredBits: number | undefined;
try {
const body = (await res.json()) as { error?: unknown; required_bits?: unknown };
if (typeof body.error === "string") detail = body.error;
if (typeof body.required_bits === "number" && Number.isInteger(body.required_bits)) requiredBits = body.required_bits;
} catch {
// keep the status text
}
throw new HttpError(res.status, detail, requiredBits);
}
/** What one node makes of the abuse reports about a listing. */
export interface ReportSummary {
/** The node's own rules hide the listing from search. */
hidden: boolean;
/** Reports from reporters this node trusts, by category. */
trusted: Record<string, number>;
/** Reports from reporters it does not trust: shown, never counted. */
others: number;
/** Tips from visitors waiting for the operator. */
signals: number;
/** The operator's own report, if any. */
own?: string;
}
/** The reports about a listing, or null if this node cannot say. */
export async function getReportSummary(author: string, id: string): Promise<ReportSummary | null> {
try {
const res = await fetch(`/api/v1/reports?author=${author}&id=${id}`);
if (!res.ok) return null;
const s = (await res.json()) as Partial<ReportSummary>;
if (typeof s.hidden !== "boolean" || typeof s.trusted !== "object" || s.trusted === null) return null;
return { hidden: s.hidden, trusted: s.trusted, others: Number(s.others) || 0, signals: Number(s.signals) || 0, own: s.own };
} catch {
return null;
}
}
/** Tells the node's operator about a listing. Unsigned: backed only by proof-of-work (see sendTip). */
export async function postSignal(body: string): Promise<void> {
const res = await fetch("/api/v1/signals", { method: "POST", headers: { "Content-Type": "application/json" }, body });
if (res.ok) return;
let detail = res.statusText;
try {
const b = (await res.json()) as { error?: unknown };
if (typeof b.error === "string") detail = b.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;
}