Add owner inbox UI with address release

Web: "My listings" (listings, requests of a listing, conversation) in
three panes on wide screens and one at a time on phones, and a sheet or
dialog to release the exact address. Sign-in uses a link printed by
`node run` (token in the URL fragment, kept in sessionStorage only).

API: GET /api/v1/mine (own listings with request counts and whether an
address is saved); inbox rows gain last_dir, needs_reply, preview,
effort and grant_until, and can be filtered by listing.

Docs: PROTOCOL.md and README describe the owner UI and login.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 20:02:51 +01:00
co-authored by Claude Sonnet 5.5
parent 3b0351c774
commit 8edae3ae56
17 changed files with 2400 additions and 49 deletions
+9
View File
@@ -14,6 +14,15 @@ export function date(unix: number): string {
return new Date(unix * 1000).toLocaleDateString(lang, { dateStyle: "medium" });
}
/** A time of day for today's events, otherwise the day. */
export function when(unix: number): string {
const d = new Date(unix * 1000);
if (d.toDateString() === new Date(Date.now()).toDateString()) {
return d.toLocaleTimeString(lang, { hour: "2-digit", minute: "2-digit" });
}
return d.toLocaleDateString(lang, { day: "numeric", month: "short" });
}
export function price(l: Listing): string {
if (!l.price) return "";
const base = money(l.price.amount_cents);
+146
View File
@@ -106,6 +106,79 @@ const de = {
"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.",
"nav.owner": "Meine Anzeigen",
"own.loginTitle": "Anmelden als Anbieter",
"own.loginHelp":
"Beim Start gibt dein Knoten im Terminal einen Anmelde-Link aus. Öffne ihn hier, oder füge den Token (Datei admin.token im Datenordner) ein. Er bleibt nur in diesem Tab gespeichert.",
"own.token": "Token",
"own.login": "Anmelden",
"own.loginBad": "Der Knoten hat den Token abgelehnt.",
"own.logout": "Abmelden",
"own.listings": "Deine Anzeigen",
"own.none": "Dein Knoten hat keine aktiven Anzeigen.",
"own.perMonth": "/ Monat",
"own.needReply": "{n} brauchen eine Antwort",
"own.noRequests": "Keine Anfragen",
"own.allAnswered": "Alle beantwortet",
"own.addressSaved": "Adresse gespeichert",
"own.noAddress": "Keine Adresse gespeichert",
"own.backListings": "← Anzeigen",
"own.backRequests": "← Anfragen",
"own.pickListing": "Wähle links eine Anzeige.",
"own.pickRequest": "Wähle eine Anfrage.",
"own.addrTitle": "Adresse auf deinem Knoten",
"own.addrHelp": "Wird nie veröffentlicht. Nur Personen, denen du sie freigibst, erhalten sie.",
"own.addrNone": "Noch keine Adresse gespeichert. Ohne sie kannst du keine Adresse freigeben.",
"own.addrChange": "Ändern",
"own.addrAdd": "Adresse hinzufügen",
"own.addrSave": "Speichern",
"own.addrRemove": "Entfernen",
"own.addrCancel": "Abbrechen",
"own.fAddress": "Adresse",
"own.fPhone": "Telefon (optional)",
"own.fEmail": "E-Mail (optional)",
"own.requests": "Anfragen",
"own.request": "Anfrage #{id}",
"own.filterAll": "Alle {n}",
"own.filterReply": "Braucht Antwort {n}",
"own.filterHidden": "Link versteckt {n}",
"own.noMatch": "Keine Anfragen in dieser Ansicht.",
"own.stReply": "Braucht Antwort",
"own.stReplied": "Beantwortet",
"own.stHidden": "Link versteckt",
"own.stGrant": "Adresse bis {date}",
"own.stGrantEnded": "Adresse abgelaufen",
"own.effort": "Aufwand {n} Bit",
"own.hiddenPreview": "Ausgeblendet: enthält einen Link",
"own.limitNote":
"Pro Anzeige zeigt dein Knoten nur eine begrenzte Zahl neuer Anfragen am Tag; der Rest wartet, die mit dem größten Aufwand zuerst.",
"own.buyer": "Interessent",
"own.you": "Du",
"own.anon": "Anonym, Ende-zu-Ende-verschlüsselt",
"own.first":
"Erste Nachricht dieser Person. Bis du antwortest, darf sie nur kurzen Text ohne Links schicken. Alles wird als reiner Text angezeigt, nie als Link.",
"own.hiddenMsg": "Ausgeblendet: Eine erste Nachricht muss kurz sein und darf keine Links enthalten.",
"own.grantSent": "Adresse freigegeben bis {date}",
"own.reply": "Antwort",
"own.send": "Senden",
"own.sending": "Wird gesendet …",
"own.release": "Adresse freigeben",
"own.delete": "Unterhaltung löschen",
"own.deleteSure": "Wirklich löschen? Sie wird von deinem Knoten entfernt.",
"own.deleteYes": "Ja, löschen",
"own.sheetTitle": "Adresse freigeben",
"own.sheetHelp":
"Eine signierte Nachricht, nur für diese Person sichtbar. Ihr Bildschirm blendet sie nach dem Datum aus. Sie könnte sie trotzdem kopiert haben.",
"own.fNote": "Hinweis an die Person",
"own.fValid": "Sichtbar für",
"own.days": "{n} Tage",
"own.day": "1 Tag",
"own.remember": "Diese Adresse für die Anzeige speichern",
"own.sendAddress": "Adresse senden",
"own.close": "Schließen",
"own.needAddress": "Bitte gib eine Adresse ein.",
"own.loadError": "Konnte nicht geladen werden.",
"own.err": "Fehlgeschlagen: {detail}",
"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.",
@@ -230,6 +303,79 @@ const en: Record<keyof typeof de, string> = {
"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.",
"nav.owner": "My listings",
"own.loginTitle": "Sign in as owner",
"own.loginHelp":
"When it starts, your node prints a sign-in link in the terminal. Open it here, or paste the token (the file admin.token in the data folder). It is kept in this tab only.",
"own.token": "Token",
"own.login": "Sign in",
"own.loginBad": "The node rejected the token.",
"own.logout": "Sign out",
"own.listings": "Your listings",
"own.none": "Your node has no active listings.",
"own.perMonth": "/ month",
"own.needReply": "{n} need a reply",
"own.noRequests": "No requests",
"own.allAnswered": "All answered",
"own.addressSaved": "Address saved",
"own.noAddress": "No address saved",
"own.backListings": "← Listings",
"own.backRequests": "← Requests",
"own.pickListing": "Choose a listing on the left.",
"own.pickRequest": "Choose a request.",
"own.addrTitle": "Address on your node",
"own.addrHelp": "Never published. Only people you release it to receive it.",
"own.addrNone": "No address saved yet. Without one you cannot release an address.",
"own.addrChange": "Change",
"own.addrAdd": "Add address",
"own.addrSave": "Save",
"own.addrRemove": "Remove",
"own.addrCancel": "Cancel",
"own.fAddress": "Address",
"own.fPhone": "Phone (optional)",
"own.fEmail": "Email (optional)",
"own.requests": "Requests",
"own.request": "Request #{id}",
"own.filterAll": "All {n}",
"own.filterReply": "Needs reply {n}",
"own.filterHidden": "Link hidden {n}",
"own.noMatch": "No requests in this view.",
"own.stReply": "Needs reply",
"own.stReplied": "Replied",
"own.stHidden": "Link hidden",
"own.stGrant": "Address until {date}",
"own.stGrantEnded": "Address expired",
"own.effort": "Effort {n} bit",
"own.hiddenPreview": "Hidden: contains a link",
"own.limitNote":
"Your node shows only a limited number of new requests per listing per day; the rest wait, strongest effort first.",
"own.buyer": "Buyer",
"own.you": "You",
"own.anon": "Anonymous, end-to-end encrypted",
"own.first":
"First message from this person. Until you reply they can send short text only, no links. Everything is shown as plain text, never as a link.",
"own.hiddenMsg": "Hidden: a first message must be short and contain no links.",
"own.grantSent": "Address released until {date}",
"own.reply": "Reply",
"own.send": "Send",
"own.sending": "Sending …",
"own.release": "Release address",
"own.delete": "Delete conversation",
"own.deleteSure": "Really delete? It is removed from your node.",
"own.deleteYes": "Yes, delete",
"own.sheetTitle": "Release address",
"own.sheetHelp":
"A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.",
"own.fNote": "Note to the buyer",
"own.fValid": "Visible for",
"own.days": "{n} days",
"own.day": "1 day",
"own.remember": "Save this address for the listing",
"own.sendAddress": "Send address",
"own.close": "Close",
"own.needAddress": "Please enter an address.",
"own.loadError": "Could not be loaded.",
"own.err": "Failed: {detail}",
"verify.title": "Checked in your browser",
"verify.intro":
"This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
+23 -2
View File
@@ -4,6 +4,8 @@ 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 { showOwner } from "./owner.ts";
import { getToken, setToken } from "./ownerApi.ts";
import { state, verifyOpts } from "./state.ts";
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
@@ -324,6 +326,16 @@ async function showDetail(author: string, id: string): Promise<void> {
// --- boot -----------------------------------------------------------------
/** "My messages" is for buyers; "My listings" only appears once the owner has signed in. */
function renderNav(): void {
const nav = document.getElementById("nav")!;
clear(nav);
append(nav, [
h("a", { href: "#/messages" }, t("nav.messages")),
getToken() && h("a", { href: "#/mine" }, t("nav.owner")),
]);
}
function route(): void {
state.generation++;
const hash = location.hash.replace(/^#/, "") || "/";
@@ -332,17 +344,26 @@ function route(): void {
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]!);
const login = /^\/login\/([0-9a-f]{16,128})$/.exec(path);
const own = /^\/mine(?:\/([0-9a-f]{32})(?:\/([0-9a-f]{64}))?)?$/.exec(path);
document.body.classList.remove("wide");
if (login) {
// The token came in the URL fragment: keep it for this tab and take it out of the address bar.
setToken(login[1]!);
history.replaceState(null, "", location.pathname + location.search + "#/mine");
void showOwner();
} else 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 if (own) void showOwner(own[1], own[2]);
else showSearch(params);
renderNav();
window.scrollTo(0, 0);
}
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 {
state.node = await getStatus();
statusEl.textContent = t("status.line", {
+518
View File
@@ -0,0 +1,518 @@
// The owner's inbox: your listings, the requests on one of them, and a
// conversation, with a sheet for releasing the exact address.
//
// On a wide screen the three panes sit side by side; on a phone only the
// deepest one shows and back links lead out. Everything here talks to the
// token-protected API of the node that served the page. Buyer text is shown
// with textContent only, never as links.
import { HttpError } from "./api.ts";
import { append, clear, h } from "./dom.ts";
import { date, price, when } from "./format.ts";
import { t, type Key } from "./i18n.ts";
import * as o from "./ownerApi.ts";
import { nowSeconds, state } from "./state.ts";
import type { Listing } from "./verify.ts";
const REFRESH_MS = 30_000;
const VALID_DAYS = [1, 3, 7, 14, 30];
const DEFAULT_DAYS = 7;
const app = () => document.getElementById("app")!;
type Filter = "all" | "reply" | "hidden";
/** The four characters that name a request in the lists. */
const shortId = (thread: string) => thread.slice(-4);
function explain(e: unknown): string {
return t("own.err", { detail: e instanceof HttpError ? e.detail : e instanceof Error ? e.message : "?" });
}
// --- sign in ---------------------------------------------------------------------
export function renderLogin(rejected: boolean): void {
const root = app();
document.body.classList.remove("wide");
clear(root);
const input = h("input", { type: "password", name: "token", autocomplete: "off", spellcheck: "false", "aria-label": t("own.token"), required: true });
append(root, [
h(
"section",
{ class: "panel" },
h("h1", null, t("own.loginTitle")),
h("p", { class: "muted" }, t("own.loginHelp")),
rejected && h("p", { class: "error", role: "alert" }, t("own.loginBad")),
h(
"form",
{
class: "stack",
onsubmit: (ev) => {
ev.preventDefault();
const v = input.value.trim();
if (!v) return;
o.setToken(v);
void showOwner();
},
},
h("label", null, t("own.token"), input),
h("div", { class: "actions" }, h("button", { type: "submit", class: "btn primary" }, t("own.login"))),
),
),
]);
}
// --- the view -------------------------------------------------------------------------
export async function showOwner(listingId?: string, thread?: string): Promise<void> {
const gen = state.generation;
if (!o.getToken()) {
renderLogin(false);
return;
}
const root = app();
document.body.classList.add("wide"); // three panes need more room than the search pages
clear(root);
const depth = thread ? 3 : listingId ? 2 : 1;
let mine: o.Mine[] = [];
let threads: o.Thread[] = [];
let msgs: o.OwnerMessage[] = [];
let filter: Filter = "all";
let loaded = false;
const notice = h("p", { class: "error", role: "alert" });
// pane 1: listings
const listingsBox = h("div", { class: "olist" });
const listingsPane = h(
"section",
{ class: "pane pane-listings" },
h("h2", { class: "pane-title" }, t("own.listings")),
listingsBox,
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))),
);
// pane 2: requests of the selected listing
const reqTitle = h("h2", { class: "pane-title" });
const chips = h("div", { class: "chips-row" });
const reqBox = h("div", { class: "olist" });
const addr = listingId ? addressCard(listingId, () => void refresh()) : null;
const requestsPane = h("section", { class: "pane pane-requests" });
append(
requestsPane,
listingId
? [
h("a", { class: "back narrow-only", href: "#/mine" }, t("own.backListings")),
reqTitle,
addr!.root,
chips,
reqBox,
h("p", { class: "muted small" }, t("own.limitNote")),
]
: [h("p", { class: "muted pick" }, t("own.pickListing"))],
);
// pane 3: one conversation
const msgBox = h("div", { class: "thread", "aria-live": "polite" });
const threadHead = h("h2", { class: "pane-title" });
const firstNote = h("p", { class: "note warn" }, t("own.first"));
const threadPane = h("section", { class: "pane pane-thread" });
if (listingId && thread) {
append(threadPane, [
h("a", { class: "back narrow-only", href: `#/mine/${listingId}` }, t("own.backRequests")),
threadHead,
h("p", { class: "muted small" }, t("own.anon")),
msgBox,
firstNote,
composer(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())),
deleteControl(listingId, thread),
]);
} else {
threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : ""));
}
append(root, [notice, h("div", { class: `owner depth-${depth}` }, listingsPane, requestsPane, threadPane)]);
// --- rendering from data
const kindLabel = (k?: string) => (k === "rent" || k === "sale" ? t(`kind.${k}` as Key) : (k ?? ""));
function renderListings(): void {
clear(listingsBox);
if (loaded && mine.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
for (const m of mine) {
const sub = [kindLabel(m.kind), m.price ? price({ price: m.price } as unknown as Listing) : ""].filter(Boolean).join(" · ");
listingsBox.append(
h(
"a",
{ class: `ocard${m.id === listingId ? " selected" : ""}`, href: `#/mine/${m.id}`, "aria-current": m.id === listingId ? "page" : undefined },
h("b", null, m.title || m.id.slice(0, 8)),
sub && h("span", { class: "muted small" }, sub),
h(
"span",
{ class: "badges" },
m.needs_reply > 0
? h("span", { class: "badge warn" }, t("own.needReply", { n: m.needs_reply }))
: m.threads === 0
? h("span", { class: "badge muted" }, t("own.noRequests"))
: h("span", { class: "badge ok" }, t("own.allAnswered")),
m.address_saved
? h("span", { class: "badge ok" }, t("own.addressSaved"))
: h("span", { class: "badge warn" }, t("own.noAddress")),
),
),
);
}
}
function status(th: o.Thread): HTMLElement[] {
const now = nowSeconds();
const out: HTMLElement[] = [];
const allHidden = th.hidden > 0 && th.hidden === th.messages;
if (th.needs_reply) out.push(h("span", { class: "badge warn" }, t("own.stReply")));
if (th.hidden > 0) out.push(h("span", { class: "badge bad" }, t("own.stHidden")));
if (th.grant_until) {
out.push(
th.grant_until > now
? h("span", { class: "badge ok" }, t("own.stGrant", { date: date(th.grant_until) }))
: h("span", { class: "badge muted" }, t("own.stGrantEnded")),
);
} else if (th.replied && !th.needs_reply) {
out.push(h("span", { class: "badge muted" }, t("own.stReplied")));
}
if (!out.length && !allHidden) out.push(h("span", { class: "badge muted" }, t("own.stReplied")));
return out;
}
function preview(th: o.Thread): string {
if (th.preview) return th.preview;
if (th.last_dir === "in") return t("own.hiddenPreview");
return th.grant_until ? t("own.grantSent", { date: date(th.grant_until) }) : "";
}
function renderRequests(): void {
const m = mine.find((x) => x.id === listingId);
reqTitle.textContent = m?.title ?? "";
const counts = { all: threads.length, reply: threads.filter((x) => x.needs_reply).length, hidden: threads.filter((x) => x.hidden > 0).length };
clear(chips);
for (const [f, key] of [["all", "own.filterAll"], ["reply", "own.filterReply"], ["hidden", "own.filterHidden"]] as const) {
chips.append(
h("button", { type: "button", class: `chip${filter === f ? " on" : ""}`, "aria-pressed": filter === f ? "true" : "false", onclick: () => { filter = f; renderRequests(); } }, t(key, { n: counts[f] })),
);
}
const shown = threads.filter((x) => filter === "all" || (filter === "reply" ? x.needs_reply : x.hidden > 0));
clear(reqBox);
if (loaded && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch")));
for (const th of shown) {
reqBox.append(
h(
"a",
{ class: `ocard${th.thread === thread ? " selected" : ""}`, href: `#/mine/${th.listing}/${th.thread}`, "aria-current": th.thread === thread ? "page" : undefined },
h("span", { class: "row" }, h("b", null, t("own.request", { id: shortId(th.thread) })), h("span", { class: "muted small" }, when(th.last_at))),
h("span", { class: th.preview ? "clip" : "clip muted" }, preview(th)),
h("span", { class: "badges" }, ...status(th), h("span", { class: "muted small" }, t("own.effort", { n: th.effort }))),
),
);
}
}
function renderThread(): void {
if (!thread) return;
threadHead.textContent = t("own.request", { id: shortId(thread) });
clear(msgBox);
for (const m of msgs) msgBox.append(bubble(m));
firstNote.hidden = msgs.some((m) => m.dir === "out");
}
function renderAll(): void {
renderListings();
if (listingId) renderRequests();
renderThread();
}
// --- data
function logout(): void {
o.clearToken();
location.hash = "#/";
}
async function refresh(): Promise<void> {
try {
mine = await o.getMine();
if (listingId) threads = await o.getThreads(listingId);
if (listingId && thread) {
try {
msgs = await o.getMessages(listingId, thread);
} catch (e) {
if (e instanceof HttpError && e.status === 404) {
if (gen === state.generation) location.hash = `#/mine/${listingId}`;
return;
}
throw e;
}
}
} catch (e) {
if (gen !== state.generation) return;
if (e instanceof o.Unauthorized) renderLogin(true);
else notice.textContent = t("own.loadError");
return;
}
if (gen !== state.generation) return;
notice.textContent = "";
loaded = true;
renderAll();
}
renderListings();
await refresh();
const tick = () => {
setTimeout(() => {
if (gen !== state.generation) return;
void refresh().then(tick);
}, REFRESH_MS);
};
tick();
}
// --- pieces ------------------------------------------------------------------------------
function bubble(m: o.OwnerMessage): HTMLElement {
const mine = m.dir === "out";
const who = mine ? t("own.you") : t("own.buyer");
const head = h("div", { class: "who" }, who, " · ", when(m.sent_at));
if (m.hidden) {
return h("div", { class: "msg in" }, head, h("p", { class: "pre muted" }, t("own.hiddenMsg")));
}
if (m.type === "grant") {
const row = (label: Key, v?: string) => (v ? [h("dt", null, t(label)), h("dd", { class: "pre" }, v)] : []);
return h(
"div",
{ class: "msg out" },
head,
h(
"div",
{ class: "grant" },
h("strong", null, t("own.grantSent", { date: date(m.valid_until ?? 0) })),
h("dl", { class: "kv" }, ...row("own.fAddress", m.address), ...row("own.fPhone", m.phone), ...row("own.fEmail", m.email), ...row("own.fNote", m.note)),
),
);
}
return h("div", { class: `msg ${mine ? "out" : "in"}` }, head, h("p", { class: "pre" }, m.text ?? ""));
}
function composer(listingId: string, thread: string, done: () => void, release: (opener: HTMLElement) => void): HTMLElement {
const area = h("textarea", { rows: 3, "aria-label": t("own.reply"), name: "reply" });
const problem = h("p", { class: "error", role: "alert" });
const send = h("button", { type: "submit", class: "btn primary" }, t("own.send"));
const rel = h("button", { type: "button", class: "btn", onclick: () => release(rel) }, t("own.release"));
return h(
"form",
{
class: "compose",
onsubmit: (ev) => {
ev.preventDefault();
const text = area.value.trim();
if (!text) return;
void (async () => {
problem.textContent = "";
send.disabled = true;
send.textContent = t("own.sending");
try {
await o.sendReply(listingId, thread, { type: "text", text });
area.value = "";
done();
} catch (e) {
problem.textContent = e instanceof o.Unauthorized ? t("own.loginBad") : explain(e);
} finally {
send.disabled = false;
send.textContent = t("own.send");
}
})();
},
},
area,
h("div", { class: "actions" }, send, rel),
problem,
);
}
function deleteControl(listingId: string, thread: string): HTMLElement {
const slot = h("p", null);
const ask = () => {
clear(slot);
append(slot, [
t("own.deleteSure"),
" ",
h("button", { type: "button", class: "btn", onclick: () => void o.deleteThread(listingId, thread).then(() => (location.hash = `#/mine/${listingId}`)) }, t("own.deleteYes")),
]);
};
slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.delete")));
return slot;
}
/** The listing's saved address, shown and editable. It lives on this node only. */
function addressCard(listingId: string, changed: () => void): { root: HTMLElement } {
const root = h("div", { class: "panel addr" });
let saved: o.Address | null = null;
function show(): void {
clear(root);
append(root, [
h("strong", null, t("own.addrTitle")),
saved
? h("p", { class: "pre" }, [saved.address, saved.phone, saved.email].filter(Boolean).join("\n"))
: h("p", { class: "muted" }, t("own.addrNone")),
h("p", { class: "muted small" }, t("own.addrHelp")),
h("button", { type: "button", class: "btn", onclick: edit }, saved ? t("own.addrChange") : t("own.addrAdd")),
]);
}
function edit(): void {
const a = h("input", { name: "address", value: saved?.address ?? "", maxlength: 300, required: true });
const p = h("input", { name: "phone", value: saved?.phone ?? "", maxlength: 40 });
const e = h("input", { name: "email", value: saved?.email ?? "", maxlength: 120 });
const problem = h("p", { class: "error", role: "alert" });
clear(root);
append(root, [
h(
"form",
{
class: "stack",
onsubmit: (ev) => {
ev.preventDefault();
void (async () => {
try {
const next: o.Address = { address: a.value.trim(), phone: p.value.trim() || undefined, email: e.value.trim() || undefined };
if (!next.address) {
problem.textContent = t("own.needAddress");
return;
}
await o.putAddress(listingId, next);
saved = next;
show();
changed();
} catch (err) {
problem.textContent = explain(err);
}
})();
},
},
h("label", null, t("own.fAddress"), a),
h("label", null, t("own.fPhone"), p),
h("label", null, t("own.fEmail"), e),
problem,
h(
"div",
{ class: "actions" },
h("button", { type: "submit", class: "btn primary" }, t("own.addrSave")),
h("button", { type: "button", class: "btn", onclick: show }, t("own.addrCancel")),
saved &&
h(
"button",
{
type: "button",
class: "btn",
onclick: () => void o.deleteAddress(listingId).then(() => { saved = null; show(); changed(); }).catch((err) => { problem.textContent = explain(err); }),
},
t("own.addrRemove"),
),
),
),
]);
a.focus();
}
void o.getAddress(listingId).then((a) => { saved = a; show(); }, () => show());
show();
return { root };
}
/** A bottom sheet on a phone, a dialog on a wide screen: releases the exact address to one person. */
function openSheet(listingId: string, thread: string, opener: HTMLElement, done: () => void): void {
const host = app();
const close = () => {
backdrop.remove();
opener.focus();
};
const address = h("input", { name: "address", maxlength: 300, required: true });
const phone = h("input", { name: "phone", maxlength: 40 });
const note = h("textarea", { name: "note", rows: 2, maxlength: 1000 });
const valid = h("select", { name: "valid" }, ...VALID_DAYS.map((d) => h("option", { value: String(d), selected: d === DEFAULT_DAYS }, d === 1 ? t("own.day") : t("own.days", { n: d }))));
const remember = h("input", { type: "checkbox", name: "remember" });
const rememberRow = h("label", { class: "check" }, remember, " ", t("own.remember"));
const problem = h("p", { class: "error", role: "alert" });
const send = h("button", { type: "submit", class: "btn primary" }, t("own.sendAddress"));
let saved: o.Address | null = null;
const form = h(
"form",
{
class: "stack",
onsubmit: (ev) => {
ev.preventDefault();
void (async () => {
problem.textContent = "";
const a = address.value.trim();
if (!a) {
problem.textContent = t("own.needAddress");
return;
}
send.disabled = true;
send.textContent = t("own.sending");
try {
if (remember.checked && (!saved || saved.address !== a)) {
await o.putAddress(listingId, { address: a, phone: phone.value.trim() || undefined, email: saved?.email });
}
await o.sendReply(listingId, thread, {
type: "grant",
address: a,
phone: phone.value.trim() || undefined,
note: note.value.trim() || undefined,
valid_days: Number(valid.value),
});
close();
done();
} catch (e) {
problem.textContent = explain(e);
send.disabled = false;
send.textContent = t("own.sendAddress");
}
})();
},
},
h("label", null, t("own.fAddress"), address),
h("label", null, t("own.fPhone"), phone),
h("label", null, t("own.fNote"), note),
h("label", null, t("own.fValid"), valid),
rememberRow,
problem,
h("div", { class: "actions" }, send),
);
const closeBtn = h("button", { type: "button", class: "btn close", "aria-label": t("own.close"), onclick: close }, "×");
const backdrop = h(
"div",
{
class: "backdrop",
onclick: (ev) => { if (ev.target === backdrop) close(); },
onkeydown: (ev) => { if ((ev as KeyboardEvent).key === "Escape") close(); },
},
h("div", { class: "sheet", role: "dialog", "aria-modal": "true", "aria-label": t("own.sheetTitle") }, h("div", { class: "row" }, h("h2", null, t("own.sheetTitle")), closeBtn), h("p", { class: "muted small" }, t("own.sheetHelp")), form),
);
host.append(backdrop);
address.focus();
void o.getAddress(listingId).then(
(a) => {
saved = a;
if (a) {
if (!address.value) address.value = a.address;
if (!phone.value && a.phone) phone.value = a.phone;
} else {
remember.checked = true; // nothing saved yet: offer to keep what is typed
}
},
() => { remember.checked = true; },
);
}
+173
View File
@@ -0,0 +1,173 @@
// 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/<token>), 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 } from "./api.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;
note?: string;
valid_days?: number;
}
async function call(method: string, path: string, body?: unknown): Promise<unknown> {
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<Mine[]> {
return (await call("GET", "/api/v1/mine")) as Mine[];
}
export async function getThreads(listing: string): Promise<Thread[]> {
return (await call("GET", `/api/v1/inbox?listing=${e(listing)}`)) as Thread[];
}
export async function getMessages(listing: string, thread: string): Promise<OwnerMessage[]> {
return (await call("GET", `/api/v1/inbox/${e(listing)}/${e(thread)}`)) as OwnerMessage[];
}
export async function sendReply(listing: string, thread: string, r: Reply): Promise<void> {
await call("POST", `/api/v1/inbox/${e(listing)}/${e(thread)}`, r);
}
export async function deleteThread(listing: string, thread: string): Promise<void> {
await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
}
/** The saved address of a listing, or null if none is saved. */
export async function getAddress(listing: string): Promise<Address | null> {
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<void> {
await call("PUT", `/api/v1/listings/${e(listing)}/address`, a);
}
export async function deleteAddress(listing: string): Promise<void> {
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
}