Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

render.gno

6.28 Kb · 187 lines
  1package usernames
  2
  3import (
  4	"strings"
  5
  6	"gno.land/p/moul/kit/ui/v0"
  7	"gno.land/p/moul/md/v0"
  8	"gno.land/p/moul/realmpath/v0"
  9	tb "gno.land/p/moul/toolbox/v0"
 10	"gno.land/r/sys/users"
 11)
 12
 13// hubURL is the toolbox this tool belongs to. A private realm cannot import
 14// the hub, so the link is a constant on this side; `r/moul/toolbox` holds the
 15// authoritative copy and its tests check that the tool path matches.
 16const hubURL = "/r/moul/toolbox"
 17
 18// maxInput bounds what is echoed back into the page. A render that reflects an
 19// unbounded query parameter is a page anyone can make arbitrarily large.
 20const maxInput = 64
 21
 22// Render routes gnoweb paths:
 23//
 24//	/                the form, and what the tool answers
 25//	/lookup?q=moul   the result, which is where the form submits
 26//	/moul            the same result, addressable directly
 27//	/g1manfred...    the same, by address
 28func Render(path string) string {
 29	req := realmpath.Parse(path)
 30	parts := req.PathParts()
 31
 32	input := req.Query.Get("q")
 33	if input == "" && len(parts) == 1 && parts[0] != "" && parts[0] != "lookup" {
 34		input = parts[0]
 35	}
 36	if len(parts) > 1 {
 37		return header() + "\n" + notFound(strings.Join(parts, "/"))
 38	}
 39	if input == "" {
 40		return header() + "\n" + renderHome()
 41	}
 42	return header() + "\n" + renderResult(input)
 43}
 44
 45func header() string {
 46	return tb.Nav(hubURL, "Usernames")
 47}
 48
 49func renderHome() string {
 50	var b strings.Builder
 51	b.WriteString(md.H1("Usernames"))
 52	b.WriteString("\nWho holds a name, and what name an address holds. Type either one.\n")
 53	b.WriteString("\n" + form())
 54	b.WriteString("\n" + md.H2("What this answers"))
 55	b.WriteString("\n" + md.BulletList([]string{
 56		"The address behind a username, and the username behind an address.",
 57		"Whether the name you typed is their **current** name or one they renamed away from.",
 58		"The canonical key the name collapses to, and who already holds that key.",
 59	}))
 60	b.WriteString("\n" + md.H2("The same thing from a terminal"))
 61	b.WriteString("\nThis page is " + md.InlineCode("r/sys/users") +
 62		" read through " + md.InlineCode("vm/qeval") + ", with the follow-up questions already asked:\n")
 63	b.WriteString("\n" + md.LanguageCodeBlock("sh", qevalCommand("moul")))
 64	b.WriteString("\nTry " + md.Link("moul", "/r/moul/toolbox/usernames:moul") +
 65		", or paste an address into the box above.\n")
 66	return b.String()
 67}
 68
 69func renderResult(input string) string {
 70	var b strings.Builder
 71	b.WriteString(md.H1("Usernames"))
 72	b.WriteString("\n" + form())
 73
 74	data := lookup(input)
 75	if data == nil {
 76		b.WriteString("\n" + notFound(input))
 77		return b.String()
 78	}
 79
 80	t := ui.NewTable("Field", "Value")
 81	// RenderLink builds `[@name](/u/name)` with no escaping of its own, which
 82	// is safe only because r/sys/users validates a name against
 83	// ^[a-z][a-z0-9]*([_-][a-z0-9]+)*$ before storing it: no pipe, no bracket,
 84	// nothing a table cell or a link would notice.
 85	t.Row("Username", data.RenderLink(""))
 86	t.Row("Address", ui.AddrFull(data.Addr()))
 87	if current := CurrentName(input); current != "" {
 88		// One ui.Cell over the whole sentence, not a code span per name: a
 89		// code span escapes for running prose and leaves the `|` that would
 90		// split the row, and wrapping an already-escaped string again is the
 91		// double-wrap sanitize refuses to be idempotent about.
 92		t.Row("Note", ui.Cell("You asked for "+trim(input)+
 93			", which is an earlier name. The current one is "+current+"."))
 94	}
 95	t.Row("Canonical", ui.Cell(users.Canonicalize(data.Name())))
 96	b.WriteString("\n" + t.String())
 97
 98	if cmd := qevalCommand(input); cmd != "" {
 99		b.WriteString("\n" + md.LanguageCodeBlock("sh", cmd))
100	}
101	return b.String()
102}
103
104func notFound(input string) string {
105	var b strings.Builder
106	b.WriteString("Nothing registered under " + md.InlineCode(trim(input)) + ".\n")
107	b.WriteString("\n" + md.BulletList(notFoundHints(input)))
108	return b.String()
109}
110
111// notFoundHints says what "not found" means for this particular input, which
112// is three different things.
113func notFoundHints(input string) []string {
114	trimmed := trim(input)
115	if address(trimmed).IsValid() {
116		return []string{
117			"That is a valid address, so it exists on chain. It has no username.",
118			"Register one at " + md.Link("r/gnoland/users", "/r/gnoland/users"),
119		}
120	}
121	hints := []string{
122		"Nobody holds it, or the account was deleted: a deleted name keeps its tombstone and resolves to nothing.",
123	}
124	if owner := CanonicalOwner(trimmed); owner != "" {
125		hints = append(hints, "A lookalike is taken: "+md.InlineCode(owner)+
126			" already holds the canonical key "+md.InlineCode(users.Canonicalize(trimmed))+".")
127	} else if Taken(trimmed) {
128		hints = append(hints, "The name IS taken, by an account that was deleted or renamed. Registering it would still fail.")
129	}
130	return hints
131}
132
133func form() string {
134	return tb.NewQuery("lookup").Field("q", "username or g1 address").String()
135}
136
137// qevalCommand is the CLI call this page is the equivalent of, with the input
138// substituted. It returns "" for an input that cannot be put inside a fenced
139// code block safely: nothing escapes inside a fence, so the only safe move is
140// not to print one.
141func qevalCommand(input string) string {
142	arg := trim(input)
143	if !safeArg(arg) {
144		return ""
145	}
146	return "gnokey query vm/qeval -remote https://rpc.gno.land \\\n" +
147		"  -data 'gno.land/r/moul/toolbox/usernames.Resolve(\"" + arg + "\")'"
148}
149
150// safeArg reports whether s can be interpolated into a shell single-quoted
151// string inside a markdown code fence. Usernames and addresses are both well
152// inside this set, so a refusal only ever hides the hint, never an answer.
153func safeArg(s string) bool {
154	if s == "" || len(s) > maxInput {
155		return false
156	}
157	for i := 0; i < len(s); i++ {
158		c := s[i]
159		switch {
160		case c >= 'a' && c <= 'z':
161		case c >= 'A' && c <= 'Z':
162		case c >= '0' && c <= '9':
163		case c == '_' || c == '-' || c == '.':
164		default:
165			return false
166		}
167	}
168	return true
169}
170
171// trim bounds an echoed input. Everything downstream escapes it; this only
172// stops one query from rendering a page of arbitrary size.
173//
174// Cut on a rune boundary, not a byte one: s[:maxInput] on a multi-byte
175// character leaves half of it, and half a rune is not a character the escapers
176// downstream can do anything sensible with. Counting runes also makes the cap
177// mean the same thing for every alphabet.
178func trim(s string) string {
179	n := 0
180	for i := range s {
181		if n == maxInput {
182			return s[:i] + "…"
183		}
184		n++
185	}
186	return s
187}