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
+2 -2
View File
@@ -20,8 +20,8 @@ pre-built and embedded; Node.js is only needed to change it
Buyers can write to an owner straight from a listing, without an account.
Messages are end-to-end encrypted in the browser and relayed through the
network, so a node only ever sees ciphertext. The owner reads and answers
through the token-protected API (`GET /api/v1/inbox`, see the protocol doc) and
can release the exact address as a signed message; an owner UI is not built yet.
in the browser (`node run` prints a sign-in link; open it to get "My listings")
and can release the exact address as a signed message.
A second node on the same network finds this one automatically (mDNS); across
networks, pass `--bootstrap /ip4/<addr>/tcp/<port>/p2p/<peer id>`.
+17
View File
@@ -0,0 +1,17 @@
package main
import "testing"
func TestLoginURL(t *testing.T) {
for addr, want := range map[string]string{
"127.0.0.1:8080": "http://127.0.0.1:8080/#/login/tok",
"0.0.0.0:8080": "http://127.0.0.1:8080/#/login/tok", // a wildcard cannot be opened
"[::]:9000": "http://127.0.0.1:9000/#/login/tok",
"[::1]:8080": "http://[::1]:8080/#/login/tok",
"192.0.2.7:80": "http://192.0.2.7:80/#/login/tok",
} {
if got := loginURL(addr, "tok"); got != want {
t.Errorf("loginURL(%q) = %q, want %q", addr, got, want)
}
}
}
+21
View File
@@ -136,6 +136,13 @@ func cmdRun(args []string) error {
log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public")
}
if token != "" {
// Printed to the terminal, not logged: the token must not end up in a
// log file. It sits in the URL fragment, which a browser never sends to
// a server; the page moves it into sessionStorage and removes it.
fmt.Fprintf(os.Stderr, "\nOwner login (answer your inbox in the browser):\n %s\n\n", loginURL(ln.Addr().String(), token))
}
go announce(ctx, log, node, st, dev.Cert.Author)
<-ctx.Done()
@@ -176,3 +183,17 @@ func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.S
timer.Reset(announceInterval)
}
}
// loginURL is the link that signs the owner in to the web UI.
func loginURL(listenAddr, token string) string {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return "http://" + listenAddr + "/#/login/" + token
}
// A wildcard address (0.0.0.0, ::) is not something a browser can open.
if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() {
host = "127.0.0.1"
}
// JoinHostPort brackets IPv6 addresses.
return "http://" + net.JoinHostPort(host, port) + "/#/login/" + token
}
+20 -3
View File
@@ -307,8 +307,24 @@ text rules below are enforced by endpoints.
`#/c/<author>/<id>/<thread secret>` (the secret stays in the URL fragment,
which is never sent to a server) that polls every 20 s, shows only verified
owner replies and counts the rest as rejected; `#/messages` lists the
conversations stored in this browser. There is **no owner UI yet**; the owner
uses the admin API.
conversations stored in this browser.
- **Owner UI** (`#/mine`): your listings (requests needing a reply, whether an
address is saved), the requests of one listing (status, preview, effort,
filters), a conversation, and a sheet to **release the address** (prefilled
from the saved one; address, phone, a free-text note, validity 1 to 30 days).
Three panes side by side on a wide screen, one at a time on a phone. It uses
the admin API above plus `GET /api/v1/mine` (own listings with request counts
and `address_saved`) and `GET /api/v1/inbox?listing=<id>`, whose rows also
carry `last_dir`, `needs_reply`, a text `preview` (empty for hidden messages),
`effort` (proof-of-work bits of the first message) and `grant_until`.
- **Owner login.** The page itself never contains the admin token (every node
serves the same page, including public gateways). `node run` prints a link
`http://127.0.0.1:8080/#/login/<token>` to the terminal, not to its log. The
token is in the URL fragment, which a browser never sends to a server; the
page moves it into `sessionStorage` (so closing the tab signs out), removes it
from the address bar and sends it only to the node that served the page. A
paste field is the fallback; a token the node refuses (for example after
`recover`) is forgotten.
### Limits of this design
@@ -338,6 +354,7 @@ token written to `admin.token` at init, mode 0600).
| `POST /api/v1/listings` | token | publish a draft; the node adds identity, time, PoW and signature |
| `PUT /api/v1/listings/{id}` | token | replace own listing (`seq + 1`); the region cannot change |
| `DELETE /api/v1/listings/{id}` | token | publish a tombstone |
| `GET /api/v1/mine` | token | your live listings with request counts and whether an address is saved (messaging, see above) |
Reads send `Access-Control-Allow-Origin: *` (the data is public). Writes are
not cross-origin. Images are not supported yet. `status` also reports the
@@ -379,7 +396,7 @@ Proof-of-work per listing and per revocation, plus subscribable blocklists
## Open
An owner UI for the inbox, abuse reporting for messages, reciprocity rules, anti-
Abuse reporting for messages, reciprocity rules, anti-
discrimination (AGG) content rules, blocklists, peer scoring and rate limits,
incremental sync and anti-entropy, DHT discovery, UI publishing, image hosting,
recovering listings onto a fresh machine with an empty database, a helper to
+1
View File
@@ -78,6 +78,7 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("GET /api/v1/messages", s.getMailbox)
// ...and the owner's inbox and private address, behind the admin token.
if cfg.Inbox != nil {
mux.HandleFunc("GET /api/v1/mine", s.admin(s.mine))
mux.HandleFunc("GET /api/v1/inbox", s.admin(s.listThreads))
mux.HandleFunc("GET /api/v1/inbox/{id}/{thread}", s.admin(s.getThread))
mux.HandleFunc("POST /api/v1/inbox/{id}/{thread}", s.admin(s.reply))
+133 -4
View File
@@ -146,6 +146,84 @@ type threadView struct {
Replied bool `json:"replied"`
FirstAt int64 `json:"first_at"`
LastAt int64 `json:"last_at"`
// LastDir is who wrote last: "in" (the buyer) or "out" (the owner).
LastDir string `json:"last_dir"`
// NeedsReply: the buyer wrote last and the message is readable.
NeedsReply bool `json:"needs_reply"`
// Preview is the start of the latest message (empty when it is hidden).
Preview string `json:"preview,omitempty"`
// Effort is the proof-of-work, in bits, of the buyer's first envelope.
Effort int `json:"effort"`
// GrantUntil is when the latest address release ends; 0 if none was sent.
GrantUntil int64 `json:"grant_until,omitempty"`
}
const previewRunes = 120
// threadViews summarises the owner's conversations, optionally of one listing.
func (s *server) threadViews(r *http.Request, listingID string) ([]threadView, error) {
threads, err := s.Store.Threads(r.Context(), s.Device.Cert.Author)
if err != nil {
return nil, err
}
out := make([]threadView, 0, len(threads))
for _, t := range threads {
if listingID != "" && t.Listing.ID != listingID {
continue
}
v := threadView{Listing: t.Listing.ID, Thread: t.Thread, Messages: t.Messages, Hidden: t.Hidden,
Replied: t.Replied, FirstAt: t.FirstAt, LastAt: t.LastAt}
msgs, err := s.Store.ThreadMessages(r.Context(), t.Listing, t.Thread)
if err != nil {
return nil, err
}
firstIn := true
for _, m := range msgs {
if m.Dir == store.InboxIn && firstIn {
v.Effort, firstIn = hexZeroBits(m.Hash), false
}
v.LastDir = m.Dir
v.NeedsReply = m.Dir == store.InboxIn && !m.Hidden
v.Preview = ""
switch {
case m.Hidden:
case m.Plain.Type == message.TypeGrant:
v.GrantUntil = m.Plain.ValidUntil
default:
v.Preview = truncateRunes(m.Plain.Text, previewRunes)
}
}
out = append(out, v)
}
return out, nil
}
// hexZeroBits counts the leading zero bits of a hex-encoded hash.
func hexZeroBits(h string) int {
n := 0
for _, c := range h {
d := strings.IndexRune("0123456789abcdef", c)
if d < 0 {
return n
}
if d == 0 {
n += 4
continue
}
for bit := 3; bit >= 0 && d&(1<<bit) == 0; bit-- {
n++
}
return n
}
return n
}
func truncateRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
func (s *server) listThreads(w http.ResponseWriter, r *http.Request) {
@@ -153,14 +231,65 @@ func (s *server) listThreads(w http.ResponseWriter, r *http.Request) {
fail(w, http.StatusInternalServerError, "internal error")
return
}
threads, err := s.Store.Threads(r.Context(), s.Device.Cert.Author)
out, err := s.threadViews(r, r.URL.Query().Get("listing"))
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]threadView, 0, len(threads))
for _, t := range threads {
out = append(out, threadView{t.Listing.ID, t.Thread, t.Messages, t.Hidden, t.Replied, t.FirstAt, t.LastAt})
noStore(w)
writeJSON(w, http.StatusOK, out)
}
type mineView struct {
ID string `json:"id"`
Title string `json:"title"`
Kind string `json:"kind,omitempty"`
Price *listing.Price `json:"price,omitempty"`
ExpiresAt int64 `json:"expires_at"`
Threads int `json:"threads"`
NeedsReply int `json:"needs_reply"`
Hidden int `json:"hidden"`
AddressSaved bool `json:"address_saved"`
}
// mine lists the owner's live listings with what the inbox holds for each.
func (s *server) mine(w http.ResponseWriter, r *http.Request) {
if _, err := s.Inbox.Collect(r.Context()); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
ls, err := s.Store.ByAuthor(r.Context(), s.Device.Cert.Author)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
threads, err := s.threadViews(r, "")
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]mineView, 0, len(ls))
for _, l := range ls {
v := mineView{ID: l.ID, Title: l.Title, Kind: l.Kind, Price: l.Price, ExpiresAt: l.ExpiresAt}
for _, t := range threads {
if t.Listing != l.ID {
continue
}
v.Threads++
if t.NeedsReply {
v.NeedsReply++
}
if t.Hidden > 0 {
v.Hidden++
}
}
if _, err := s.Store.GetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}); err == nil {
v.AddressSaved = true
} else if !errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out = append(out, v)
}
noStore(w)
writeJSON(w, http.StatusOK, out)
+76
View File
@@ -155,6 +155,82 @@ func TestMessagingOverHTTP(t *testing.T) {
}
}
func TestMineAndThreadSummaries(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
// Nothing yet: the listing is there, with nothing in its inbox.
var mine []mineView
code, body := f.do(t, "GET", "/api/v1/mine", "", true)
if code != 200 || json.Unmarshal(body, &mine) != nil || len(mine) != 1 {
t.Fatalf("mine: %d %s", code, body)
}
if mine[0].ID != l.ID || mine[0].Title != l.Title || mine[0].Threads != 0 || mine[0].AddressSaved {
t.Fatalf("empty listing: %+v", mine[0])
}
// One readable request, one with a link (hidden).
ok, bad := newThread(t), newThread(t)
f.send(t, buyerHello(t, l, ok, "Ist die Wohnung noch frei?"))
f.send(t, buyerHello(t, l, bad, "Schau auf https://evil.example"))
f.do(t, "PUT", "/api/v1/listings/"+l.ID+"/address", `{"address":"Musterweg 7, 22765 Hamburg"}`, true)
code, body = f.do(t, "GET", "/api/v1/mine", "", true)
if code != 200 || json.Unmarshal(body, &mine) != nil {
t.Fatalf("mine: %d %s", code, body)
}
if m := mine[0]; m.Threads != 2 || m.NeedsReply != 1 || m.Hidden != 1 || !m.AddressSaved {
t.Fatalf("counts: %+v", m)
}
byThread := func() map[string]threadView {
var ts []threadView
code, body := f.do(t, "GET", "/api/v1/inbox?listing="+l.ID, "", true)
if code != 200 || json.Unmarshal(body, &ts) != nil {
t.Fatalf("inbox: %d %s", code, body)
}
out := map[string]threadView{}
for _, v := range ts {
out[v.Thread] = v
}
return out
}
ts := byThread()
a, b := ts[ok.PublicHex()], ts[bad.PublicHex()]
if !a.NeedsReply || a.LastDir != "in" || a.Preview != "Ist die Wohnung noch frei?" || a.Effort < msgDifficulty {
t.Fatalf("readable request: %+v", a)
}
if b.NeedsReply || b.Preview != "" || b.Hidden != 1 {
t.Fatalf("hidden request must not leak its text or ask for a reply: %+v", b)
}
// Answer with an address: the request no longer needs a reply and shows the release.
path := "/api/v1/inbox/" + l.ID + "/" + ok.PublicHex()
if code, body := f.do(t, "POST", path, `{"type":"grant","note":"Samstag 10 Uhr","valid_days":7}`, true); code != 200 {
t.Fatalf("grant: %d %s", code, body)
}
a = byThread()[ok.PublicHex()]
if a.NeedsReply || a.LastDir != "out" || a.GrantUntil == 0 || a.Preview != "" {
t.Fatalf("after the grant: %+v", a)
}
// Another listing's filter returns nothing; the token is required.
if code, body := f.do(t, "GET", "/api/v1/inbox?listing="+strings.Repeat("0", 32), "", true); code != 200 || strings.TrimSpace(string(body)) != "[]" {
t.Fatalf("filter: %d %s", code, body)
}
if code, _ := f.do(t, "GET", "/api/v1/mine", "", false); code != 401 {
t.Fatalf("mine without a token: %d", code)
}
}
func TestHexZeroBits(t *testing.T) {
for h, want := range map[string]int{"": 0, "f": 0, "8": 0, "7": 1, "1": 3, "0": 4, "00f": 8, "0a": 4, "004": 9, "0000": 16, "zz": 0} {
if got := hexZeroBits(h); got != want {
t.Errorf("hexZeroBits(%q) = %d, want %d", h, got, want)
}
}
}
func TestHiddenFirstMessageTextIsWithheld(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
+745 -36
View File
@@ -197,6 +197,75 @@ var de = {
"inbox.none": "Du hast noch keine Unterhaltungen. \xD6ffne 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. \xD6ffne ihn hier, oder f\xFCge 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": "\u2190 Anzeigen",
"own.backRequests": "\u2190 Anfragen",
"own.pickListing": "W\xE4hle links eine Anzeige.",
"own.pickRequest": "W\xE4hle eine Anfrage.",
"own.addrTitle": "Adresse auf deinem Knoten",
"own.addrHelp": "Wird nie ver\xF6ffentlicht. Nur Personen, denen du sie freigibst, erhalten sie.",
"own.addrNone": "Noch keine Adresse gespeichert. Ohne sie kannst du keine Adresse freigeben.",
"own.addrChange": "\xC4ndern",
"own.addrAdd": "Adresse hinzuf\xFCgen",
"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\xE4lt einen Link",
"own.limitNote": "Pro Anzeige zeigt dein Knoten nur eine begrenzte Zahl neuer Anfragen am Tag; der Rest wartet, die mit dem gr\xF6\xDFten Aufwand zuerst.",
"own.buyer": "Interessent",
"own.you": "Du",
"own.anon": "Anonym, Ende-zu-Ende-verschl\xFCsselt",
"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 \u2026",
"own.release": "Adresse freigeben",
"own.delete": "Unterhaltung l\xF6schen",
"own.deleteSure": "Wirklich l\xF6schen? Sie wird von deinem Knoten entfernt.",
"own.deleteYes": "Ja, l\xF6schen",
"own.sheetTitle": "Adresse freigeben",
"own.sheetHelp": "Eine signierte Nachricht, nur f\xFCr diese Person sichtbar. Ihr Bildschirm blendet sie nach dem Datum aus. Sie k\xF6nnte sie trotzdem kopiert haben.",
"own.fNote": "Hinweis an die Person",
"own.fValid": "Sichtbar f\xFCr",
"own.days": "{n} Tage",
"own.day": "1 Tag",
"own.remember": "Diese Adresse f\xFCr die Anzeige speichern",
"own.sendAddress": "Adresse senden",
"own.close": "Schlie\xDFen",
"own.needAddress": "Bitte gib eine Adresse ein.",
"own.loadError": "Konnte nicht geladen werden.",
"own.err": "Fehlgeschlagen: {detail}",
"verify.title": "Pr\xFCfung in deinem Browser",
"verify.intro": "Diese Pr\xFCfung l\xE4uft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt f\xE4lschen.",
"verify.limit": "Nicht pr\xFCfbar: ob der Anbieter sein Ger\xE4t inzwischen gesperrt hat. Das wei\xDF nur das Netzwerk; dein Knoten kennt den aktuellen Stand.",
@@ -308,6 +377,75 @@ var en = {
"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": "\u2190 Listings",
"own.backRequests": "\u2190 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 \u2026",
"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.",
"verify.limit": "Cannot be checked: whether the owner has since revoked their device. Only the network knows that; your node has the current state.",
@@ -343,6 +481,13 @@ function rooms(x2) {
function date(unix) {
return new Date(unix * 1e3).toLocaleDateString(lang, { dateStyle: "medium" });
}
function when(unix) {
const d = new Date(unix * 1e3);
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" });
}
function price(l) {
if (!l.price) return "";
const base = money(l.price.amount_cents);
@@ -2799,7 +2944,7 @@ function edwards(params, extraOpts = {}) {
const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
try {
return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
} catch (e) {
} catch (e2) {
return { isValid: false, value: _0n4 };
}
} : opts.uvRatio;
@@ -3786,15 +3931,15 @@ function aead(shared, epk, rpk, header) {
const key = hkdf(sha256, shared, concat(epk, rpk), SEAL_INFO, 32);
return chacha20poly1305(key, new Uint8Array(12), enc2.encode(canonicalize(header)));
}
function headerOf(e) {
function headerOf(e2) {
return {
v: e.v,
listing: { author: e.listing.author, id: e.listing.id },
to: e.to,
rcpt: e.rcpt,
epk: e.epk,
created_at: e.created_at,
expires_at: e.expires_at
v: e2.v,
listing: { author: e2.listing.author, id: e2.listing.id },
to: e2.to,
rcpt: e2.rcpt,
epk: e2.epk,
created_at: e2.created_at,
expires_at: e2.expires_at
};
}
var tick = () => new Promise((r) => setTimeout(r, 0));
@@ -3866,27 +4011,27 @@ var fail = (error) => ({ ok: false, error });
function openReply(input, threadSecret, expect) {
try {
return open(input, threadSecret, expect);
} catch (e) {
return fail(e instanceof Error ? e.message : "unreadable");
} catch (e2) {
return fail(e2 instanceof Error ? e2.message : "unreadable");
}
}
function open(input, threadSecret, expect) {
if (!isObject(input) || !isObject(input.listing)) return fail("not an envelope");
const e = input;
const e2 = input;
const threadPub = threadPublic(threadSecret);
const epk = hexBytes(e.epk, 32);
const ct = typeof e.ct === "string" && /^[0-9a-f]*$/.test(e.ct) && e.ct.length % 2 === 0 ? hexBytes(e.ct, e.ct.length / 2) : null;
if (e.v !== VERSION || e.to !== "buyer" || e.rcpt !== mailbox(threadPub) || !epk || !ct || ct.length < TAG + 1 || ct.length > BUCKETS[BUCKETS.length - 1] + TAG || !safeInt(e.created_at) || !safeInt(e.expires_at)) {
const epk = hexBytes(e2.epk, 32);
const ct = typeof e2.ct === "string" && /^[0-9a-f]*$/.test(e2.ct) && e2.ct.length % 2 === 0 ? hexBytes(e2.ct, e2.ct.length / 2) : null;
if (e2.v !== VERSION || e2.to !== "buyer" || e2.rcpt !== mailbox(threadPub) || !epk || !ct || ct.length < TAG + 1 || ct.length > BUCKETS[BUCKETS.length - 1] + TAG || !safeInt(e2.created_at) || !safeInt(e2.expires_at)) {
return fail("not a reply for this conversation");
}
if (e.listing.author !== expect.author || e.listing.id !== expect.id) {
if (e2.listing.author !== expect.author || e2.listing.id !== expect.id) {
return fail("reply refers to another listing");
}
const rpk = x25519.getPublicKey(threadSecret);
const shared = x25519.getSharedSecret(threadSecret, epk);
let body;
try {
body = unpad(aead(shared, epk, rpk, headerOf(e)).decrypt(ct));
body = unpad(aead(shared, epk, rpk, headerOf(e2)).decrypt(ct));
} catch {
return fail("cannot decrypt");
}
@@ -3897,7 +4042,7 @@ function open(input, threadSecret, expect) {
if (bad) return fail(bad);
const plain = p;
if (plain.thread !== threadPub) return fail("reply belongs to another thread");
if (plain.listing.author !== e.listing.author || plain.listing.id !== e.listing.id) {
if (plain.listing.author !== e2.listing.author || plain.listing.id !== e2.listing.id) {
return fail("reply refers to another listing");
}
const c = plain.cert;
@@ -4030,12 +4175,12 @@ var app = () => document.getElementById("app");
var fromHex = (s) => Uint8Array.from(s.match(/../g) ?? [], (b) => parseInt(b, 16));
var difficulty = () => state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY;
var utf8 = (s) => new TextEncoder().encode(s).length;
function describe(e) {
if (e instanceof InputError) return t(`problem.${e.problem}`);
if (e instanceof HttpError) {
if (e.status === 404) return t("send.404");
if (e.status === 429) return t("send.429");
return t("send.other", { detail: e.detail });
function describe(e2) {
if (e2 instanceof InputError) return t(`problem.${e2.problem}`);
if (e2 instanceof HttpError) {
if (e2.status === 404) return t("send.404");
if (e2.status === 429) return t("send.429");
return t("send.other", { detail: e2.detail });
}
return t("send.network");
}
@@ -4071,8 +4216,8 @@ function composer(opts) {
await opts.send(text);
area.value = "";
update();
} catch (e) {
problem.textContent = describe(e);
} catch (e2) {
problem.textContent = describe(e2);
} finally {
button.disabled = false;
area.disabled = false;
@@ -4248,7 +4393,7 @@ async function showConversation(author, id, secret) {
{ class: "panel" },
h("h2", null, t("chat.link")),
h("p", { class: "muted" }, t("chat.linkHelp")),
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e) => e.target.select() })
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e2) => e2.target.select() })
),
deleteControl(conv)
]);
@@ -4375,10 +4520,558 @@ function showInbox() {
]);
}
// src/ownerApi.ts
var TOKEN_KEY = "allmende.owner.token";
var memory = null;
function getToken() {
try {
return sessionStorage.getItem(TOKEN_KEY) ?? memory;
} catch {
return memory;
}
}
function setToken(token) {
memory = token;
try {
sessionStorage.setItem(TOKEN_KEY, token);
} catch {
}
}
function clearToken() {
memory = null;
try {
sessionStorage.removeItem(TOKEN_KEY);
} catch {
}
}
var Unauthorized = class extends Error {
constructor() {
super("unauthorized");
}
};
async function call(method, path, body) {
const token = getToken();
if (!token) throw new Unauthorized();
const res = await fetch(path, {
method,
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
...body === void 0 ? {} : { "Content-Type": "application/json" }
},
body: body === void 0 ? void 0 : JSON.stringify(body)
});
if (res.status === 401) {
clearToken();
throw new Unauthorized();
}
if (res.status === 204) return null;
let data = null;
try {
data = await res.json();
} catch {
}
if (!res.ok) {
const detail = typeof data?.error === "string" ? data.error : res.statusText;
throw new HttpError(res.status, detail);
}
return data;
}
var e = encodeURIComponent;
async function getMine() {
return await call("GET", "/api/v1/mine");
}
async function getThreads(listing) {
return await call("GET", `/api/v1/inbox?listing=${e(listing)}`);
}
async function getMessages(listing, thread) {
return await call("GET", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
}
async function sendReply(listing, thread, r) {
await call("POST", `/api/v1/inbox/${e(listing)}/${e(thread)}`, r);
}
async function deleteThread(listing, thread) {
await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
}
async function getAddress(listing) {
try {
return await call("GET", `/api/v1/listings/${e(listing)}/address`);
} catch (err) {
if (err instanceof HttpError && err.status === 404) return null;
throw err;
}
}
async function putAddress(listing, a) {
await call("PUT", `/api/v1/listings/${e(listing)}/address`, a);
}
async function deleteAddress(listing) {
await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
}
// src/owner.ts
var REFRESH_MS = 3e4;
var VALID_DAYS = [1, 3, 7, 14, 30];
var DEFAULT_DAYS = 7;
var app2 = () => document.getElementById("app");
var shortId = (thread) => thread.slice(-4);
function explain(e2) {
return t("own.err", { detail: e2 instanceof HttpError ? e2.detail : e2 instanceof Error ? e2.message : "?" });
}
function renderLogin(rejected) {
const root = app2();
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;
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")))
)
)
]);
}
async function showOwner(listingId, thread) {
const gen = state.generation;
if (!getToken()) {
renderLogin(false);
return;
}
const root = app2();
document.body.classList.add("wide");
clear(root);
const depth = thread ? 3 : listingId ? 2 : 1;
let mine2 = [];
let threads = [];
let msgs = [];
let filter = "all";
let loaded2 = false;
const notice = h("p", { class: "error", role: "alert" });
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")))
);
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"))]
);
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,
composer2(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())),
deleteControl2(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)]);
const kindLabel = (k) => k === "rent" || k === "sale" ? t(`kind.${k}`) : k ?? "";
function renderListings() {
clear(listingsBox);
if (loaded2 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
for (const m of mine2) {
const sub = [kindLabel(m.kind), m.price ? price({ price: m.price }) : ""].filter(Boolean).join(" \xB7 ");
listingsBox.append(
h(
"a",
{ class: `ocard${m.id === listingId ? " selected" : ""}`, href: `#/mine/${m.id}`, "aria-current": m.id === listingId ? "page" : void 0 },
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) {
const now = nowSeconds();
const out = [];
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) {
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() {
const m = mine2.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"]]) {
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 (loaded2 && 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" : void 0 },
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() {
if (!thread) return;
threadHead.textContent = t("own.request", { id: shortId(thread) });
clear(msgBox);
for (const m of msgs) msgBox.append(bubble2(m));
firstNote.hidden = msgs.some((m) => m.dir === "out");
}
function renderAll() {
renderListings();
if (listingId) renderRequests();
renderThread();
}
function logout() {
clearToken();
location.hash = "#/";
}
async function refresh() {
try {
mine2 = await getMine();
if (listingId) threads = await getThreads(listingId);
if (listingId && thread) {
try {
msgs = await getMessages(listingId, thread);
} catch (e2) {
if (e2 instanceof HttpError && e2.status === 404) {
if (gen === state.generation) location.hash = `#/mine/${listingId}`;
return;
}
throw e2;
}
}
} catch (e2) {
if (gen !== state.generation) return;
if (e2 instanceof Unauthorized) renderLogin(true);
else notice.textContent = t("own.loadError");
return;
}
if (gen !== state.generation) return;
notice.textContent = "";
loaded2 = true;
renderAll();
}
renderListings();
await refresh();
const tick2 = () => {
setTimeout(() => {
if (gen !== state.generation) return;
void refresh().then(tick2);
}, REFRESH_MS);
};
tick2();
}
function bubble2(m) {
const mine2 = m.dir === "out";
const who = mine2 ? t("own.you") : t("own.buyer");
const head = h("div", { class: "who" }, who, " \xB7 ", 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 = (label2, v) => v ? [h("dt", null, t(label2)), 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 ${mine2 ? "out" : "in"}` }, head, h("p", { class: "pre" }, m.text ?? ""));
}
function composer2(listingId, thread, done, release) {
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 sendReply(listingId, thread, { type: "text", text });
area.value = "";
done();
} catch (e2) {
problem.textContent = e2 instanceof Unauthorized ? t("own.loginBad") : explain(e2);
} finally {
send.disabled = false;
send.textContent = t("own.send");
}
})();
}
},
area,
h("div", { class: "actions" }, send, rel),
problem
);
}
function deleteControl2(listingId, thread) {
const slot = h("p", null);
const ask = () => {
clear(slot);
append(slot, [
t("own.deleteSure"),
" ",
h("button", { type: "button", class: "btn", onclick: () => void 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;
}
function addressCard(listingId, changed) {
const root = h("div", { class: "panel addr" });
let saved = null;
function show() {
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() {
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 e2 = 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 = { address: a.value.trim(), phone: p.value.trim() || void 0, email: e2.value.trim() || void 0 };
if (!next.address) {
problem.textContent = t("own.needAddress");
return;
}
await 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"), e2),
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 deleteAddress(listingId).then(() => {
saved = null;
show();
changed();
}).catch((err) => {
problem.textContent = explain(err);
})
},
t("own.addrRemove")
)
)
)
]);
a.focus();
}
void getAddress(listingId).then((a) => {
saved = a;
show();
}, () => show());
show();
return { root };
}
function openSheet(listingId, thread, opener, done) {
const host = app2();
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: 1e3 });
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 = 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 putAddress(listingId, { address: a, phone: phone.value.trim() || void 0, email: saved?.email });
}
await sendReply(listingId, thread, {
type: "grant",
address: a,
phone: phone.value.trim() || void 0,
note: note.value.trim() || void 0,
valid_days: Number(valid.value)
});
close();
done();
} catch (e2) {
problem.textContent = explain(e2);
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 }, "\xD7");
const backdrop = h(
"div",
{
class: "backdrop",
onclick: (ev) => {
if (ev.target === backdrop) close();
},
onkeydown: (ev) => {
if (ev.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 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;
}
},
() => {
remember.checked = true;
}
);
}
// src/main.ts
var PAGE = 20;
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
var app2 = document.getElementById("app");
var app3 = document.getElementById("app");
var statusEl = document.getElementById("status");
function label(prefix, value) {
if (!value) return "";
@@ -4457,8 +5150,8 @@ function searchForm(params) {
),
regions
);
form.addEventListener("submit", (e) => {
e.preventDefault();
form.addEventListener("submit", (e2) => {
e2.preventDefault();
const q = new URLSearchParams();
for (const [k, v] of new FormData(form)) {
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
@@ -4533,9 +5226,9 @@ async function loadResults(gen, q, root) {
}
function showSearch(params) {
const gen = state.generation;
clear(app2);
clear(app3);
const results = h("div", { class: "results", "aria-live": "polite" });
app2.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
app3.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
const prefix = params.get("geohash")?.trim().toLowerCase();
if (prefix && !GEOHASH_PREFIX.test(prefix)) {
results.append(h("p", { class: "error" }, t("filter.regionHint")));
@@ -4620,9 +5313,9 @@ function listingBody(l) {
}
async function showDetail(author, id) {
const gen = state.generation;
clear(app2);
clear(app3);
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
app2.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
app3.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
let raw;
try {
raw = await getListing(author, id);
@@ -4649,6 +5342,14 @@ async function showDetail(author, id) {
}
append(body, [...listingBody(l), verification(raw, l, v)]);
}
function renderNav() {
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() {
state.generation++;
const hash = location.hash.replace(/^#/, "") || "/";
@@ -4657,16 +5358,24 @@ function route() {
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) {
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() {
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", {
+88 -1
View File
@@ -214,7 +214,7 @@ pre {
}
/* Messages */
.nav { margin-left: auto; }
.nav { margin-left: auto; display: flex; gap: 16px; }
textarea {
width: 100%;
box-sizing: border-box;
@@ -236,3 +236,90 @@ textarea:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px;
.msg .who { color: var(--muted); font-size: 0.85rem; margin-bottom: 4px; }
.grant { border: 2px solid var(--accent); border-radius: 8px; padding: 10px 12px; margin: 4px 0; }
input[readonly] { width: 100%; box-sizing: border-box; }
/* Owner inbox */
body.wide .top, body.wide main, body.wide .foot { max-width: 80rem; }
.error:empty { display: none; }
.stack { display: grid; gap: 10px; }
.stack label, .sheet label { display: flex; flex-direction: column; gap: 4px; color: var(--muted); font-size: 0.9rem; }
.stack input, .sheet input:not([type="checkbox"]), .sheet select, .sheet textarea { width: 100%; }
input[type="checkbox"] { min-height: auto; width: auto; }
label.check { flex-direction: row; align-items: center; gap: 8px; }
.row { display: flex; gap: 12px; justify-content: space-between; align-items: baseline; }
.note { margin: 0 0 8px; padding: 10px 12px; border-radius: 8px; font-size: 0.9rem; }
.note.warn { color: var(--warn); background: var(--warn-bg); }
.owner { display: grid; gap: 16px; grid-template-columns: 17rem minmax(0, 1fr) minmax(0, 24rem); align-items: start; }
.pane-title { margin: 0 0 8px; font-size: 1.1rem; overflow-wrap: anywhere; }
.pick { padding: 16px; }
.olist { display: grid; gap: 8px; margin-bottom: 12px; }
.ocard {
display: grid;
gap: 4px;
min-height: 2.75rem;
padding: 12px 14px;
color: var(--text);
text-decoration: none;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.ocard.selected { border: 2px solid var(--accent); padding: 11px 13px; }
.ocard .clip { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.badge.warn { color: var(--warn); background: var(--warn-bg); }
.badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); }
.chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
.chip {
min-height: 2.25rem;
padding: 4px 12px;
font: inherit;
font-size: 0.9rem;
color: var(--text);
background: var(--surface);
border: 1px solid var(--line);
border-radius: 999px;
cursor: pointer;
}
.chip.on { color: var(--accent-text); background: var(--accent); border-color: var(--accent); font-weight: 600; }
.addr { margin-bottom: 10px; }
.narrow-only { display: none; }
.owner .thread { margin-bottom: 12px; }
.owner .msg { max-width: 92%; }
.owner .msg.in { justify-self: start; }
.backdrop {
position: fixed;
inset: 0;
z-index: 10;
display: flex;
align-items: flex-end;
justify-content: center;
background: rgba(20, 24, 26, 0.55);
}
.sheet {
width: 100%;
max-width: 32rem;
max-height: 92vh;
overflow-y: auto;
padding: 16px 16px 20px;
background: var(--surface);
border: 1px solid var(--line);
border-radius: 16px 16px 0 0;
}
.sheet h2 { margin: 0; font-size: 1.1rem; }
.btn.close { min-width: 2.75rem; padding: 4px 10px; }
/* One pane at a time on a phone: the deepest one. */
@media (max-width: 60rem) {
.owner { grid-template-columns: minmax(0, 1fr); }
.owner > .pane { display: none; }
.owner.depth-1 > .pane-listings,
.owner.depth-2 > .pane-requests,
.owner.depth-3 > .pane-thread { display: block; }
.narrow-only { display: inline-block; }
}
@media (min-width: 40rem) {
.backdrop { align-items: center; }
.sheet { border-radius: var(--radius); }
}
+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`);
}
+88 -1
View File
@@ -214,7 +214,7 @@ pre {
}
/* Messages */
.nav { margin-left: auto; }
.nav { margin-left: auto; display: flex; gap: 16px; }
textarea {
width: 100%;
box-sizing: border-box;
@@ -236,3 +236,90 @@ textarea:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px;
.msg .who { color: var(--muted); font-size: 0.85rem; margin-bottom: 4px; }
.grant { border: 2px solid var(--accent); border-radius: 8px; padding: 10px 12px; margin: 4px 0; }
input[readonly] { width: 100%; box-sizing: border-box; }
/* Owner inbox */
body.wide .top, body.wide main, body.wide .foot { max-width: 80rem; }
.error:empty { display: none; }
.stack { display: grid; gap: 10px; }
.stack label, .sheet label { display: flex; flex-direction: column; gap: 4px; color: var(--muted); font-size: 0.9rem; }
.stack input, .sheet input:not([type="checkbox"]), .sheet select, .sheet textarea { width: 100%; }
input[type="checkbox"] { min-height: auto; width: auto; }
label.check { flex-direction: row; align-items: center; gap: 8px; }
.row { display: flex; gap: 12px; justify-content: space-between; align-items: baseline; }
.note { margin: 0 0 8px; padding: 10px 12px; border-radius: 8px; font-size: 0.9rem; }
.note.warn { color: var(--warn); background: var(--warn-bg); }
.owner { display: grid; gap: 16px; grid-template-columns: 17rem minmax(0, 1fr) minmax(0, 24rem); align-items: start; }
.pane-title { margin: 0 0 8px; font-size: 1.1rem; overflow-wrap: anywhere; }
.pick { padding: 16px; }
.olist { display: grid; gap: 8px; margin-bottom: 12px; }
.ocard {
display: grid;
gap: 4px;
min-height: 2.75rem;
padding: 12px 14px;
color: var(--text);
text-decoration: none;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.ocard.selected { border: 2px solid var(--accent); padding: 11px 13px; }
.ocard .clip { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.badge.warn { color: var(--warn); background: var(--warn-bg); }
.badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); }
.chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
.chip {
min-height: 2.25rem;
padding: 4px 12px;
font: inherit;
font-size: 0.9rem;
color: var(--text);
background: var(--surface);
border: 1px solid var(--line);
border-radius: 999px;
cursor: pointer;
}
.chip.on { color: var(--accent-text); background: var(--accent); border-color: var(--accent); font-weight: 600; }
.addr { margin-bottom: 10px; }
.narrow-only { display: none; }
.owner .thread { margin-bottom: 12px; }
.owner .msg { max-width: 92%; }
.owner .msg.in { justify-self: start; }
.backdrop {
position: fixed;
inset: 0;
z-index: 10;
display: flex;
align-items: flex-end;
justify-content: center;
background: rgba(20, 24, 26, 0.55);
}
.sheet {
width: 100%;
max-width: 32rem;
max-height: 92vh;
overflow-y: auto;
padding: 16px 16px 20px;
background: var(--surface);
border: 1px solid var(--line);
border-radius: 16px 16px 0 0;
}
.sheet h2 { margin: 0; font-size: 1.1rem; }
.btn.close { min-width: 2.75rem; padding: 4px 10px; }
/* One pane at a time on a phone: the deepest one. */
@media (max-width: 60rem) {
.owner { grid-template-columns: minmax(0, 1fr); }
.owner > .pane { display: none; }
.owner.depth-1 > .pane-listings,
.owner.depth-2 > .pane-requests,
.owner.depth-3 > .pane-thread { display: block; }
.narrow-only { display: inline-block; }
}
@media (min-width: 40rem) {
.backdrop { align-items: center; }
.sheet { border-radius: var(--radius); }
}
+24
View File
@@ -176,6 +176,14 @@ export interface Gateway {
mailboxes: Map<string, unknown[]>;
/** Make POST /api/v1/messages answer with this status and error. */
postFails?: { status: number; error: string };
/** Plays the node's owner endpoints (/mine, /inbox, .../address); unset, they answer 404. */
owner?: (req: {
method: string;
path: string;
query: URLSearchParams;
body: string;
auth: string;
}) => { status: number; body?: unknown } | undefined;
close(): Promise<void>;
}
@@ -203,6 +211,22 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
// The owner's token-protected routes are played by the test, if it sets `owner`.
if (/^\/api\/v1\/(mine|inbox)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
const auth = req.headers.authorization ?? "";
const r = gateway.owner?.({ method: req.method ?? "GET", path: url.pathname, query: url.searchParams, body, auth });
if (!r) return json(404, { error: "not found" });
if (r.status === 204) {
res.writeHead(204);
return res.end();
}
json(r.status, r.body ?? null);
});
return;
}
if (url.pathname === "/api/v1/messages") {
if (req.method === "POST") {
let body = "";
+316
View File
@@ -0,0 +1,316 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, test } from "node:test";
import type { Address, Mine, OwnerMessage, Thread } from "../src/ownerApi.ts";
import { NOW, openPage, startGateway, type Gateway, type Page } from "./helpers.ts";
const TOKEN = "ab12".repeat(16);
const L1 = "11".repeat(16);
const L2 = "22".repeat(16);
const T_NEW = "a".repeat(60) + "a3f9"; // needs a reply
const T_LINK = "b".repeat(60) + "5b10"; // hid a link
const T_GRANT = "c".repeat(60) + "e204"; // address released
const XSS = `<img src=x onerror="window.__pwned=1"> noch frei?`;
/** A stand-in for the owner's node: state, and a record of what the page asked. */
function fakeNode() {
const s = {
token: TOKEN,
calls: [] as { method: string; path: string; body: string; auth: string }[],
address: { address: "Musterweg 7, 22765 Hamburg", phone: "+49 40 1" } as Address | null,
mine: [
{ id: L1, title: "Helle Wohnung", kind: "rent", price: { amount_cents: 115000, currency: "EUR", period: "month" }, expires_at: NOW + 86400 * 30, threads: 3, needs_reply: 1, hidden: 1, address_saved: true },
{ id: L2, title: "Gewerbefläche", kind: "rent", expires_at: NOW + 86400 * 30, threads: 0, needs_reply: 0, hidden: 0, address_saved: false },
] as Mine[],
threads: [
{ listing: L1, thread: T_NEW, messages: 1, hidden: 0, replied: false, first_at: NOW - 600, last_at: NOW - 600, last_dir: "in", needs_reply: true, preview: XSS, effort: 19 },
{ listing: L1, thread: T_LINK, messages: 1, hidden: 1, replied: false, first_at: NOW - 90000, last_at: NOW - 90000, last_dir: "in", needs_reply: false, effort: 15 },
{ listing: L1, thread: T_GRANT, messages: 3, hidden: 0, replied: true, first_at: NOW - 90000, last_at: NOW - 80000, last_dir: "out", needs_reply: false, effort: 17, grant_until: NOW + 86400 },
] as Thread[],
msgs: {
[T_NEW]: [{ hash: "h1", dir: "in", received_at: NOW - 600, type: "text", n: 1, sent_at: NOW - 600, text: XSS }],
[T_LINK]: [{ hash: "h2", dir: "in", hidden: true, reason: "x", received_at: NOW, type: "text", n: 1, sent_at: NOW - 90000 }],
[T_GRANT]: [
{ hash: "h3", dir: "in", received_at: NOW, type: "text", n: 1, sent_at: NOW - 90000, text: "Guten Tag" },
{ hash: "h4", dir: "out", received_at: NOW, type: "grant", n: 1, sent_at: NOW - 80000, address: "Musterweg 7, 22765 Hamburg", note: "Klingel: Meyer", valid_until: NOW + 86400 },
],
} as Record<string, OwnerMessage[]>,
};
const handler: NonNullable<Gateway["owner"]> = (r) => {
s.calls.push({ method: r.method, path: r.path + (r.query.size ? "?" + r.query : ""), body: r.body, auth: r.auth });
if (r.auth !== `Bearer ${s.token}`) return { status: 401, body: { error: "unauthorized" } };
if (r.path === "/api/v1/mine") return { status: 200, body: s.mine };
if (r.path === "/api/v1/inbox") return { status: 200, body: s.threads.filter((t) => t.listing === r.query.get("listing")) };
const th = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(r.path);
if (th) {
const msgs = s.msgs[th[2]!];
if (!msgs) return { status: 404, body: { error: "no such conversation" } };
if (r.method === "POST") return { status: 200, body: { hash: "x" } };
if (r.method === "DELETE") return { status: 204 };
return { status: 200, body: msgs };
}
if (/\/address$/.test(r.path)) {
if (r.method === "PUT") { s.address = JSON.parse(r.body) as Address; return { status: 204 }; }
if (r.method === "DELETE") { s.address = null; return { status: 204 }; }
return s.address ? { status: 200, body: s.address } : { status: 404, body: { error: "no address saved for this listing" } };
}
return undefined;
};
return { s, handler };
}
let gw: Gateway;
let node: ReturnType<typeof fakeNode>;
let page: Page | undefined;
beforeEach(async () => {
gw = await startGateway({ listings: [] });
node = fakeNode();
gw.owner = node.handler;
});
afterEach(async () => {
page?.close();
page = undefined;
await gw.close();
});
const open = (hash: string) => (page = openPage(gw.url, hash));
const text = () => page!.document.body.textContent ?? "";
const q = <T extends Element = HTMLElement>(sel: string) => page!.document.querySelector<T>(sel);
const qa = (sel: string) => [...page!.document.querySelectorAll(sel)];
const button = (label: string) => qa("button").find((b) => b.textContent === label) as HTMLButtonElement | undefined;
const submit = (form: Element) => form.dispatchEvent(new page!.window.Event("submit", { cancelable: true }));
const posts = () => node.s.calls.filter((c) => c.method === "POST");
test("without a token the page asks for one, and a wrong token is refused", async () => {
open("#/mine");
await page!.waitFor(() => q('input[name="token"]') !== null, "the sign-in form");
assert.equal(node.s.calls.length, 0, "nothing is requested before signing in");
assert.equal(q("nav a[href='#/mine']"), null, "the owner link is hidden until signed in");
q<HTMLInputElement>('input[name="token"]')!.value = "not-the-token";
submit(q("form")!);
await page!.waitFor(() => /rejected the token/.test(text()), "a rejection notice");
assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), null, "a refused token is forgotten");
q<HTMLInputElement>('input[name="token"]')!.value = TOKEN;
submit(q("form")!);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
assert.ok(node.s.calls.every((c) => c.auth === "Bearer not-the-token" || c.auth === `Bearer ${TOKEN}`));
});
test("the login link signs in and disappears from the address bar", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
assert.equal(page!.window.location.hash, "#/mine", "the token is not left in the URL");
assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), TOKEN);
assert.equal(page!.window.localStorage.getItem("allmende.owner.token"), null, "never in localStorage");
assert.ok(q("nav a[href='#/mine']"), "the owner link appears");
assert.ok(node.s.calls.every((c) => c.auth === `Bearer ${TOKEN}`));
const [first, second] = qa(".pane-listings .ocard");
assert.match(first!.textContent!, /Helle Wohnung/);
assert.match(first!.textContent!, /1 need a reply/);
assert.match(first!.textContent!, /Address saved/);
assert.match(first!.textContent!, /1,150\.00/);
assert.match(second!.textContent!, /No requests/);
assert.match(second!.textContent!, /No address saved/);
});
test("a listing's requests show status, preview and effort, and can be filtered", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => qa(".pane-requests .olist .ocard").length === 3, "three requests");
const rows = qa(".pane-requests .olist .ocard");
const [neu, link, grant] = rows.map((r) => r.textContent!);
assert.match(neu!, /#a3f9/);
assert.match(neu!, /Needs reply/);
assert.match(neu!, /Effort 19 bit/);
assert.match(link!, /#5b10/);
assert.match(link!, /Link hidden/);
assert.match(link!, /Hidden: contains a link/);
assert.match(grant!, /#e204/);
assert.match(grant!, /Address until/);
assert.match(text(), /Musterweg 7, 22765 Hamburg/, "the saved address is shown");
button("Needs reply 1")!.click();
assert.equal(qa(".pane-requests .olist .ocard").length, 1);
button("Link hidden 1")!.click();
assert.equal(qa(".pane-requests .olist .ocard").length, 1);
assert.match(qa(".pane-requests .olist .ocard")[0]!.textContent!, /#5b10/);
button("All 3")!.click();
assert.equal(qa(".pane-requests .olist .ocard").length, 3);
assert.equal(button("All 3")!.getAttribute("aria-pressed"), "true");
});
test("buyer text is shown as text only, and the first-message note disappears once you replied", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_NEW}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 1, "the conversation");
assert.equal(q(".pane-thread .msg img"), null, "no element is created from buyer text");
assert.equal((page!.window as unknown as { __pwned?: number }).__pwned, undefined);
assert.ok(q(".pane-thread .msg .pre")!.textContent!.includes("<img src=x"), "the markup is visible as text");
assert.equal(q<HTMLElement>(".pane-thread .note")!.hidden, false, "first message: the rules are explained");
assert.match(text(), /Request #a3f9/);
// An answered conversation does not show that note.
page!.window.location.hash = `#/mine/${L1}/${T_GRANT}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 2, "the second conversation");
assert.equal(q<HTMLElement>(".pane-thread .note")!.hidden, true);
assert.match(q(".pane-thread .grant")!.textContent!, /Address released until/);
assert.match(q(".pane-thread .grant")!.textContent!, /Klingel: Meyer/);
// A hidden message never shows its text, only why.
page!.window.location.hash = `#/mine/${L1}/${T_LINK}`;
await page!.waitFor(() => /Hidden: a first message must be short/.test(text()), "hidden explanation");
});
test("a reply is sent as text and the box is cleared", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_NEW}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 1, "the conversation");
const area = q<HTMLTextAreaElement>(".pane-thread textarea")!;
area.value = "Ja, noch frei. Besichtigung am Samstag?";
submit(q(".pane-thread form.compose")!);
await page!.waitFor(() => posts().length === 1, "the reply");
assert.equal(posts()[0]!.path, `/api/v1/inbox/${L1}/${T_NEW}`);
assert.deepEqual(JSON.parse(posts()[0]!.body), { type: "text", text: "Ja, noch frei. Besichtigung am Samstag?" });
await page!.waitFor(() => area.value === "", "the box to clear");
// Empty text is not sent.
submit(q(".pane-thread form.compose")!);
await new Promise((r) => setTimeout(r, 50));
assert.equal(posts().length, 1);
});
test("releasing the address: prefilled sheet, signed grant request, closes", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_NEW}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 1, "the conversation");
button("Release address")!.click();
await page!.waitFor(() => q('.sheet input[name="address"]') !== null, "the sheet");
await page!.waitFor(() => q<HTMLInputElement>('.sheet input[name="address"]')!.value !== "", "prefill from the saved address");
assert.equal(q<HTMLInputElement>('.sheet input[name="address"]')!.value, "Musterweg 7, 22765 Hamburg");
assert.equal(q<HTMLInputElement>('.sheet input[name="phone"]')!.value, "+49 40 1");
assert.equal(q<HTMLSelectElement>('.sheet select[name="valid"]')!.value, "7", "a week by default");
assert.equal(q<HTMLInputElement>('.sheet input[name="remember"]')!.checked, false, "already saved: not offered again");
assert.match(q(".sheet")!.textContent!, /could still have copied it/);
q<HTMLTextAreaElement>('.sheet textarea[name="note"]')!.value = "Samstag 10 Uhr, bitte zweimal klingeln";
q<HTMLSelectElement>('.sheet select[name="valid"]')!.value = "3";
submit(q(".sheet form")!);
await page!.waitFor(() => posts().length === 1, "the grant");
assert.deepEqual(JSON.parse(posts()[0]!.body), {
type: "grant",
address: "Musterweg 7, 22765 Hamburg",
phone: "+49 40 1",
note: "Samstag 10 Uhr, bitte zweimal klingeln",
valid_days: 3,
});
await page!.waitFor(() => q(".sheet") === null, "the sheet to close");
assert.equal(node.s.calls.filter((c) => c.method === "PUT").length, 0, "an unchanged address is not saved again");
});
test("releasing without a saved address offers to keep it, and refuses an empty one", async () => {
node.s.address = null;
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_NEW}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 1, "the conversation");
button("Release address")!.click();
await page!.waitFor(() => q<HTMLInputElement>('.sheet input[name="remember"]')?.checked === true, "remember is on by default");
submit(q(".sheet form")!);
await page!.waitFor(() => /enter an address/.test(text()), "a refusal");
assert.equal(posts().length, 0);
q<HTMLInputElement>('.sheet input[name="address"]')!.value = "Neue Straße 3, 20095 Hamburg";
submit(q(".sheet form")!);
await page!.waitFor(() => posts().length === 1, "the grant");
const put = node.s.calls.find((c) => c.method === "PUT")!;
assert.deepEqual(JSON.parse(put.body), { address: "Neue Straße 3, 20095 Hamburg" });
assert.deepEqual(node.s.address, { address: "Neue Straße 3, 20095 Hamburg" });
assert.equal(JSON.parse(posts()[0]!.body).valid_days, 7);
});
test("the sheet closes with Escape and with the backdrop, and sends nothing", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_NEW}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 1, "the conversation");
button("Release address")!.click();
await page!.waitFor(() => q(".sheet") !== null, "the sheet");
q<HTMLElement>(".sheet input")!.dispatchEvent(new page!.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
assert.equal(q(".sheet"), null);
button("Release address")!.click();
await page!.waitFor(() => q(".sheet") !== null, "the sheet again");
q<HTMLElement>(".backdrop")!.dispatchEvent(new page!.window.MouseEvent("click", { bubbles: true }));
assert.equal(q(".sheet"), null);
assert.equal(posts().length, 0);
});
test("the saved address can be changed and removed", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => /Musterweg 7/.test(text()), "the saved address");
button("Change")!.click();
const form = q(".addr form")!;
q<HTMLInputElement>('.addr input[name="address"]')!.value = "Hafenstraße 9, 20459 Hamburg";
q<HTMLInputElement>('.addr input[name="phone"]')!.value = "";
submit(form);
await page!.waitFor(() => /Hafenstraße 9/.test(q(".addr")!.textContent!), "the new address");
assert.deepEqual(node.s.address, { address: "Hafenstraße 9, 20459 Hamburg" });
button("Change")!.click();
button("Remove")!.click();
await page!.waitFor(() => /No address saved yet/.test(text()), "the address removed");
assert.equal(node.s.address, null);
});
test("deleting a conversation asks first, then goes back to the requests", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_LINK}`;
await page!.waitFor(() => button("Delete conversation") !== undefined, "the delete button");
button("Delete conversation")!.click();
assert.equal(node.s.calls.filter((c) => c.method === "DELETE").length, 0, "nothing is deleted by one click");
button("Yes, delete")!.click();
await page!.waitFor(() => page!.window.location.hash === `#/mine/${L1}`, "back to the requests");
assert.equal(node.s.calls.filter((c) => c.method === "DELETE")[0]!.path, `/api/v1/inbox/${L1}/${T_LINK}`);
});
test("a token that stops working sends the owner back to sign in", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
page!.window.location.hash = `#/mine/${L1}/${T_NEW}`;
await page!.waitFor(() => qa(".pane-thread .msg").length === 1, "the conversation");
node.s.token = "rotated"; // e.g. after `recover`
q<HTMLTextAreaElement>(".pane-thread textarea")!.value = "Hallo";
submit(q(".pane-thread form.compose")!);
await page!.waitFor(() => /rejected the token/.test(text()), "a rejection");
assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), null);
});
test("signing out forgets the token", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
button("Sign out")!.click();
assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), null);
await page!.waitFor(() => q("nav a[href='#/mine']") === null, "the owner link to vanish");
});