// 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"
"unicode"
)
// 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 strings.ContainsAny(n.Cmd, "\r\n") {
return errors.New("next has a cmd with a line break")
}
if n.Open != "" {
if err := checkOpen(n.Open, origin); err != nil {
return err
}
}
return nil
}
// Safe is n with whatever Validate refuses taken out: an open that is not
// a page of the forge, a cmd with a line break. A server builds every next
// it sends through it, so a bad one is never on the wire.
func (n *Next) Safe(origin string) *Next {
c := *n
if c.Open != "" && checkOpen(c.Open, origin) != nil {
c.Open = ""
}
if strings.ContainsAny(c.Cmd, "\r\n") {
c.Cmd = ""
}
return &c
}
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 strings.ContainsAny(n.Cmd, "\r\n") {
fmt.Fprintf(w, " run (not shown: the command has line breaks)\n")
} else 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), format characters (bidi marks and
// overrides, zero-width), and the line and paragraph separators 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) || r == 0x2028 || r == 0x2029 || unicode.Is(unicode.Cf, r) {
return -1
}
return r
}, s)
}