Skip to content
quarry Artifact [51b57599f7]
Login

Artifact [51b57599f7]

Artifact 51b57599f7559a7388e15fd84ac74318390a3e09efd49387bfbc320803bc8a3e:


// Package nextstep is the one shape of "next" (RFC 0033): the step a
// refusal or a client envelope points at. The forge's refusals and the
// client's envelopes share it, so a field has one name and one meaning
// on both sides. It imports nothing of the server, so the client may.
package nextstep

import (
	"errors"
	"fmt"
	"io"
	"net/url"
	"regexp"
	"strings"
)

// Next is the step to take. Say is one sentence and is always present.
// Open is a page of the forge, to be done signed in at a browser. Cmd is
// the client command for the step and Call the API call that takes it;
// either is left out when there is none. Ask is true only where the same
// call sent with Quarry-Ask would be admitted. Help is an anchor in
// /llms.txt, never its top.
type Next struct {
	Say  string `json:"say"`
	Call string `json:"call,omitempty"`
	Cmd  string `json:"cmd,omitempty"`
	Open string `json:"open,omitempty"`
	Ask  bool   `json:"ask"`
	Help string `json:"help,omitempty"`
}

// Validate says what is wrong with n for the forge at origin: no
// sentence, or an open that is not a page of that forge. origin is the
// forge's address ("https://host"), or "" for a forge that names a page
// by its path alone.
func (n *Next) Validate(origin string) error {
	if n == nil {
		return errors.New("no next")
	}
	if strings.TrimSpace(n.Say) == "" {
		return errors.New("next has no say")
	}
	if n.Open != "" {
		if err := checkOpen(n.Open, origin); err != nil {
			return err
		}
	}
	return nil
}

func checkOpen(open, origin string) error {
	if Clean(open) != open {
		return fmt.Errorf("open %q carries control characters", open)
	}
	if strings.HasPrefix(open, "/") && !strings.HasPrefix(open, "//") && !strings.Contains(open, `\`) {
		return nil
	}
	u, err := url.Parse(open)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return fmt.Errorf("open %q is neither a path nor an http(s) address", open)
	}
	if origin == "" {
		return fmt.Errorf("open %q is absolute but the forge's origin is not known", open)
	}
	base, err := url.Parse(origin)
	if err != nil || !SameOrigin(u, base) {
		return fmt.Errorf("open %q is not the forge's origin", open)
	}
	return nil
}

// Render writes n as a person reads it: the sentence after lead, then
// the page to open and the command to run, each on its own line. Every
// field is stripped of terminal escapes. An open that is not a page of
// base is left out, so a forge cannot send a person to another site; a
// nil base accepts paths alone.
func (n *Next) Render(w io.Writer, lead string, base *url.URL) {
	if n == nil {
		return
	}
	if n.Say != "" {
		fmt.Fprintf(w, "%s%s\n", lead, Clean(n.Say))
	}
	if open := n.openFor(base); open != "" {
		fmt.Fprintf(w, "  open   %s\n", Clean(open))
	}
	if n.Cmd != "" {
		fmt.Fprintf(w, "  run    %s\n", Clean(n.Cmd))
	}
}

func (n *Next) openFor(base *url.URL) string {
	if n.Open == "" {
		return ""
	}
	origin := ""
	if base != nil {
		origin = base.Scheme + "://" + base.Host
	}
	if checkOpen(n.Open, origin) != nil {
		return ""
	}
	return n.Open
}

// SameOrigin is whether two URLs name one scheme, host and port, with
// the case of the host and a default port ignored.
func SameOrigin(a, b *url.URL) bool {
	port := func(u *url.URL) string {
		if p := u.Port(); p != "" {
			return p
		}
		if asciiLower(u.Scheme) == "https" {
			return "443"
		}
		return "80"
	}
	return a.Hostname() != "" && asciiLower(a.Scheme) == asciiLower(b.Scheme) &&
		asciiLower(a.Hostname()) == asciiLower(b.Hostname()) && port(a) == port(b)
}

// asciiLower folds ASCII only: strings.EqualFold folds Unicode, so a
// host spelled with the Kelvin sign would match one spelled with k.
func asciiLower(s string) string {
	b := []byte(s)
	for i, c := range b {
		if c >= 'A' && c <= 'Z' {
			b[i] = c + 32
		}
	}
	return string(b)
}

var terminalEscape = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b.?`)

// Clean makes a server string safe to print: escape sequences and
// control characters (C0, DEL, C1) are dropped, so a forge cannot write
// to the terminal.
func Clean(s string) string {
	s = terminalEscape.ReplaceAllString(s, "")
	return strings.Map(func(r rune) rune {
		if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) {
			return -1
		}
		return r
	}, s)
}