Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/urlshort/v1"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914308
  max_deposit = "6000000ugnot"

urlshort.gno

// Package urlshort is a simple on-chain URL alias registry.
//
// Callers register an `alias -> url` mapping they own. An alias can only be
// claimed once; the owner may later update the target URL, but nobody else can
// overwrite an alias they do not own. A per-alias click counter is bumped every
// time the alias is resolved through Render("/<alias>").
package urlshort

import (
	"strings"

	"chain"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/nt/avl/v0"
)

// selfPath is this realm's own page. A root-relative link resolves against
// the domain, not the realm, so every link back into it names it in full.
const selfPath = "/r/moul/x/daily/urlshort/v1"

// entry is the persisted record for a single alias.
type entry struct {
	url    string
	owner  address
	note   string
	clicks int
}

// aliases maps alias (string) -> *entry, kept in an avl.Tree for deterministic
// iteration order in Render.
var aliases avl.Tree

// isAlphanumeric reports whether s is non-empty and made only of [0-9A-Za-z].
func isAlphanumeric(s string) bool {
	if s == "" {
		return false
	}
	for _, c := range s {
		switch {
		case c >= '0' && c <= '9':
		case c >= 'a' && c <= 'z':
		case c >= 'A' && c <= 'Z':
		default:
			return false
		}
	}
	return true
}

// Shorten registers `alias -> url` owned by the caller.
//
// Rules:
//   - alias must be non-empty and alphanumeric;
//   - url must be non-empty;
//   - if the alias is unclaimed, it is created owned by the caller;
//   - if it is already claimed by the caller, the url/note are updated;
//   - if it is claimed by someone else, the call aborts.
func Shorten(cur realm, alias string, url string, note string) {
	if !cur.IsCurrent() {
		panic("urlshort: spoofed realm")
	}
	if !isAlphanumeric(alias) {
		panic("alias must be non-empty and alphanumeric")
	}
	if url == "" {
		panic("url must be non-empty")
	}
	// The URL is rendered as an <autolink>, so it is checked here rather than
	// escaped there: http(s) only, and nothing that could close the brackets.
	if !safeURL(url) {
		panic("url must be http:// or https:// with no spaces or angle brackets")
	}

	caller := cur.Previous().Address()

	if v := aliases.Get(alias); v != nil {
		e := v.(*entry)
		if e.owner != caller {
			panic("alias already taken by another owner")
		}
		e.url = url
		e.note = note
		chain.Emit("AliasUpdated", "alias", alias, "owner", caller.String())
		return
	}

	e := &entry{url: url, owner: caller, note: note, clicks: 0}
	aliases.Set(alias, e)
	chain.Emit("AliasCreated", "alias", alias, "owner", caller.String())
}

// Remove deletes an alias owned by the caller. Aborts if the alias does not
// exist or the caller is not the owner.
func Remove(cur realm, alias string) {
	if !cur.IsCurrent() {
		panic("urlshort: spoofed realm")
	}
	v := aliases.Get(alias)
	if v == nil {
		panic("alias not found")
	}
	e := v.(*entry)
	caller := cur.Previous().Address()
	if e.owner != caller {
		panic("only the owner can remove an alias")
	}
	aliases.Remove(alias)
	chain.Emit("AliasRemoved", "alias", alias, "owner", caller.String())
}

// Lookup returns the target url for an alias and whether it exists. It is a
// read-only helper and does NOT increment the click counter.
func Lookup(alias string) (string, bool) {
	v := aliases.Get(alias)
	if v == nil {
		return "", false
	}
	return v.(*entry).url, true
}

// Render renders Markdown. The root path lists every alias; "/<alias>" shows a
// single alias detail and bumps its click counter.
func Render(path string) string {
	if path == "" || path == "/" {
		return renderIndex()
	}

	alias := strings.TrimPrefix(path, "/")
	v := aliases.Get(alias)
	if v == nil {
		return "# URL Shortener\n\nNo alias named " + md.InlineCode(alias) + ".\n\n[← all aliases](" + selfPath + ")\n"
	}

	e := v.(*entry)
	e.clicks++

	var b strings.Builder
	b.WriteString("# πŸ”— " + alias + "\n\n")
	b.WriteString("**Target:** <" + e.url + ">\n\n")
	b.WriteString("**Owner:** " + e.owner.String() + "\n\n")
	if e.note != "" {
		b.WriteString("**Note:** " + ui.Inline(e.note) + "\n\n")
	}
	b.WriteString("**Clicks:** " + itoa(e.clicks) + "\n\n")
	b.WriteString("[← all aliases](" + selfPath + ")\n")
	return b.String()
}

func renderIndex() string {
	var b strings.Builder
	b.WriteString("# πŸ”— URL Shortener\n\n")

	if aliases.Size() == 0 {
		b.WriteString("_No aliases registered yet._\n\n")
		b.WriteString("Call `Shorten(alias, url, note)` to register one.\n")
		return b.String()
	}

	b.WriteString("| Alias | Target | Owner | Clicks |\n")
	b.WriteString("|-------|--------|-------|--------|\n")
	aliases.Iterate("", "", func(key string, value interface{}) bool {
		e := value.(*entry)
		b.WriteString("| [" + key + "](" + selfPath + ":" + key + ") | <" + e.url + "> | " +
			ui.Addr(e.owner) + " | " + itoa(e.clicks) + " |\n")
		return false
	})
	b.WriteString("\nTotal aliases: " + itoa(aliases.Size()) + "\n")
	return b.String()
}

// itoa converts a non-negative int to its decimal string without importing
// strconv (kept minimal & deterministic).
func itoa(n int) string {
	if n == 0 {
		return "0"
	}
	neg := n < 0
	if neg {
		n = -n
	}
	var buf [20]byte
	i := len(buf)
	for n > 0 {
		i--
		buf[i] = byte('0' + n%10)
		n /= 10
	}
	if neg {
		i--
		buf[i] = '-'
	}
	return string(buf[i:])
}

// safeURL reports whether u can be written into a markdown autolink unescaped.
func safeURL(u string) bool {
	if !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
		return false
	}
	return !strings.ContainsAny(u, " \t\r\n<>`\\")
}

urlshort_test.gno

package urlshort

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

func TestIsAlphanumeric(t *testing.T) {
	cases := []struct {
		in   string
		want bool
	}{
		{"", false},
		{"abc", true},
		{"ABC123", true},
		{"a b", false},
		{"a-b", false},
		{"under_score", false},
		{"9", true},
	}
	for _, c := range cases {
		if got := isAlphanumeric(c.in); got != c.want {
			t.Errorf("isAlphanumeric(%q) = %v, want %v", c.in, got, c.want)
		}
	}
}

func TestItoa(t *testing.T) {
	cases := []struct {
		in   int
		want string
	}{
		{0, "0"},
		{7, "7"},
		{42, "42"},
		{1000, "1000"},
	}
	for _, c := range cases {
		if got := itoa(c.in); got != c.want {
			t.Errorf("itoa(%d) = %q, want %q", c.in, got, c.want)
		}
	}
}

func TestShortenAndRender(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	Shorten(cross(cur), "gno", "https://gno.land", "the chain")

	url, ok := Lookup("gno")
	uassert.True(t, ok, "alias should exist")
	uassert.Equal(t, "https://gno.land", url)

	// Detail render bumps the click counter.
	out := Render("/gno")
	uassert.True(t, strings.Contains(out, "https://gno.land"), "detail shows url")
	uassert.True(t, strings.Contains(out, "Clicks:** 1"), "click counted")

	// Index lists the alias.
	idx := Render("/")
	uassert.True(t, strings.Contains(idx, "[gno](/r/moul/x/daily/urlshort/v1:gno)"), "index lists alias")
}

func TestShortenOwnershipRules(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice2")
	bob := testutils.TestAddress("bob2")

	testing.SetRealm(testing.NewUserRealm(alice))
	Shorten(cross(cur), "mine", "https://a.example", "")

	// Bob cannot overwrite alice's alias.
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "alias already taken by another owner", func() {
		Shorten(cross(cur), "mine", "https://b.example", "")
	})

	// Alice can update her own.
	testing.SetRealm(testing.NewUserRealm(alice))
	Shorten(cross(cur), "mine", "https://a2.example", "updated")
	url, _ := Lookup("mine")
	uassert.Equal(t, "https://a2.example", url)

	// Invalid alias aborts.
	uassert.AbortsWithMessage(t, cur, "alias must be non-empty and alphanumeric", func() {
		Shorten(cross(cur), "bad alias", "https://x.example", "")
	})

	// Empty url aborts.
	uassert.AbortsWithMessage(t, cur, "url must be non-empty", func() {
		Shorten(cross(cur), "okalias", "", "")
	})
}

func TestRemoveRules(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice3")
	bob := testutils.TestAddress("bob3")

	testing.SetRealm(testing.NewUserRealm(alice))
	Shorten(cross(cur), "rm", "https://rm.example", "")

	// Bob cannot remove alice's alias.
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "only the owner can remove an alias", func() {
		Remove(cross(cur), "rm")
	})

	// Alice removes her own.
	testing.SetRealm(testing.NewUserRealm(alice))
	Remove(cross(cur), "rm")
	_, ok := Lookup("rm")
	uassert.False(t, ok, "alias should be gone")
}

zz_escape_test.gno

package urlshort

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/nt/uassert/v0"
)

// The note is escaped, and a target that could close its <autolink>, or is
// not http(s), is refused when it is written.
func TestNoteIsEscapedAndTargetChecked(cur realm, t *testing.T) {
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("escaper")))
	Shorten(cross(cur), "esc", "https://ok.example", "[claim](https://evil.example)")
	page := Render("esc")
	uassert.False(t, strings.Contains(page, "[claim](https://evil.example)"), page)
	uassert.AbortsContains(t, cur, "url must be http", func() { Shorten(cross(cur), "esc2", "https://a.example> [evil](https://b.example)", "") })
	uassert.AbortsContains(t, cur, "url must be http", func() { Shorten(cross(cur), "esc3", "javascript:alert(1)", "") })
}

// A path that names nothing is echoed back on the not-found page. It is the
// visitor's text, so a backtick in it must not close a code span and let a
// link through.
func TestNotFoundPathIsEscaped(t *testing.T) {
	out := Render("x` [claim](https://evil.example) `")
	// Still there, but inside a span md.InlineCode widened past its backticks.
	uassert.True(t, strings.Contains(out, md.InlineCode("x` [claim](https://evil.example) `")), out)
}