diff --git a/modules/i3/cmd/i3-tools/main.go b/modules/i3/cmd/i3-tools/main.go index a8fd4a857..82de29aa6 100644 --- a/modules/i3/cmd/i3-tools/main.go +++ b/modules/i3/cmd/i3-tools/main.go @@ -53,7 +53,7 @@ func machine() *i3 { if state == "" { state = filepath.Join(home, ".local", "state") } - t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts")} + t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), handAct: liveHandAct} t.socket = func() (string, error) { runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid())) i3sock := "" @@ -83,6 +83,16 @@ func tools(t *i3) []stdio.Tool { Input: desktop.Schema(map[string]any{"force": desktop.Flag("reload even when the check finds errors")}), Run: call(t.reload), }, + { + Name: "node-display-session.open", + Description: "Open an http or https address in the person's default browser, for any caller over the bus " + + "(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " + + "too long once encoded, no graphical session or no default program for the scheme; the opener's " + + "failure is refused naming its status. Answers once the opener has started: opened within its bound, " + + "or opening when it still runs. Every call is an act, recorded in the log of acts done by hand.", + Input: desktop.Schema(map[string]any{"address": desktop.Str("the http or https address to open")}, "address"), + Run: call(t.open), + }, { Name: "node-display-session.workspaces", Description: "The session's workspaces: number, name, output, and whether each is visible, focused or urgent.", diff --git a/modules/i3/cmd/i3-tools/manifest_test.go b/modules/i3/cmd/i3-tools/manifest_test.go index d41fb7adc..5be02a970 100644 --- a/modules/i3/cmd/i3-tools/manifest_test.go +++ b/modules/i3/cmd/i3-tools/manifest_test.go @@ -17,6 +17,7 @@ import ( type manifest struct { Capabilities []string `json:"capabilities"` Requires []string `json:"requires"` + Invokes []string `json:"invokes"` Claims []struct { Name string `json:"name"` Scope string `json:"scope"` @@ -82,7 +83,7 @@ func resource(t *testing.T, m manifest, id string) map[string]any { func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) { m := readManifest(t) - if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows" { + if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows,open" { t.Fatalf("%+v", m.Claims) } if strings.Join(m.Requires, ",") != "x11-display" { @@ -97,7 +98,7 @@ func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) { t.Errorf("the seat's %s is not served", v) } } - if len(served) != len(m.Tools)+3 { + if len(served) != len(m.Tools)+4 { t.Fatalf("served %d, listed %d", len(served), len(m.Tools)) } for _, n := range m.Tools { @@ -175,6 +176,23 @@ func TestTheConfigurationIsTheModulesFileImprovedAndEndsWithTheDropIns(t *testin } } +// open is an act (design 08 sign-in-page §29, DQ-7): the manifest invokes the hand-act log, the +// package the opener needs is present (ADR 0303 §2), and open is among node-display-session's +// served verbs. +func TestOpenIsAnActWithItsPackageAndInvoke(t *testing.T) { + m := readManifest(t) + if strings.Join(m.Invokes, ",") != "seat:mesh-hand-acts.hand-act" { + t.Fatalf("invokes: %v", m.Invokes) + } + served := map[string]bool{} + for _, v := range m.Claims[0].Serves { + served[v] = true + } + if !served["open"] { + t.Fatal("node-display-session does not serve open") + } +} + func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) { m := readManifest(t) r := resource(t, m, "session") @@ -194,7 +212,7 @@ func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) { pkgs[x["package"].(string)] = true } } - if !pkgs["i3-wm"] || !pkgs["dex"] || len(pkgs) != 2 { + if !pkgs["i3-wm"] || !pkgs["dex"] || !pkgs["xdg-utils"] || len(pkgs) != 3 { t.Fatalf("%v", pkgs) } a := m.Build.Artifacts[0] diff --git a/modules/i3/cmd/i3-tools/open.go b/modules/i3/cmd/i3-tools/open.go new file mode 100644 index 000000000..b48939e68 --- /dev/null +++ b/modules/i3/cmd/i3-tools/open.go @@ -0,0 +1,229 @@ +// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https +// address in the person's default browser, outside i3's own IPC (which hands a shell a command +// line); this verb takes the address as one argument, through the account's own program chooser +// (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act +// (ADR 0565 §10): each call that is acted on is written to the log of acts done by hand. +package main + +import ( + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + stdio "git.novox.be/novox/mesh-sdk/go" + + "i3/internal/desktop" +) + +// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a +// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener +// is left to go on and the answer says opening. A test shortens it with the i3's openBound field. +const defaultOpenTimeout = 10 * time.Second + +// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3). +const openMaxAddress = 2048 + +// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter, +// ended by a colon. +var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`) + +// openKept are the characters open's encoding never touches, beside the unreserved ones (letters, +// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is +// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9). +const openKept = "-._~:/?#[]@&=+%" + +// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme +// other than http or https, no scheme (a file path), no host. +func checkAddressShape(address string) (scheme string, err error) { + m := schemePattern.FindStringSubmatch(address) + if m == nil { + return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address) + } + scheme = strings.ToLower(m[1]) + if scheme != "http" && scheme != "https" { + return "", fmt.Errorf("a scheme other than http or https: %s", scheme) + } + afterScheme := address[len(m[0]):] + if !strings.HasPrefix(afterScheme, "//") { + return "", fmt.Errorf("no host: %s has no // after its scheme", scheme) + } + rest := afterScheme[2:] + end := strings.IndexAny(rest, "/?#") + authority := rest + if end >= 0 { + authority = rest[:end] + } + if at := strings.LastIndex(authority, "@"); at >= 0 { + authority = authority[at+1:] + } + if authority == "" { + return "", fmt.Errorf("no host") + } + return scheme, nil +} + +// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs +// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form. +// Nothing is refused for a character, and the result is never read by a shell. +func encodeAddress(address string) string { + var b strings.Builder + for i := 0; i < len(address); i++ { + c := address[i] + switch { + case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9': + b.WriteByte(c) + case strings.IndexByte(openKept, c) >= 0: + b.WriteByte(c) + default: + fmt.Fprintf(&b, "%%%02X", c) + } + } + return b.String() +} + +// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason: +// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is +// none. +func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) { + res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme) + name := strings.TrimSpace(res.Stdout) + if !res.OK() || name == "" { + return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme) + } + return name, nil +} + +// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data +// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes +// and arguments. +func entryCommand(entry string) string { + for _, dir := range xdgDataDirs() { + b, err := os.ReadFile(filepath.Join(dir, "applications", entry)) + if err != nil { + continue + } + inEntry := false + for _, line := range strings.Split(string(b), "\n") { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "["): + inEntry = line == "[Desktop Entry]" + case inEntry: + if exec, ok := strings.CutPrefix(line, "Exec="); ok { + if fields := strings.Fields(exec); len(fields) > 0 { + return fields[0] + } + return "" + } + } + } + } + return "" +} + +// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the +// system's (XDG_DATA_DIRS, or its default). +func xdgDataDirs() []string { + dirs := []string{os.Getenv("XDG_DATA_HOME")} + if dirs[0] == "" { + dirs[0] = filepath.Join(desktop.Home(), ".local", "share") + } + extra := os.Getenv("XDG_DATA_DIRS") + if extra == "" { + extra = "/usr/local/share:/usr/share" + } + for _, d := range strings.Split(extra, ":") { + if d != "" { + dirs = append(dirs, d) + } + } + return dirs +} + +// open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's +// default browser for the scheme, and answers once the opener has started. +func (t *i3) open(ctx context.Context, a desktop.Args) (any, error) { + caller := stdio.CallerOf(map[string]any(a)) + address, err := a.Text("address") + if err != nil { + return nil, err + } + scheme, err := checkAddressShape(address) + if err != nil { + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + encoded := encodeAddress(address) + if len(encoded) > openMaxAddress { + err := fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + + s, err := t.d.Find() + if err != nil { + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + env := s.Env(t.d.Base) + + program, err := defaultProgram(ctx, t.d, env, scheme) + if err != nil { + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + + bound := t.openBound + if bound == 0 { + bound = defaultOpenTimeout + } + runCtx, cancel := context.WithTimeout(ctx, bound) + defer cancel() + res := t.d.Run(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) + + if !res.OK() && !res.TimedOut { + reason := res.Err().Error() + t.journalOpen(address, "refused", reason) + return nil, fmt.Errorf("the opener failed: %s", reason) + } + + started := "opened" + if res.TimedOut { + started = "opening" + } + command := entryCommand(program) + t.journalOpen(address, started, program) + t.recordHandAct(caller, encoded, program, started) + return map[string]any{"address": encoded, "program": program, "command": command, "started": started}, nil +} + +// journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14): +// the address, opened or refused, and the program or the reason. +func (t *i3) journalOpen(address, outcome, programOrReason string) { + fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason) +} + +// recordHandAct writes open's call to the log of acts done by hand (design 08 sign-in-page §29; +// ADR 0565 §10): open is an act, so every call that is acted on (never a refusal before the +// opener ran) is recorded with its caller and why. +func (t *i3) recordHandAct(caller, address, program, started string) { + if t.handAct == nil { + return + } + what := fmt.Sprintf("%s %s in %s", started, address, program) + why := fmt.Sprintf("asked by %s", caller) + if err := t.handAct(what, why); err != nil { + fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err) + } +} + +// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module +// (design 08 sign-in-page §29). +func liveHandAct(what, why string) error { + _, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"}) + return err +} diff --git a/modules/i3/cmd/i3-tools/open_test.go b/modules/i3/cmd/i3-tools/open_test.go new file mode 100644 index 000000000..f36f139b5 --- /dev/null +++ b/modules/i3/cmd/i3-tools/open_test.go @@ -0,0 +1,224 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "i3/internal/desktop" +) + +// runCall records one call the stood-in opener saw, so a test can check the exact argv it was +// handed (design 08 sign-in-page §29, R2-9: one argument, no shell). +type runCall struct { + name string + args []string +} + +// stubOpener builds an i3 whose session is found (unless find answers an error) and whose +// commands are answered from answers, keyed by the command's name ("xdg-mime", "systemd-run"); +// every call is recorded in calls. +func stubOpener(t *testing.T, find func() (*desktop.Session, error), answers map[string]desktop.Result) (*i3, *[]runCall) { + t.Helper() + calls := &[]runCall{} + run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + *calls = append(*calls, runCall{name, args}) + res, ok := answers[name] + if !ok { + t.Fatalf("unexpected command %s %v", name, args) + } + if res.TimedOut { + <-ctx.Done() + return desktop.Result{TimedOut: true} + } + return res + } + return &i3{d: desktop.Desk{Find: find, Run: run}, openBound: 50 * time.Millisecond}, calls +} + +func foundSession() (*desktop.Session, error) { + return &desktop.Session{}, nil +} + +func writeDesktopEntry(t *testing.T, entry, execLine string) { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_DATA_HOME", dir) + apps := filepath.Join(dir, "applications") + if err := os.MkdirAll(apps, 0o755); err != nil { + t.Fatal(err) + } + text := "[Desktop Entry]\nType=Application\nName=Browser\nExec=" + execLine + "\n" + if err := os.WriteFile(filepath.Join(apps, entry), []byte(text), 0o644); err != nil { + t.Fatal(err) + } +} + +// 935/I-1: every scheme but http and https, and a file path, is refused. +func TestOpenRefusesEveryOtherScheme(t *testing.T) { + x, calls := stubOpener(t, foundSession, map[string]desktop.Result{}) + for _, address := range []string{ + "/etc/passwd", // no scheme: a file path + "file:///etc/passwd", // a scheme other than http or https + "ftp://example.net/f", // a scheme other than http or https + "mailto:a@example.net", // a scheme other than http or https, no // + "http://", // no host + "https:///path", // no host + } { + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil { + t.Errorf("%s: not refused", address) + } + } + if len(*calls) != 0 { + t.Fatalf("a refused address never reaches the opener: %v", *calls) + } +} + +// 935/I-1: an address over 2048 bytes once encoded is refused. +func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) { + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{}) + address := "https://example.net/" + strings.Repeat("a", 2048) + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil { + t.Fatal("not refused") + } +} + +// 935/I-1: with no graphical session it refuses, as its other tools answer. +func TestOpenRefusesWithNoGraphicalSession(t *testing.T) { + x, _ := stubOpener(t, func() (*desktop.Session, error) { + return nil, &desktop.NoSession{Reason: "none"} + }, map[string]desktop.Result{}) + _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if !desktop.IsNoSession(err) { + t.Fatalf("%v", err) + } +} + +// 935/I-1: no default program for the scheme is refused. +func TestOpenRefusesWithNoDefaultProgram(t *testing.T) { + x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: ""}, + }) + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil { + t.Fatal("not refused") + } + for _, c := range *calls { + if c.name == "systemd-run" { + t.Fatal("the opener never runs with no default program") + } + } +} + +// 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its +// UTF-8 form, and the address reaches the opener as one argument, never a shell command line. +func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 0}, + }) + address := `https://example.net/a'b;c d$(e),f"g` + got, err := run(t, x, "node-display-session.open", map[string]any{"address": address}) + if err != nil { + t.Fatal(err) + } + want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g` + answer := got.(map[string]any) + if answer["address"] != want { + t.Fatalf("got %q, want %q", answer["address"], want) + } + var last runCall + for _, c := range *calls { + if c.name == "systemd-run" { + last = c + } + } + if len(last.args) == 0 || last.args[len(last.args)-1] != want { + t.Fatalf("the address is not the opener's last, whole argument: %v", last.args) + } + for _, a := range last.args { + if strings.Contains(a, "'") || strings.Contains(a, ";") || strings.Contains(a, " ") { + t.Fatalf("an argument still carries a shell character: %q", a) + } + } +} + +// 935/I-3: an opener that fails is refused with its status and names no program. +func TestOpenRefusesWhenTheOpenerFails(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 1, Stderr: "no such unit"}, + }) + _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if err == nil || !strings.Contains(err.Error(), "no such unit") { + t.Fatalf("%v", err) + } +} + +// 935/I-3: an opener that ends well answers opened with the program. +func TestOpenAnswersOpenedWithTheProgram(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 0}, + }) + got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if err != nil { + t.Fatal(err) + } + answer := got.(map[string]any) + if answer["started"] != "opened" || answer["program"] != "browser.desktop" || answer["command"] != "firefox" { + t.Fatalf("%+v", answer) + } +} + +// 935/I-3: one still running at its bound answers opening, with the program (H-M2: the answer +// names the program only once the opener started). +func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {TimedOut: true}, + }) + got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if err != nil { + t.Fatal(err) + } + answer := got.(map[string]any) + if answer["started"] != "opening" || answer["program"] != "browser.desktop" { + t.Fatalf("%+v", answer) + } +} + +// DQ-7: each call that is acted on writes one act to the log of acts done by hand, with its caller +// and why; a refusal before the opener ran writes none. +func TestOpenWritesOneActDoneByHand(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 0}, + }) + var recorded []string + x.handAct = func(what, why string) error { + recorded = append(recorded, what+"|"+why) + return nil + } + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err != nil { + t.Fatal(err) + } + if len(recorded) != 1 || !strings.Contains(recorded[0], "https://example.net") { + t.Fatalf("%v", recorded) + } + + recorded = nil + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil { + t.Fatal("expected a refusal") + } + if len(recorded) != 0 { + t.Fatalf("a refusal before the opener ran writes no act: %v", recorded) + } +} diff --git a/modules/i3/cmd/i3-tools/tools.go b/modules/i3/cmd/i3-tools/tools.go index 0142b6963..5835985a5 100644 --- a/modules/i3/cmd/i3-tools/tools.go +++ b/modules/i3/cmd/i3-tools/tools.go @@ -19,6 +19,12 @@ type i3 struct { configDir string layouts string watcher *Watcher + // handAct writes one call of open to the log of acts done by hand (design 08 sign-in-page §29); + // nil in a test that does not check it. + handAct func(what, why string) error + // openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens + // it so a still-running opener is seen without waiting out the real bound. + openBound time.Duration } func (t *i3) ask(kind uint32, payload string, out any) error { diff --git a/modules/i3/module.json b/modules/i3/module.json index 315b77deb..02dafc062 100644 --- a/modules/i3/module.json +++ b/modules/i3/module.json @@ -16,10 +16,14 @@ "serves": [ "reload", "workspaces", - "windows" + "windows", + "open" ] } ], + "invokes": [ + "seat:mesh-hand-acts.hand-act" + ], "tools": [ "i3_focus", "i3_move", @@ -68,6 +72,11 @@ "type": "package", "package": "dex" }, + { + "id": "package-xdg-utils", + "type": "package", + "package": "xdg-utils" + }, { "id": "config-dir", "type": "directory",