// The owner's half of the API: everything here needs the admin token. // // The token reaches the page in the URL fragment of the login link the node // prints (#/login/), which a browser never sends to a server. It is kept // in sessionStorage only, so closing the tab signs the owner out, and it is only // ever sent to the node that served this page. import { HttpError, getListing } from "./api.ts"; import { MAX_LIFETIME_DAYS, draftFromListing, type Draft } from "./draft.ts"; import type { Listing } from "./verify.ts"; const TOKEN_KEY = "allmende.owner.token"; let memory: string | null = null; export function getToken(): string | null { try { return sessionStorage.getItem(TOKEN_KEY) ?? memory; } catch { return memory; } } export function setToken(token: string): void { memory = token; try { sessionStorage.setItem(TOKEN_KEY, token); } catch { // keep it in memory: the page still works, it just forgets on reload } } export function clearToken(): void { memory = null; try { sessionStorage.removeItem(TOKEN_KEY); } catch { // nothing stored } } /** The node refused the token (or none is set): the owner has to sign in again. */ export class Unauthorized extends Error { constructor() { super("unauthorized"); } } export interface Mine { id: string; title: string; kind?: string; price?: { amount_cents: number; currency: string; period?: string }; expires_at: number; threads: number; needs_reply: number; hidden: number; address_saved: boolean; } export interface Thread { listing: string; thread: string; messages: number; hidden: number; replied: boolean; first_at: number; last_at: number; last_dir: "in" | "out"; needs_reply: boolean; preview?: string; effort: number; grant_until?: number; } export interface OwnerMessage { hash: string; dir: "in" | "out"; hidden?: boolean; reason?: string; received_at: number; type: "text" | "grant"; n: number; sent_at: number; text?: string; address?: string; phone?: string; email?: string; note?: string; valid_until?: number; } export interface Address { address: string; phone?: string; email?: string; } export interface Reply { type: "text" | "grant"; text?: string; address?: string; phone?: string; email?: string; note?: string; valid_days?: number; } async function call(method: string, path: string, body?: unknown): Promise { const token = getToken(); if (!token) throw new Unauthorized(); const res = await fetch(path, { method, headers: { Authorization: `Bearer ${token}`, Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }), }, body: body === undefined ? undefined : JSON.stringify(body), }); if (res.status === 401) { clearToken(); throw new Unauthorized(); } if (res.status === 204) return null; let data: unknown = null; try { data = await res.json(); } catch { // no body } if (!res.ok) { const detail = typeof (data as { error?: unknown } | null)?.error === "string" ? (data as { error: string }).error : res.statusText; throw new HttpError(res.status, detail); } return data; } const e = encodeURIComponent; export async function getMine(): Promise { return (await call("GET", "/api/v1/mine")) as Mine[]; } export async function getThreads(listing: string): Promise { return (await call("GET", `/api/v1/inbox?listing=${e(listing)}`)) as Thread[]; } export async function getMessages(listing: string, thread: string): Promise { return (await call("GET", `/api/v1/inbox/${e(listing)}/${e(thread)}`)) as OwnerMessage[]; } export async function sendReply(listing: string, thread: string, r: Reply): Promise { await call("POST", `/api/v1/inbox/${e(listing)}/${e(thread)}`, r); } export async function deleteThread(listing: string, thread: string): Promise { await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`); } export async function blockThread(listing: string, thread: string): Promise { await call("PUT", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`); } export async function unblockThread(listing: string, thread: string): Promise { await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`); } export interface Blocked { listing: string; thread: string; blocked_at: number; } export async function getBlocked(): Promise { return (await call("GET", "/api/v1/blocked")) as Blocked[]; } /** A visitor's tip about a listing, as the operator sees it. */ export interface Tip { id: number; author: string; listing: string; title?: string; category: string; note: string; created_at: number; work: number; } export async function getTips(): Promise { return (await call("GET", "/api/v1/signals")) as Tip[]; } export async function dismissTips(author: string, listing: string): Promise { await call("DELETE", `/api/v1/signals/${e(author)}/${e(listing)}`); } /** Signs a report as this node's operator and shares it; the answer is the node's new view. */ export async function signReport(author: string, listing: string, category: string, note: string): Promise { await call("POST", "/api/v1/reports", { listing: { author, id: listing }, category, note }); } /** The saved address of a listing, or null if none is saved. */ export async function getAddress(listing: string): Promise
{ try { return (await call("GET", `/api/v1/listings/${e(listing)}/address`)) as Address; } catch (err) { if (err instanceof HttpError && err.status === 404) return null; throw err; } } export async function putAddress(listing: string, a: Address): Promise { await call("PUT", `/api/v1/listings/${e(listing)}/address`, a); } export async function deleteAddress(listing: string): Promise { await call("DELETE", `/api/v1/listings/${e(listing)}/address`); } /** Publishes a new listing. The node signs it and mines its proof-of-work, which takes a few seconds. */ /** Makes the node follow exactly these regions, now and after a restart; returns what it follows. */ export async function setRegions(regions: string[]): Promise { return ((await call("PUT", "/api/v1/regions", { regions })) as { regions: string[] }).regions; } /** * Renews the node's device certificate from the recovery phrase, which is * used for this one request. The device key stays, so nothing else changes. * Returns when the new certificate runs out, in unix seconds. */ export async function renewCertificate(phrase: string): Promise { return ((await call("PUT", "/api/v1/certificate", { phrase })) as { cert_expires_at: number }).cert_expires_at; } export async function createListing(d: Draft): Promise { return (await call("POST", "/api/v1/listings", d)) as Listing; } /** Replaces one of your listings (a new version of it). The region cannot change. */ export async function updateListing(id: string, d: Draft): Promise { return (await call("PUT", `/api/v1/listings/${e(id)}`, d)) as Listing; } /** Withdraws a listing: publishes a deletion marker that outlives every older copy. */ export async function deleteListing(id: string): Promise { await call("DELETE", `/api/v1/listings/${e(id)}`); } /** Your own listing as the node has it, or null if it is gone. */ export async function getOwnListing(author: string, id: string): Promise { return (await getListing(author, id)) as Listing | null; } /** Publishes the listing again for a fresh term, otherwise unchanged. */ export async function renewListing(author: string, id: string, days = MAX_LIFETIME_DAYS): Promise { const l = await getOwnListing(author, id); if (!l || l.tombstone) throw new HttpError(404, "no such listing of yours"); return updateListing(id, draftFromListing(l, days)); }