From 4f7143c4ccd36ee5faac8c682e6db3c39ae45924 Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:33:27 +0200 Subject: [PATCH 01/10] chore: start nodkey try --telegram (#125) Co-Authored-By: Claude Opus 5.5 From dcabc50aeb24d955daa77423762003d8a37c326a Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:36:24 +0200 Subject: [PATCH 02/10] feat: telegram pairing from /start, a token in memory, and a message prefix (#125) Co-Authored-By: Claude Opus 5.5 --- internal/telegram/api.go | 24 ++++++ internal/telegram/pair.go | 122 +++++++++++++++++++++++++++++ internal/telegram/pair_test.go | 138 +++++++++++++++++++++++++++++++++ internal/telegram/telegram.go | 18 ++++- 4 files changed, 301 insertions(+), 1 deletion(-) create mode 100644 internal/telegram/pair.go create mode 100644 internal/telegram/pair_test.go diff --git a/internal/telegram/api.go b/internal/telegram/api.go index 983ac62..ca26588 100644 --- a/internal/telegram/api.go +++ b/internal/telegram/api.go @@ -118,6 +118,9 @@ type client struct { http *http.Client base string token botToken + // prefix is HTML that goes before the text of every message that + // the client sends or edits; "" for none. + prefix string // The times and the sleep are fields, so tests can make them short. timeout time.Duration // one try of a method other than getUpdates @@ -258,8 +261,25 @@ func (c *client) call(ctx context.Context, method string, params, result any) er } } +// withPrefix returns params with c.prefix before the text of a message. +func (c *client) withPrefix(params any) any { + if c.prefix == "" { + return params + } + switch v := params.(type) { + case sendMessageParams: + v.Text = c.prefix + v.Text + return v + case editMessageTextParams: + v.Text = c.prefix + v.Text + return v + } + return params +} + // callOnce makes one call of method. timeout bounds the whole call. func (c *client) callOnce(ctx context.Context, method string, params, result any, timeout time.Duration) *apiError { + params = c.withPrefix(params) if err := ctx.Err(); err != nil { return &apiError{method: method, reason: "stopped before the call", err: err} } @@ -523,6 +543,10 @@ type ( user struct { ID int64 `json:"id"` + // FirstName and Username are read only by Pair, to show who sent + // /start. + FirstName string `json:"first_name"` + Username string `json:"username"` } message struct { diff --git a/internal/telegram/pair.go b/internal/telegram/pair.go new file mode 100644 index 0000000..8c4dd61 --- /dev/null +++ b/internal/telegram/pair.go @@ -0,0 +1,122 @@ +package telegram + +import ( + "bytes" + "context" + "errors" + "fmt" + "regexp" + "strings" + "unicode" +) + +// pairCodePattern is the form of a pairing code: what Telegram allows in +// the start parameter of a link. +var pairCodePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,64}$`) + +// Pairing finds the Telegram user ID of the approver from a /start +// message, so that no one has to look it up by hand. nodkey try uses it. +type Pairing struct { + api *client + // Bot is the user name of the bot, without "@". + Bot string +} + +// Paired is the person who sent /start with the code. +type Paired struct { + UserID int64 + // Name is the first name and the user name, as Telegram has them, + // with every character that is not printable replaced. + Name string +} + +// NewPairing checks the token with getMe and returns a Pairing for its +// bot. Errors never show the token. +func NewPairing(ctx context.Context, token []byte) (*Pairing, error) { + return newPairing(ctx, token, defaultBaseURL) +} + +func newPairing(ctx context.Context, token []byte, base string) (*Pairing, error) { + t, err := parseToken(bytes.Clone(token)) + if err != nil { + return nil, err + } + api := newClient(t, base) + var me struct { + Username string `json:"username"` + } + if err := api.call(ctx, "getMe", struct{}{}, &me); err != nil { + return nil, err + } + if !botNamePattern.MatchString(me.Username) { + return nil, errors.New("telegram: getMe: the bot has no valid user name") + } + return &Pairing{api: api, Bot: me.Username}, nil +} + +// botNamePattern is the form of a bot's user name. +var botNamePattern = regexp.MustCompile(`^[A-Za-z0-9_]{5,32}$`) + +// Link is the link that opens the bot and sends /start with code. +func (p *Pairing) Link(code string) string { + return "https://t.me/" + p.Bot + "?start=" + code +} + +// Wait waits for the message "/start code" in a private chat with the +// bot, and returns who sent it. Every other message is skipped. It ends +// with ErrPollConflict when another program polls the same bot. +func (p *Pairing) Wait(ctx context.Context, code string) (Paired, error) { + if !pairCodePattern.MatchString(code) { + return Paired{}, errors.New("telegram: the pairing code is not valid") + } + want := "/start " + code + var offset int64 + for { + if err := ctx.Err(); err != nil { + return Paired{}, err + } + updates, e := p.api.getUpdates(ctx, offset) + if e != nil { + switch { + case ctx.Err() != nil: + return Paired{}, ctx.Err() + case !e.temporary: + return Paired{}, e + } + if err := p.api.sleep(ctx, pollFirstBackoff); err != nil { + return Paired{}, err + } + continue + } + for _, u := range updates { + offset = max(offset, u.UpdateID+1) + m := u.Message + if u.malformed || m == nil || m.Chat.Type != "private" || m.From.ID <= 0 || + m.Chat.ID != m.From.ID || m.Text != want { + continue + } + name := cleanName(m.From.FirstName) + if m.From.Username != "" { + name += " (@" + cleanName(m.From.Username) + ")" + } + return Paired{UserID: m.From.ID, Name: name}, nil + } + } +} + +// cleanName caps s and replaces each character that is not printable. +func cleanName(s string) string { + s = strings.Map(func(r rune) rune { + if unicode.IsPrint(r) { + return r + } + return '?' + }, s) + if r := []rune(s); len(r) > 64 { + s = string(r[:64]) + "…" + } + return s +} + +// Format hides the Pairing, so that no fmt verb prints the token. +func (*Pairing) Format(f fmt.State, _ rune) { _, _ = f.Write([]byte("telegram.Pairing")) } diff --git a/internal/telegram/pair_test.go b/internal/telegram/pair_test.go new file mode 100644 index 0000000..c083542 --- /dev/null +++ b/internal/telegram/pair_test.go @@ -0,0 +1,138 @@ +package telegram + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "testing" + "time" +) + +const testPairCode = "abcdefghij0123456789" + +// newTestPairing returns a Pairing for the fake f, after getMe. +func newTestPairing(t *testing.T, f *fakeTelegram) *Pairing { + t.Helper() + f.reply("getMe", http.StatusOK, `{"ok":true,"result":{"id":42,"is_bot":true,"username":"try_test_bot"}}`) + p, err := newPairing(t.Context(), []byte(f.token+"\n"), f.srv.URL) + if err != nil { + t.Fatal(err) + } + p.api.sleep = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } + return p +} + +func startUpdate(id int64, chatID, fromID int64, chatType, text string) string { + return fmt.Sprintf(`{"update_id":%d,"message":{"message_id":1,"chat":{"id":%d,"type":%q},`+ + `"from":{"id":%d,"first_name":"Ann\u001b[31m","username":"ann_x"},"text":%q}}`, id, chatID, chatType, fromID, text) +} + +// Only "/start CODE" from a private chat with its sender counts. +func TestPairingWait(t *testing.T) { + f := newFake(t) + p := newTestPairing(t, f) + if got, want := p.Link(testPairCode), "https://t.me/try_test_bot?start="+testPairCode; got != want { + t.Fatalf("link %q, want %q", got, want) + } + f.addRawUpdate(1, startUpdate(1, 7, 7, "private", "/start wrong-code-0123456789")) + f.addRawUpdate(2, startUpdate(2, -100, 8, "group", "/start "+testPairCode)) + f.addRawUpdate(3, startUpdate(3, 9, 10, "private", "/start "+testPairCode)) + f.addRawUpdate(4, startUpdate(4, 11, 11, "private", "/start "+testPairCode+" x")) + f.addRawUpdate(5, `{"update_id":5,"message":"not an object"}`) + f.addRawUpdate(6, startUpdate(6, 12, 12, "private", "/start "+testPairCode)) + got, err := p.Wait(t.Context(), testPairCode) + if err != nil { + t.Fatal(err) + } + if got.UserID != 12 || got.Name != "Ann?[31m (@ann_x)" { + t.Fatalf("paired %+v, want user 12, a clean name", got) + } +} + +func TestPairingDeny(t *testing.T) { + t.Run("bad code", func(t *testing.T) { + p := newTestPairing(t, newFake(t)) + for _, code := range []string{"", "short", "abc def ghi jkl mno", strings.Repeat("a", 65)} { + if _, err := p.Wait(t.Context(), code); err == nil { + t.Errorf("code %q: no error", code) + } + } + }) + t.Run("conflict", func(t *testing.T) { + f := newFake(t) + p := newTestPairing(t, f) + f.reply("getUpdates", http.StatusConflict, `{"ok":false,"error_code":409,"description":"Conflict"}`) + if _, err := p.Wait(t.Context(), testPairCode); !errors.Is(err, ErrPollConflict) { + t.Fatalf("Wait: %v, want ErrPollConflict", err) + } + }) + t.Run("token refused", func(t *testing.T) { + f := newFake(t) + _, err := newPairing(t.Context(), []byte(newCanaryToken(t)), f.srv.URL) + if !errors.Is(err, ErrTokenRefused) { + t.Fatalf("newPairing: %v, want ErrTokenRefused", err) + } + }) + t.Run("no bot name", func(t *testing.T) { + f := newFake(t) + f.reply("getMe", http.StatusOK, `{"ok":true,"result":{"id":42,"username":"bad name/x"}}`) + if _, err := newPairing(t.Context(), []byte(f.token), f.srv.URL); err == nil { + t.Fatal("no error") + } + }) + t.Run("not a token", func(t *testing.T) { + if _, err := NewPairing(t.Context(), []byte("not a token")); err == nil { + t.Fatal("no error") + } + }) + t.Run("cancel", func(t *testing.T) { + p := newTestPairing(t, newFake(t)) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := p.Wait(ctx, testPairCode); !errors.Is(err, context.Canceled) { + t.Fatalf("Wait: %v", err) + } + }) +} + +// The prefix goes, escaped, before every message and edit. +func TestPrefix(t *testing.T) { + f := newFake(t) + read := func(string) ([]byte, error) { return []byte(f.token), nil } + a, err := newApprover(testTelegramConfig(), Options{Prefix: "TRY · "}, read, f.srv.URL) + if err != nil { + t.Fatal(err) + } + if err := a.Inform(t.Context(), "hello"); err != nil { + t.Fatal(err) + } + if got := f.callsOf("sendMessage")[0].str("text"); !strings.HasPrefix(got, "TRY <MODE> · ") { + t.Fatalf("text %q", got) + } + edit, ok := a.api.withPrefix(editMessageTextParams{Text: "x"}).(editMessageTextParams) + if !ok || edit.Text != "TRY <MODE> · x" { + t.Fatalf("edit %+v", edit) + } + if got, ok := a.api.withPrefix(getUpdatesParams{Offset: 3}).(getUpdatesParams); !ok || got.Offset != 3 { + t.Fatalf("getUpdates params changed: %+v", got) + } +} + +// NewWithToken keeps its own copy of the token, and checks it. +func TestNewWithToken(t *testing.T) { + if _, err := NewWithToken(testTelegramConfig(), []byte("not a token"), Options{}); err == nil { + t.Fatal("no error for a bad token") + } + token := []byte(newCanaryToken(t)) + want := string(token) + a, err := NewWithToken(testTelegramConfig(), token, Options{}) + if err != nil { + t.Fatal(err) + } + clear(token) + if a.api.token.value != want { + t.Fatal("the Approver does not hold its own copy of the token") + } +} diff --git a/internal/telegram/telegram.go b/internal/telegram/telegram.go index 05f2c91..dc2e483 100644 --- a/internal/telegram/telegram.go +++ b/internal/telegram/telegram.go @@ -30,9 +30,11 @@ package telegram import ( + "bytes" "context" "errors" "fmt" + "html" "io" "log/slog" "os" @@ -115,6 +117,9 @@ var ( // Options are the optional parts of an Approver. type Options struct { + // Prefix is plain text that goes before the text of every message + // and edit, such as "TRY MODE · " for nodkey try. Default: none. + Prefix string // Logger gets refused button presses and problems with Telegram. The // default drops them. No line holds the bot token or message text. Logger *slog.Logger @@ -239,6 +244,15 @@ func New(cfg config.Telegram, opts Options) (*Approver, error) { return newApprover(cfg, opts, config.ReadPrivateFile, defaultBaseURL) } +// NewWithToken is New with the bot token in memory instead of in +// cfg.TokenFile. nodkey try uses it: the person types the token, and it +// is never written to a file. The Approver keeps a copy, so the caller +// may clear token. +func NewWithToken(cfg config.Telegram, token []byte, opts Options) (*Approver, error) { + read := func(string) ([]byte, error) { return bytes.Clone(token), nil } + return newApprover(cfg, opts, read, defaultBaseURL) +} + // newApprover is New with the token reader and the address of the Bot API. // Tests use a fake reader and a fake Telegram server. func newApprover(cfg config.Telegram, opts Options, read func(string) ([]byte, error), base string) (*Approver, error) { @@ -284,8 +298,10 @@ func newApprover(cfg config.Telegram, opts Options, read func(string) ([]byte, e slog.String("variable", name), slog.String("path", path)) } } + api := newClient(token, base) + api.prefix = html.EscapeString(opts.Prefix) return &Approver{ - api: newClient(token, base), + api: api, userID: cfg.UserID, noticeChat: cfg.NoticeChatID, log: logger, From 998af4b7c16c1deafc648e44364bdc31ca5be28c Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:38:02 +0200 Subject: [PATCH 03/10] feat: nodkey try --telegram: a new bot, a /start link, approval on the phone (#125) Co-Authored-By: Claude Opus 5.5 --- cmd/nodkey/terminal_linux.go | 34 +++++++++ cmd/nodkey/terminal_other.go | 9 ++- cmd/nodkey/try.go | 71 ++++++++++++++----- cmd/nodkey/try_test.go | 4 +- cmd/nodkey/trytelegram.go | 130 +++++++++++++++++++++++++++++++++++ 5 files changed, 229 insertions(+), 19 deletions(-) create mode 100644 cmd/nodkey/trytelegram.go diff --git a/cmd/nodkey/terminal_linux.go b/cmd/nodkey/terminal_linux.go index e91088c..4e85b17 100644 --- a/cmd/nodkey/terminal_linux.go +++ b/cmd/nodkey/terminal_linux.go @@ -30,3 +30,37 @@ func isTerminal(w io.Writer) bool { } return terminal } + +// echoOff turns off the echo of the terminal f, so that what the person +// types is not shown. restore turns it back on. It fails when f is not a +// terminal. +func echoOff(f *os.File) (restore func(), err error) { + rc, err := f.SyscallConn() + if err != nil { + return nil, err + } + var old syscall.Termios + var errno syscall.Errno + if err := rc.Control(func(fd uintptr) { + //nolint:gosec // G103: TCGETS writes a Termios, and the pointer lives only in this call. + _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCGETS, uintptr(unsafe.Pointer(&old))) + if errno != 0 { + return + } + t := old + t.Lflag &^= syscall.ECHO + //nolint:gosec // G103: TCSETS reads a Termios, and the pointer lives only in this call. + _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCSETS, uintptr(unsafe.Pointer(&t))) + }); err != nil { + return nil, err + } + if errno != 0 { + return nil, errno + } + return func() { + _ = rc.Control(func(fd uintptr) { + //nolint:gosec // G103: TCSETS reads a Termios, and the pointer lives only in this call. + _, _, _ = syscall.Syscall(syscall.SYS_IOCTL, fd, syscall.TCSETS, uintptr(unsafe.Pointer(&old))) + }) + }, nil +} diff --git a/cmd/nodkey/terminal_other.go b/cmd/nodkey/terminal_other.go index 8363ab2..f96aa27 100644 --- a/cmd/nodkey/terminal_other.go +++ b/cmd/nodkey/terminal_other.go @@ -2,8 +2,15 @@ package main -import "io" +import ( + "errors" + "io" + "os" +) // isTerminal reports false: nodkey version 1 runs on Linux only, so // nodkey version asks GitHub only there. func isTerminal(io.Writer) bool { return false } + +// echoOff fails: hidden input needs Linux. +func echoOff(*os.File) (func(), error) { return nil, errors.New("hidden input works only on Linux") } diff --git a/cmd/nodkey/try.go b/cmd/nodkey/try.go index 49d6912..b5b8105 100644 --- a/cmd/nodkey/try.go +++ b/cmd/nodkey/try.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "context" "errors" "flag" @@ -23,6 +24,7 @@ import ( "github.com/code6x/nodkey/internal/client" "github.com/code6x/nodkey/internal/config" "github.com/code6x/nodkey/internal/store" + "github.com/code6x/nodkey/internal/telegram" "github.com/code6x/nodkey/internal/transport" ) @@ -55,7 +57,7 @@ var ( tryWindow = 5 * time.Minute ) -const tryUsage = `Usage: nodkey try +const tryUsage = `Usage: nodkey try [--telegram] nodkey try run [--secret VAR=NAME]... [--reason TEXT] -- COMMAND [ARGS...] Try nodkey on this machine, with fake secrets, in a few minutes. It needs @@ -72,6 +74,11 @@ nodkey try run is nodkey run with the client config of the trial. Run it in a second terminal while nodkey try runs. It never reads ~/.config/nodkey/client.toml. +With --telegram, the requests show up in Telegram on your phone instead. +Make a new bot with @BotFather for this, never the bot of a real broker. +nodkey try asks for its token (hidden, kept only in memory), prints a link +that you open on the phone, and takes your user ID from that message. + Try mode is not a setup: it shows the flow, never a real secret. See docs/setup.md for a real one. ` @@ -84,6 +91,7 @@ func runTry(args []string, stdin io.Reader, stdout, stderr io.Writer) int { } fs := flag.NewFlagSet("nodkey try", flag.ContinueOnError) fs.SetOutput(io.Discard) + useTelegram := fs.Bool("telegram", false, "") if err := fs.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { _, _ = io.WriteString(stderr, tryUsage) @@ -100,7 +108,15 @@ func runTry(args []string, stdin io.Reader, stdout, stderr io.Writer) int { } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP, syscall.SIGQUIT) defer stop() - return serveTry(ctx, dir, stdin, stdout) + var tg *tryTelegram + if *useTelegram { + tg, err = setupTryTelegram(ctx, bufio.NewReaderSize(stdin, maxTryLine), stdin, stdout) + if err != nil { + _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: %s (exit 1)\n", err) + return exitFailure + } + } + return serveTry(ctx, dir, stdin, stdout, tg) } // runTryRun runs nodkey try run: nodkey run with the client config of the @@ -178,25 +194,31 @@ type trial struct { stopRun context.CancelFunc runDone chan struct{} + runErr error // the error of the approver's Run; read after runDone serveDone chan struct{} } // serveTry runs the trial in dir until ctx ends or a part stops, then // stops it and removes dir. -func serveTry(ctx context.Context, dir string, stdin io.Reader, stdout io.Writer) int { +// With tg, the approver is the Telegram bot of tg, and ap only prints. +func serveTry(ctx context.Context, dir string, stdin io.Reader, stdout io.Writer, tg *tryTelegram) int { tr := &trial{dir: dir} ap := newTryApprover(stdin, stdout) - addr, err := tr.start(ap) + addr, err := tr.start(ap, tg) code := exitOK if err != nil { ap.say(fmt.Sprintf("nodkey try: TRY MODE: cannot start: %s\n", err)) code = exitFailure } else { - ap.say(tryIntro(addr)) + ap.say(tryIntro(addr, tg != nil)) select { case <-ctx.Done(): case <-tr.runDone: - ap.say("nodkey try: TRY MODE: the terminal approver stopped: no answer can come any more\n") + if tg != nil { + ap.say("nodkey try: TRY MODE: Telegram stopped: " + tryTelegramErr(tr.runErr) + "\n") + } else { + ap.say("nodkey try: TRY MODE: the terminal approver stopped: no answer can come any more\n") + } code = exitFailure case <-tr.serveDone: ap.say("nodkey try: TRY MODE: the trial broker stopped\n") @@ -214,7 +236,7 @@ func serveTry(ctx context.Context, dir string, stdin io.Reader, stdout io.Writer // start makes the directory and the parts of the trial: the keys, the // config, the audit log, the store, the service, the approval core with // the terminal approver, and the server on 127.0.0.1 with a random port. -func (tr *trial) start(ap *tryApprover) (string, error) { +func (tr *trial) start(ap *tryApprover, tg *tryTelegram) (string, error) { // As nodkey broker: no core dumps, and other processes of the user // cannot read its memory. It needs no root. if err := hardenProcess(); err != nil { @@ -243,7 +265,11 @@ func (tr *trial) start(ap *tryApprover) (string, error) { if err != nil { return "", err } - cfg := tryConfig(tr.dir, clientPin) + userID := int64(tryUserID) + if tg != nil { + userID = tg.userID + } + cfg := tryConfig(tr.dir, clientPin, userID) tr.audit, err = audit.Open(cfg.AuditLog, audit.Options{Journal: logF, Alert: func(audit.Recovery) {}}) if err != nil { return "", err @@ -254,7 +280,17 @@ func (tr *trial) start(ap *tryApprover) (string, error) { if err != nil { return "", err } - core, err := approval.New(cfg, ap, approval.Options{Logger: tr.log}) + var approver approval.Approver = ap + if tg != nil { + tga, err := telegram.NewWithToken(cfg.Telegram, tg.token, + telegram.Options{Logger: tr.log, ForeignTap: tr.svc.ForeignTap, Prefix: tryPrefix}) + clear(tg.token) + if err != nil { + return "", err + } + approver = tga + } + core, err := approval.New(cfg, approver, approval.Options{Logger: tr.log}) if err != nil { return "", err } @@ -284,7 +320,7 @@ func (tr *trial) start(ap *tryApprover) (string, error) { } go func() { defer close(tr.runDone) - _ = tr.svc.Run(runCtx, core, say, say) + tr.runErr = tr.svc.Run(runCtx, core, say, say) }() tr.serveDone = make(chan struct{}) go func() { @@ -401,14 +437,14 @@ func (tr *trial) stop() bool { // tryConfig is the broker config of the trial. It is made here, not read // from a file: the trial reads no config file. Its one store is the trial // store, a name that no config file can give a store type to. -func tryConfig(dir string, clientPin config.Pin) *config.Broker { +func tryConfig(dir string, clientPin config.Pin, userID int64) *config.Broker { // The rule is one that LoadBroker would make from ask = "window". rule := config.Rule{Ask: config.AskWindow, Window: tryWindow} cfg := &config.Broker{ Listen: netip.AddrPortFrom(netip.AddrFrom4([4]byte{127, 0, 0, 1}), 0), TLSKey: filepath.Join(dir, tryBrokerKey), AuditLog: filepath.Join(dir, tryAuditLog), - Telegram: config.Telegram{UserID: tryUserID, NoticeChatID: tryUserID, Timeout: tryTimeout, SSHTimeout: tryTimeout}, + Telegram: config.Telegram{UserID: userID, NoticeChatID: userID, Timeout: tryTimeout, SSHTimeout: tryTimeout}, // Preapprove and Standing stay zero: the trial allows no scheduled // and no standing grant. Clients: map[string]config.Client{tryClientName: {Name: tryClientName, Pin: clientPin}}, @@ -437,7 +473,11 @@ func writeTryClientConfig(path, addr string, brokerPin config.Pin, key string) e } // tryIntro is what nodkey try prints when the trial is ready. -func tryIntro(addr string) string { +func tryIntro(addr string, inTelegram bool) string { + answer := "The request shows up here. Type 1, 2 or 3 and Enter to answer it, or\nwait" + if inTelegram { + answer = "The request shows up in Telegram. Tap a button to answer it, or\nwait" + } return fmt.Sprintf(`nodkey try: TRY MODE: a trial broker listens on %s, with fake secrets only: demo-token, demo-password and demo-api-key. Their values start with TRY-. @@ -445,10 +485,9 @@ In a second terminal, run: nodkey try run --secret DEMO_TOKEN=demo-token -- sh -c 'echo "got ${#DEMO_TOKEN} characters"' -The request shows up here. Type 1, 2 or 3 and Enter to answer it, or -wait %s: then it expires and is denied. Press Ctrl-C to end the trial. +%s %s: then it expires and is denied. Press Ctrl-C to end the trial. -`, addr, tryTimeout) +`, addr, answer, tryTimeout) } // tryOutro is what nodkey try prints when the trial ends. diff --git a/cmd/nodkey/try_test.go b/cmd/nodkey/try_test.go index d9f2d7c..9fdae0c 100644 --- a/cmd/nodkey/try_test.go +++ b/cmd/nodkey/try_test.go @@ -80,7 +80,7 @@ func TestBrokerHasNoTerminalApproval(t *testing.T) { // The trial's config has only the trial store, with no type, so no real // store can serve it, and nodkey broker cannot make it from a file. func TestTryConfigHasOnlyTheTrialStore(t *testing.T) { - cfg := tryConfig("/nonexistent", config.Pin{}) + cfg := tryConfig("/nonexistent", config.Pin{}, tryUserID) if len(cfg.Stores) != 1 || cfg.Stores[tryStoreName].Type != "" { t.Fatalf("stores %v, want only %q with no type", cfg.Stores, tryStoreName) } @@ -242,7 +242,7 @@ func TestTryApproverTooEarly(t *testing.T) { // The trial allows no scheduled and no standing grant. func TestTryConfigAllowsNoScheduledOrStandingGrants(t *testing.T) { - cfg := tryConfig("/nonexistent", config.Pin{}) + cfg := tryConfig("/nonexistent", config.Pin{}, tryUserID) if cfg.Preapprove != (config.PreapproveLimits{}) { t.Errorf("preapprove limits %+v, want none", cfg.Preapprove) } diff --git a/cmd/nodkey/trytelegram.go b/cmd/nodkey/trytelegram.go new file mode 100644 index 0000000..d3a4c98 --- /dev/null +++ b/cmd/nodkey/trytelegram.go @@ -0,0 +1,130 @@ +package main + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "io" + "os" + "strings" + + "github.com/code6x/nodkey/internal/telegram" +) + +// tryPrefix goes before every Telegram message of the trial. +const tryPrefix = "TRY MODE · " + +// tryTelegram is what nodkey try --telegram set up: the bot token, only +// in memory, and the approver's user ID from the /start message. +type tryTelegram struct { + token []byte + userID int64 +} + +// Format hides the token. +func (*tryTelegram) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, "tryTelegram") } + +// tryConflictText says what to do when Telegram reports that another +// program polls the bot. +const tryConflictText = "Telegram says another program polls this bot, maybe a nodkey broker. " + + "Use a new bot for the trial, never the broker's bot: with two programs on one bot, " + + "the real broker stops (exit 76)" + +// tryTelegramErr is the text of an error of the Telegram part of the trial. +func tryTelegramErr(err error) string { + switch { + case errors.Is(err, telegram.ErrPollConflict): + return tryConflictText + case errors.Is(err, telegram.ErrTokenRefused): + return "Telegram does not accept the bot token" + } + return err.Error() +} + +// setupTryTelegram asks for the token of a new bot, prints the link that +// sends /start with a random code, and takes the approver's user ID only +// from that message, after the person confirms the name. +func setupTryTelegram(ctx context.Context, in *bufio.Reader, stdin io.Reader, out io.Writer) (*tryTelegram, error) { + _, _ = io.WriteString(out, `nodkey try: TRY MODE: approval in Telegram. + 1. In Telegram, open @BotFather, send /newbot, and make a NEW bot for this trial. + Never use the bot of a real broker: the real broker would stop. + 2. Paste the token of the new bot here and press Enter. It is not shown, + and it is kept only in memory. +Token: `) + token, err := readTryToken(ctx, in, stdin) + _, _ = io.WriteString(out, "\n") + if err != nil { + return nil, err + } + p, err := telegram.NewPairing(ctx, token) + if err != nil { + clear(token) + return nil, errors.New(tryTelegramErr(err)) + } + b := make([]byte, 16) + _, _ = rand.Read(b) + code := base64.RawURLEncoding.EncodeToString(b) + _, _ = fmt.Fprintf(out, "nodkey try: TRY MODE: on your phone, open this link and tap Start:\n\n %s\n\n", p.Link(code)) + who, err := p.Wait(ctx, code) + if err != nil { + clear(token) + return nil, errors.New(tryTelegramErr(err)) + } + _, _ = fmt.Fprintf(out, "nodkey try: TRY MODE: Telegram user %s (ID %d) sent the code.\n"+ + "Only this user can answer. Is this you? Type yes and Enter: ", who.Name, who.UserID) + answer, err := readTryLine(ctx, in) + if err != nil || strings.TrimSpace(string(answer)) != "yes" { + clear(token) + return nil, errors.New("not confirmed, so the trial does not start") + } + return &tryTelegram{token: token, userID: who.UserID}, nil +} + +// readTryToken reads the token, with the echo of the terminal off when +// stdin is a terminal. +func readTryToken(ctx context.Context, in *bufio.Reader, stdin io.Reader) ([]byte, error) { + if f, ok := stdin.(*os.File); ok && isTerminal(f) { + restore, err := echoOff(f) + if err != nil { + return nil, fmt.Errorf("cannot hide the input: %w", err) + } + defer restore() + } + line, err := readTryLine(ctx, in) + if err != nil { + return nil, err + } + token := []byte(strings.TrimSpace(string(line))) + clear(line) + return token, nil +} + +// readTryLine reads one line of at most maxTryLine bytes, until ctx ends. +func readTryLine(ctx context.Context, in *bufio.Reader) ([]byte, error) { + type result struct { + line []byte + err error + } + done := make(chan result, 1) + go func() { + line, err := in.ReadSlice('\n') + if err == nil || (errors.Is(err, io.EOF) && len(line) > 0) { + done <- result{line: append([]byte(nil), line...)} + clear(line) + return + } + if errors.Is(err, bufio.ErrBufferFull) { + err = errors.New("the line is too long") + } + done <- result{err: err} + }() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case r := <-done: + return r.line, r.err + } +} From 1cf7c520c5fd53c53c79ac45c2c29ecdd1f731ea Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:39:56 +0200 Subject: [PATCH 04/10] test: nodkey try --telegram with the fake Telegram: approve, not confirmed, conflict, bad token (#125) Co-Authored-By: Claude Opus 5.5 --- cmd/nodkey/brokerfake_linux_test.go | 24 ++++++++ cmd/nodkey/try_linux_test.go | 96 ++++++++++++++++++++++++++++- 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/cmd/nodkey/brokerfake_linux_test.go b/cmd/nodkey/brokerfake_linux_test.go index ae00bdf..49e4750 100644 --- a/cmd/nodkey/brokerfake_linux_test.go +++ b/cmd/nodkey/brokerfake_linux_test.go @@ -352,6 +352,8 @@ func (f *fakeTelegram) ServeHTTP(w http.ResponseWriter, r *http.Request) { writeTelegram(w, http.StatusOK, message(p.MessageID)) case "answerCallbackQuery": writeTelegram(w, http.StatusOK, `{"ok":true,"result":true}`) + case "getMe": + writeTelegram(w, http.StatusOK, `{"ok":true,"result":{"id":1,"is_bot":true,"username":"try_test_bot"}}`) default: writeTelegram(w, http.StatusNotFound, `{"ok":false,"error_code":404,"description":"Not Found"}`) } @@ -609,6 +611,28 @@ func (f *fakeTelegram) tap(msgID int64, data string) string { return id } +// sendStart queues the message "/start code" from the approver, in a +// private chat with the bot. +func (f *fakeTelegram) sendStart(code string) { + f.t.Helper() + f.mu.Lock() + defer f.mu.Unlock() + f.nextUpdate++ + raw, err := json.Marshal(map[string]any{ + "update_id": f.nextUpdate, + "message": map[string]any{ + "message_id": 1, "date": 1, "text": "/start " + code, + "chat": map[string]any{"id": approverID, "type": "private"}, + "from": map[string]any{"id": approverID, "is_bot": false, "first_name": "Test", "username": "test_user"}, + }, + }) + if err != nil { + f.t.Fatal(err) + } + f.updates = append(f.updates, tgUpdate{id: f.nextUpdate, raw: raw}) + f.notifyLocked() +} + // waitTapAnswer waits for the answer to the press id // (answerCallbackQuery), and returns the text that the phone shows. func (f *fakeTelegram) waitTapAnswer(id string) string { diff --git a/cmd/nodkey/try_linux_test.go b/cmd/nodkey/try_linux_test.go index dca3d97..97450fa 100644 --- a/cmd/nodkey/try_linux_test.go +++ b/cmd/nodkey/try_linux_test.go @@ -5,9 +5,11 @@ import ( "errors" "io" "io/fs" + "net/http" "os" "os/exec" "path/filepath" + "regexp" "slices" "strings" "syscall" @@ -27,6 +29,10 @@ const ( func TestTryChild(t *testing.T) { switch os.Getenv(tryChildMode) { case "try": + args := []string{"try"} + if a := os.Getenv(tryChildArgs); a != "" { + args = append(args, strings.Split(a, tryArgSep)...) + } if s := os.Getenv(tryChildTimeout); s != "" { d, err := time.ParseDuration(s) if err != nil { @@ -34,7 +40,7 @@ func TestTryChild(t *testing.T) { } tryTimeout = d } - os.Exit(run([]string{"try"}, os.Stdin, os.Stdout, os.Stderr)) + os.Exit(run(args, os.Stdin, os.Stdout, os.Stderr)) case "run": args := strings.Split(os.Getenv(tryChildArgs), tryArgSep) os.Exit(run(append([]string{"try", "run"}, args...), os.Stdin, os.Stdout, os.Stderr)) @@ -58,6 +64,7 @@ type tryEnv struct { log *lineLog exited chan struct{} waitErr error + extra []string // more environment of nodkey try, such as the fake Telegram's proxy } // newTryEnv makes the directories of a trial, without starting it. @@ -101,7 +108,7 @@ func (e *tryEnv) startNoWait(timeout time.Duration) { t := e.t t.Helper() cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestTryChild$") //nolint:gosec // G204: the test runs its own binary again. - cmd.Env = e.env("try", tryChildTimeout+"="+timeout.String()) + cmd.Env = e.env("try", append([]string{tryChildTimeout + "=" + timeout.String()}, e.extra...)...) cmd.Dir = e.work in, err := cmd.StdinPipe() if err != nil { @@ -443,3 +450,88 @@ func TestTryRunWithoutATrial(t *testing.T) { checkClientLines(t, stderr) e.checkClean() } + +// newTryTelegramEnv is a trial with --telegram, and the fake Telegram. +func newTryTelegramEnv(t *testing.T, opts brokerOptions) (*tryEnv, *fakeTelegram) { + t.Helper() + f := newFakeTelegram(t, opts) + e := newTryEnv(t) + e.extra = []string{tryChildArgs + "=--telegram", "HTTPS_PROXY=http://" + f.proxyAddr, + "SSL_CERT_FILE=" + f.caFile, "SSL_CERT_DIR=" + f.caDir} + return e, f +} + +// pairTry types the token, sends /start with the code of the link, and +// answers the question of the name with confirm. +func (e *tryEnv) pairTry(f *fakeTelegram, confirm string) { + t := e.t + t.Helper() + e.answer(f.token) + e.log.wait(t, "https://t.me/try_test_bot?start=") + m := regexp.MustCompile(`start=([A-Za-z0-9_-]{16,64})$`).FindStringSubmatch(strings.TrimSpace(e.log.text())) + if m == nil { + t.Fatalf("no code in the link:\n%s", e.log.text()) + } + f.sendStart(m[1]) + e.log.wait(t, "sent the code.") + if !e.log.has("Test (@test_user) (ID 7000001)") { + t.Fatalf("the name is not shown:\n%s", e.log.text()) + } + e.answer(confirm) +} + +func TestTryTelegram(t *testing.T) { + e, f := newTryTelegramEnv(t, brokerOptions{}) + e.startNoWait(time.Minute) + e.pairTry(f, "yes") + e.log.wait(t, "The request shows up in Telegram") + if strings.Contains(e.log.text(), f.token) { + t.Fatal("nodkey try printed the bot token") + } + r := e.run(e.demoArgs()...) + msgID, requestID := f.waitAsk(1) + if body := f.bodies(); !strings.Contains(body, "TRY MODE · ") { + t.Fatalf("the message does not say TRY MODE:\n%s", body) + } + f.waitTapAnswer(f.tap(msgID, "o:"+requestID)) + code, stderr := r.wait(t) + if code != 0 { + t.Fatalf("nodkey try run: exit code %d, want 0; stderr:\n%s", code, stderr) + } + checkClientLines(t, stderr) + e.checkValue(stderr) + e.stopAndCheck(syscall.SIGTERM) +} + +// Without "yes", the trial does not start. +func TestTryTelegramNotConfirmed(t *testing.T) { + e, f := newTryTelegramEnv(t, brokerOptions{}) + e.startNoWait(time.Minute) + e.pairTry(f, "no") + if code := e.exitCode(); code != exitFailure || !e.log.has("not confirmed") { + t.Fatalf("exit code %d, want 1; output:\n%s", code, e.log.text()) + } + e.checkClean() +} + +// A conflict from Telegram stops the trial and says to use a new bot. +func TestTryTelegramConflict(t *testing.T) { + e, f := newTryTelegramEnv(t, brokerOptions{refusePolls: http.StatusConflict}) + e.startNoWait(time.Minute) + e.answer(f.token) + if code := e.exitCode(); code != exitFailure || !e.log.has("never the broker's bot") { + t.Fatalf("exit code %d, want 1; output:\n%s", code, e.log.text()) + } + e.checkClean() +} + +// A token that Telegram does not accept stops the trial. +func TestTryTelegramBadToken(t *testing.T) { + e, _ := newTryTelegramEnv(t, brokerOptions{}) + e.startNoWait(time.Minute) + e.answer(newBotToken()) + if code := e.exitCode(); code != exitFailure || !e.log.has("does not accept the bot token") { + t.Fatalf("exit code %d, want 1; output:\n%s", code, e.log.text()) + } + e.checkClean() +} From 2c5492301c97cdaff9bad9403ceb1cf7414173b1 Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:40:36 +0200 Subject: [PATCH 05/10] docs: nodkey try --telegram in DESIGN.md, THREAT-MODEL.md T38, README.md and the manual test (#125) Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 35 ++++++++++++++++++++++++++++---- README.md | 5 +++++ THREAT-MODEL.md | 16 +++++++++++++-- docs/manual-telegram-test.md | 39 ++++++++++++++++++++++++++++++++++++ 4 files changed, 89 insertions(+), 6 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index a381f85..c617abc 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -98,7 +98,7 @@ One static Go binary holds all parts. The subcommand picks the role: | `nodkey run` | agent machine | Get secrets, then start one command with them. | | `nodkey ssh-agent` | agent machine | Serve an SSH agent socket. Send each signature request to the broker. | | `nodkey ssh-grant` | agent machine | Ask once for SSH logins to a list of hosts for N minutes (see [decision 4](#13-decision-4-ssh-approval-scope)). | -| `nodkey try` | one machine | A trial with fake secrets and approval in its own terminal, for a first look. It is not a setup (section 15). | +| `nodkey try` | one machine | A trial with fake secrets and approval in its own terminal, or with `--telegram` on the phone, for a first look. It is not a setup (section 15). | | `nodkey keygen` | both | Make a TLS key pair for the broker or a client. Print its pin. | | `nodkey audit verify` | trusted machine | Check the hash chain of an audit log. | | `nodkey update` | both, as root | Install a release in place of this binary, with the install script that is built into it (section 18). | @@ -108,7 +108,9 @@ One static Go binary holds all parts. The subcommand picks the role: `nodkey try` runs the real broker parts on `127.0.0.1` of one machine, but with its own approver (the terminal) and its own store (three fake -values). Both live only in the code of `nodkey try`. `nodkey broker` +values). Both live only in the code of `nodkey try`. With `--telegram` +it uses the Telegram approver instead, with a new bot that the person +makes for the trial. `nodkey broker` cannot use them: no flag, config key or variable turns them on (THREAT-MODEL.md, T38). @@ -3346,7 +3348,7 @@ nodkey preapprove --secret NAME... (--daily HH:MM-HH:MM | --weekly DAYS HH:MM-HH nodkey preapprove --cancel ID nodkey preapprove --login ITEM --url URL [--reason TEXT] nodkey agent-browser-plugin -nodkey try +nodkey try [--telegram] nodkey try run [--secret VAR=NAME]... [--reason TEXT] -- COMMAND [ARGS...] nodkey keygen --out FILE nodkey audit verify FILE [--anchor SEQ:HASH]... [--anchors FILE|-] @@ -3771,7 +3773,8 @@ credentials. Its one client is `try-client`. Its one store holds three secrets, `demo-token`, `demo-password` and `demo-api-key`, with random values that start with `TRY-`, made at the start. Their rule is `ask = "window"` with a 5 minute window. It has no -SSH keys, no Telegram and no check for a newer release. +SSH keys and no check for a newer release. Without `--telegram` it has +no Telegram. nodkey try shows each request in its own terminal, with the lines of the message and the choices: `1` Approve once, `2` Approve 5 min, `3` Deny. @@ -3786,6 +3789,30 @@ SIGQUIT stops the trial with exit code 0: it ends the parts in the order of `nodkey broker`, removes the directory, and prints what a real setup adds, with a pointer to docs/setup.md. +With `--telegram`, the requests go to Telegram instead of the terminal, +before the directory is made: + +1. nodkey try asks the person to make a new bot with @BotFather, never + the bot of a real broker, and to paste its token. When stdin is a + terminal, its echo is off while the token is typed. The token is kept + only in memory, never in a file or a log. +2. It calls `getMe` for the bot's user name, makes a random code (16 + bytes, base64url), and prints the link `https://t.me/BOT?start=CODE`. +3. It polls the bot until the message `/start CODE` comes in a private + chat with its sender. Every other message is skipped. The sender's + user ID becomes the one approver and the notice chat. No one has to + look up the ID with `getUpdates`. +4. It shows the sender's name and ID, and starts only when the person + types `yes`. + +Then the trial runs as above, but with the Telegram approver of +`nodkey broker`: the same messages and buttons, with `TRY MODE · ` before +the text of every message and every edit. The terminal shows only the +intro and the notices. When Telegram answers a poll with a conflict +(another program polls the bot, such as a real broker), nodkey try stops +with exit code 1 and says to use a new bot. A token that Telegram does +not accept stops it with 1 too. + `nodkey try run` is `nodkey run` with the client config of the trial, `client.toml` in that directory. It never reads `~/.config/nodkey/client.toml`. In `nodkey try run`, each line that nodkey diff --git a/README.md b/README.md index ae9ee69..0852175 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,11 @@ command. So you read the command before you tap. Press Ctrl-C in the first terminal to end the trial; it removes its files. +To answer on your phone instead, run `nodkey try --telegram`. It asks you +to make a new bot with @BotFather (never the bot of a real broker), to +paste its token, and to open a link on your phone. Then each request +comes to Telegram, with `TRY MODE` on each message. + Try mode is not a setup. The agent could type the answer in that terminal, so the trial has only fake values (they start with `TRY-`) and can never reach a real secret. A real setup adds a separate broker host, diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index baf2bdf..c448b65 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -1296,7 +1296,8 @@ must never take answers from a terminal. made in memory, with one store that has no type, so no `[store.*]` section can name it, and `store.New` cannot make it. It never starts `bws` or `bw`. Its only values are random, made at the start, and start - with `TRY-`. It has no SSH key and no bot token. + with `TRY-`. It has no SSH key. Only with `--telegram` does it have a + bot token, which the person types and which stays in memory. - `nodkey try run` reads only the client config of the trial, never `~/.config/nodkey/client.toml`, and it pins the trial's broker key. So it cannot send a request to a real broker by mistake, and a real @@ -1307,8 +1308,19 @@ must never take answers from a terminal. `nodkey try run` prints starts with `TRY MODE`, so a person does not take the trial for a setup. The trial allows no scheduled and no standing grant. +- With `--telegram`, the token is typed on this machine, which may be an + agent machine (docs/setup.md, "Where you do the setup"). The guide and + the prompt say: make a new bot for the trial, never use the broker's + bot. If the broker's bot is used anyway, both poll, Telegram answers + one of them with a conflict, and the real broker stops with exit code + 76 (T6); nodkey try stops too and says to use a new bot. The approver's + user ID comes only from the `/start CODE` message with a random code, + and the person must confirm the name. + Risk that remains: the agent on the same machine can answer a request of -the trial, or read its fake values. That is fine: they open nothing. A +the trial, or read its fake values. With `--telegram`, it can also read +the token of the trial's bot from the terminal or the memory of the +process; that bot opens nothing, and the person can delete it. That is fine: they open nothing. A person who copies the trial's way of working to a real setup loses the phone. The last lines of `nodkey try` and the guides say what a real setup adds: a separate broker host, a store, Telegram and the rules. diff --git a/docs/manual-telegram-test.md b/docs/manual-telegram-test.md index 07fb285..416d640 100644 --- a/docs/manual-telegram-test.md +++ b/docs/manual-telegram-test.md @@ -742,6 +742,41 @@ Expected: At the end, delete the machine identity, the project and the file with the client secret. +### Check 18: nodkey try --telegram (optional) + +New in 0.8.0: skip it with nodkey 0.7.0 or older. + +This checks the trial with Telegram (issue #125). It needs no broker +files: stop the broker of terminal 1 first. Make a second new bot in +BotFather for it, not the test bot of the other checks. + +1. Terminal 1: `HOME="$T/home" "$T/nodkey" try --telegram`. Paste the + token of the second bot. Check that the token is not shown while you + paste it. +2. Open the link that it prints on the phone, and tap **Start**. + Terminal 1 shows your first name and user ID. Type `yes`. +3. Terminal 2: run the `nodkey try run` command that terminal 1 prints, + with `"$T/nodkey"` in place of `nodkey` and `HOME="$T/home"` before + it. Tap **Approve once**. Then run it again and tap **Deny**. +4. Start the broker of terminal 1 again, in a third terminal, with the + bot of the trial: put the second bot's token in the token file + for a moment. Within a minute, one of the two stops. Then put the + token of the test bot back. +5. Press Ctrl-C in terminal 1. + +Expected: + +- Step 2: the name is yours, and nothing starts before `yes`. +- Step 3: each message starts with `TRY MODE · `. Approve once: the + command prints its line, and exit code 0. Deny: exit code 77. Each line + of `nodkey try run` starts with `TRY MODE`. +- Step 4: nodkey try stops with `Telegram says another program polls + this bot` and exit code 1, or the broker stops with exit code 76. +- Step 5: the trial ends, and `ls "$XDG_RUNTIME_DIR/nodkey-try"` says + there is no such file. + +Delete the second bot in BotFather after the test. + ## Clean up 1. Terminal 1: stop the broker with Ctrl-C, if it still runs. @@ -797,3 +832,7 @@ raw answer of the Bot API, and the lines of the log with `user_id` or | 17 | an Infisical store (optional) | the command gets the value; after the access token ended, the next fetch works | | | | 17 | a missing name; a value with `${` | exit 77 for both; the log says why | | | | 17 | the client secret and the values in the logs | `0` for `broker.log` and `audit.jsonl` | | | +| 18 | `try --telegram`: hidden token, link, name | the token is not shown; your name and ID; starts only after `yes` | | | +| 18 | `try --telegram`: Approve once, Deny | `TRY MODE · ` on each message; exit 0, then 77 | | | +| 18 | `try --telegram`: the bot of a broker | nodkey try stops and says to use a new bot, or the broker stops with 76 | | | +| 18 | `try --telegram`: Ctrl-C | the directory of the trial is gone | | | From c18341696f5501dc00397f32f3af20d0038d420b Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:40:48 +0200 Subject: [PATCH 06/10] docs: the results of check 16 go to #125 Co-Authored-By: Claude Opus 5.5 --- docs/manual-telegram-test.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/manual-telegram-test.md b/docs/manual-telegram-test.md index 416d640..bd3e3e3 100644 --- a/docs/manual-telegram-test.md +++ b/docs/manual-telegram-test.md @@ -789,7 +789,8 @@ Delete the second bot in BotFather after the test. ## Results -Copy this table into a comment on issue #17, and fill it in. The issue is +Copy this table into a comment on issue #17 (the rows of check 16: on +issue #125), and fill it in. The issue is public. Leave out the token, your user ID, the name of the bot, every raw answer of the Bot API, and the lines of the log with `user_id` or `chat_id`. From 891137459d9f34d96ffae12a936e8cb8e877a70e Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:44:39 +0200 Subject: [PATCH 07/10] fix: review findings for nodkey try --telegram (#125) Harden the process before the token is read; the guard test covers the Telegram parts of the trial; Format with value receivers; T38 says that either poller may stop on a conflict. Co-Authored-By: Claude Opus 5.5 --- THREAT-MODEL.md | 8 +++++--- cmd/nodkey/try.go | 6 ++++++ cmd/nodkey/try_test.go | 5 ++++- cmd/nodkey/trytelegram.go | 2 +- internal/telegram/pair.go | 2 +- 5 files changed, 17 insertions(+), 6 deletions(-) diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index c448b65..874414f 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -1311,9 +1311,11 @@ must never take answers from a terminal. - With `--telegram`, the token is typed on this machine, which may be an agent machine (docs/setup.md, "Where you do the setup"). The guide and the prompt say: make a new bot for the trial, never use the broker's - bot. If the broker's bot is used anyway, both poll, Telegram answers - one of them with a conflict, and the real broker stops with exit code - 76 (T6); nodkey try stops too and says to use a new bot. The approver's + bot. If the broker's bot is used anyway, both poll, and Telegram + answers one of them with a conflict: either the real broker stops with + exit code 76 (T6), or nodkey try stops and says to use a new bot. While + both poll, the trial can take button presses meant for the broker; + those requests get no answer and are denied. The approver's user ID comes only from the `/start CODE` message with a random code, and the person must confirm the name. diff --git a/cmd/nodkey/try.go b/cmd/nodkey/try.go index b5b8105..3b6aa09 100644 --- a/cmd/nodkey/try.go +++ b/cmd/nodkey/try.go @@ -110,6 +110,12 @@ func runTry(args []string, stdin io.Reader, stdout, stderr io.Writer) int { defer stop() var tg *tryTelegram if *useTelegram { + // Before the token is read: no core dumps, and other processes + // of the user cannot read its memory. + if err := hardenProcess(); err != nil { + _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: cannot turn off core dumps: %s (exit 1)\n", err) + return exitFailure + } tg, err = setupTryTelegram(ctx, bufio.NewReaderSize(stdin, maxTryLine), stdin, stdout) if err != nil { _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: %s (exit 1)\n", err) diff --git a/cmd/nodkey/try_test.go b/cmd/nodkey/try_test.go index 9fdae0c..d48d080 100644 --- a/cmd/nodkey/try_test.go +++ b/cmd/nodkey/try_test.go @@ -20,13 +20,16 @@ import ( ) // tryFiles are the files of nodkey try. Only they may use its parts. -var tryFiles = map[string]bool{"try.go": true, "tryapprover.go": true, "trystore.go": true} +var tryFiles = map[string]bool{"try.go": true, "tryapprover.go": true, "trystore.go": true, "trytelegram.go": true} // tryOnly are the names of the parts of nodkey try: the terminal // approver, the test store, the config without a file, and the trial. var tryOnly = map[string]bool{ "tryApprover": true, "newTryApprover": true, "tryStore": true, "newTryStore": true, "tryConfig": true, "trial": true, "serveTry": true, "runTryRun": true, "tryUserID": true, + "tryTelegram": true, "setupTryTelegram": true, "tryPrefix": true, + // The parts of package telegram that only nodkey try uses. + "NewWithToken": true, "NewPairing": true, "Prefix": true, } // nodkey broker has no way to turn on the approval in the terminal, or diff --git a/cmd/nodkey/trytelegram.go b/cmd/nodkey/trytelegram.go index d3a4c98..6632bfd 100644 --- a/cmd/nodkey/trytelegram.go +++ b/cmd/nodkey/trytelegram.go @@ -25,7 +25,7 @@ type tryTelegram struct { } // Format hides the token. -func (*tryTelegram) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, "tryTelegram") } +func (tryTelegram) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, "tryTelegram") } // tryConflictText says what to do when Telegram reports that another // program polls the bot. diff --git a/internal/telegram/pair.go b/internal/telegram/pair.go index 8c4dd61..daeaf58 100644 --- a/internal/telegram/pair.go +++ b/internal/telegram/pair.go @@ -119,4 +119,4 @@ func cleanName(s string) string { } // Format hides the Pairing, so that no fmt verb prints the token. -func (*Pairing) Format(f fmt.State, _ rune) { _, _ = f.Write([]byte("telegram.Pairing")) } +func (Pairing) Format(f fmt.State, _ rune) { _, _ = f.Write([]byte("telegram.Pairing")) } From 8ef8b51215c5ac5b8c58f18c6c4c580375499990 Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:27:55 +0200 Subject: [PATCH 08/10] docs: the trial with Telegram is check 18 after the rebase (#125) Main added checks 16 and 17 (1Password, Infisical). Co-Authored-By: Claude Opus 5.5 --- docs/manual-telegram-test.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manual-telegram-test.md b/docs/manual-telegram-test.md index bd3e3e3..1fe09e8 100644 --- a/docs/manual-telegram-test.md +++ b/docs/manual-telegram-test.md @@ -789,7 +789,7 @@ Delete the second bot in BotFather after the test. ## Results -Copy this table into a comment on issue #17 (the rows of check 16: on +Copy this table into a comment on issue #17 (the rows of check 18: on issue #125), and fill it in. The issue is public. Leave out the token, your user ID, the name of the bot, every raw answer of the Bot API, and the lines of the log with `user_id` or From 2b1dc1490e7ca1ff1a4e21314c7205078eae0f06 Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:38:35 +0200 Subject: [PATCH 09/10] fix: review findings after the rebase of nodkey try --telegram (#125) - check that no trial runs before the pairing polls the bot - a signal during the setup ends with exit code 0; the end of the input says what to do - every new error says how to fix it; the usage error names --telegram - Options.Prefix is at most 32 characters, and every message keeps room for it - the token is trimmed as bytes - THREAT-MODEL T38: what a pasted broker token gives the agent, and the removed buttons Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 10 +++++--- THREAT-MODEL.md | 8 ++++++- cmd/nodkey/try.go | 31 ++++++++++++++++++++++--- cmd/nodkey/try_linux_test.go | 42 ++++++++++++++++++++++++++++++++++ cmd/nodkey/trytelegram.go | 30 +++++++++++++++++------- internal/telegram/pair.go | 7 ++++-- internal/telegram/pair_test.go | 25 ++++++++++++++++++++ internal/telegram/telegram.go | 3 +++ internal/telegram/text.go | 9 +++++--- 9 files changed, 145 insertions(+), 20 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index c617abc..07b5410 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -3792,8 +3792,10 @@ adds, with a pointer to docs/setup.md. With `--telegram`, the requests go to Telegram instead of the terminal, before the directory is made: -1. nodkey try asks the person to make a new bot with @BotFather, never - the bot of a real broker, and to paste its token. When stdin is a +1. When a trial runs already, nodkey try stops with exit code 1: a + second poller would stop the first trial. Then it asks the person to + make a new bot with @BotFather, never the bot of a real broker, and to + paste its token. When stdin is a terminal, its echo is off while the token is typed. The token is kept only in memory, never in a file or a log. 2. It calls `getMe` for the bot's user name, makes a random code (16 @@ -3811,7 +3813,9 @@ the text of every message and every edit. The terminal shows only the intro and the notices. When Telegram answers a poll with a conflict (another program polls the bot, such as a real broker), nodkey try stops with exit code 1 and says to use a new bot. A token that Telegram does -not accept stops it with 1 too. +not accept stops it with 1 too. A signal during the setup stops it with +exit code 0; nothing was made. `Options.Prefix` of the Telegram approver +is at most 32 characters, and every message keeps room for it. `nodkey try run` is `nodkey run` with the client config of the trial, `client.toml` in that directory. It never reads diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 874414f..8c58565 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -1315,7 +1315,13 @@ must never take answers from a terminal. answers one of them with a conflict: either the real broker stops with exit code 76 (T6), or nodkey try stops and says to use a new bot. While both poll, the trial can take button presses meant for the broker; - those requests get no answer and are denied. The approver's + those requests get no answer and are denied, and the trial removes the + buttons of the broker's message. A second trial checks first that no + trial runs, so it does not poll the bot of the first one. If the + broker's token was pasted, the agent may now have it: with it, it can + poll the bot and stop the broker, or send messages that look like the + broker's (T6). Make a new token (docs/setup.md section 13, "A new bot + token"). The approver's user ID comes only from the `/start CODE` message with a random code, and the person must confirm the name. diff --git a/cmd/nodkey/try.go b/cmd/nodkey/try.go index 3b6aa09..7f9cebd 100644 --- a/cmd/nodkey/try.go +++ b/cmd/nodkey/try.go @@ -99,7 +99,7 @@ func runTry(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return parseErrorCode(stderr, "try", err) } if fs.NArg() > 0 { - return usageFail(stderr, "try", fmt.Sprintf("unexpected argument %.64q; it takes none, or run", fs.Arg(0))) + return usageFail(stderr, "try", fmt.Sprintf("unexpected argument %.64q; it takes none, --telegram, or run", fs.Arg(0))) } dir, err := tryDir() if err != nil { @@ -113,11 +113,22 @@ func runTry(args []string, stdin io.Reader, stdout, stderr io.Writer) int { // Before the token is read: no core dumps, and other processes // of the user cannot read its memory. if err := hardenProcess(); err != nil { - _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: cannot turn off core dumps: %s (exit 1)\n", err) + _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: cannot turn off core dumps: %s; "+ + "--telegram needs this to keep the bot token safe, so use nodkey try without it (exit 1)\n", err) + return exitFailure + } + // Before the pairing polls the bot: a second trial would stop + // the first one with a conflict from Telegram. + if err := checkNoTrial(dir); err != nil { + _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: %s (exit 1)\n", err) return exitFailure } tg, err = setupTryTelegram(ctx, bufio.NewReaderSize(stdin, maxTryLine), stdin, stdout) - if err != nil { + switch { + case err != nil && ctx.Err() != nil: + _, _ = io.WriteString(stdout, "\nnodkey try: TRY MODE: stopped before the setup ended; nothing was made\n") + return exitOK + case err != nil: _, _ = fmt.Fprintf(stdout, "nodkey try: TRY MODE: %s (exit 1)\n", err) return exitFailure } @@ -390,6 +401,20 @@ func (tr *trial) removeMade() { } } +// checkNoTrial returns an error when a trial runs in dir. It takes no +// lock: makeDir takes it later. +func checkNoTrial(dir string) error { + f, err := os.OpenFile(filepath.Join(dir, tryLockFile), os.O_RDWR|syscall.O_NOFOLLOW, 0) //nolint:gosec // G304: the lock file of the trial's own directory. + if err != nil { + return nil // no trial; makeDir checks the rest + } + defer func() { _ = f.Close() }() + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + return errors.New("a trial runs already, in another terminal; stop it with Ctrl-C first") + } + return nil +} + // removeStaleTryDir removes dir, the directory of an earlier trial, when // it holds a lock file that no trial holds. func removeStaleTryDir(dir string) error { diff --git a/cmd/nodkey/try_linux_test.go b/cmd/nodkey/try_linux_test.go index 97450fa..129f119 100644 --- a/cmd/nodkey/try_linux_test.go +++ b/cmd/nodkey/try_linux_test.go @@ -535,3 +535,45 @@ func TestTryTelegramBadToken(t *testing.T) { } e.checkClean() } + +// When the input ends before the token, the trial says so, and makes +// nothing. +func TestTryTelegramInputEnds(t *testing.T) { + e, _ := newTryTelegramEnv(t, brokerOptions{}) + e.startNoWait(time.Minute) + e.log.wait(t, "kept only in memory") + _ = e.in.Close() + if code := e.exitCode(); code != exitFailure || !e.log.has("the input ended before the answer") { + t.Fatalf("exit code %d, want 1; output:\n%s", code, e.log.text()) + } + e.checkClean() +} + +// A signal during the setup stops the trial cleanly, with exit code 0. +func TestTryTelegramSignalInSetup(t *testing.T) { + e, _ := newTryTelegramEnv(t, brokerOptions{}) + e.startNoWait(time.Minute) + e.log.wait(t, "kept only in memory") + if err := e.cmd.Process.Signal(syscall.SIGINT); err != nil { + t.Fatal(err) + } + if code := e.exitCode(); code != exitOK || !e.log.has("stopped before the setup ended") { + t.Fatalf("exit code %d, want 0; output:\n%s", code, e.log.text()) + } + e.checkClean() +} + +// While a trial runs, a second one with --telegram stops before it asks +// for a token, so it never polls the bot of the first one. +func TestTryTelegramWhileATrialRuns(t *testing.T) { + e := newTryEnv(t) + e.start(time.Minute) + second, _ := newTryTelegramEnv(t, brokerOptions{}) + second.home, second.runtime, second.tmp, second.work = e.home, e.runtime, e.tmp, e.work + second.startNoWait(time.Minute) + if code := second.exitCode(); code != exitFailure || !second.log.has("a trial runs already") || + second.log.has("approval in Telegram") { + t.Fatalf("second trial: exit code %d, want 1; output:\n%s", code, second.log.text()) + } + e.stopAndCheck(syscall.SIGTERM) +} diff --git a/cmd/nodkey/trytelegram.go b/cmd/nodkey/trytelegram.go index 6632bfd..d08c007 100644 --- a/cmd/nodkey/trytelegram.go +++ b/cmd/nodkey/trytelegram.go @@ -2,6 +2,7 @@ package main import ( "bufio" + "bytes" "context" "crypto/rand" "encoding/base64" @@ -31,7 +32,7 @@ func (tryTelegram) Format(f fmt.State, _ rune) { _, _ = io.WriteString(f, "tryTe // program polls the bot. const tryConflictText = "Telegram says another program polls this bot, maybe a nodkey broker. " + "Use a new bot for the trial, never the broker's bot: with two programs on one bot, " + - "the real broker stops (exit 76)" + "the real broker stops with exit code 76. Make a new bot in @BotFather, then start nodkey try --telegram again" // tryTelegramErr is the text of an error of the Telegram part of the trial. func tryTelegramErr(err error) string { @@ -39,9 +40,18 @@ func tryTelegramErr(err error) string { case errors.Is(err, telegram.ErrPollConflict): return tryConflictText case errors.Is(err, telegram.ErrTokenRefused): - return "Telegram does not accept the bot token" + return "Telegram does not accept the bot token; copy the token of the new bot from @BotFather again, " + + "then start nodkey try --telegram again" } - return err.Error() + return err.Error() + "; check that this machine can reach api.telegram.org, then start nodkey try --telegram again" +} + +// tryInputErr is the error of a line that the person did not type. +func tryInputErr(err error) error { + if errors.Is(err, io.EOF) { + return errors.New("the input ended before the answer; run nodkey try --telegram in a terminal") + } + return err } // setupTryTelegram asks for the token of a new bot, prints the link that @@ -57,7 +67,7 @@ Token: `) token, err := readTryToken(ctx, in, stdin) _, _ = io.WriteString(out, "\n") if err != nil { - return nil, err + return nil, tryInputErr(err) } p, err := telegram.NewPairing(ctx, token) if err != nil { @@ -78,7 +88,11 @@ Token: `) answer, err := readTryLine(ctx, in) if err != nil || strings.TrimSpace(string(answer)) != "yes" { clear(token) - return nil, errors.New("not confirmed, so the trial does not start") + if err != nil { + return nil, tryInputErr(err) + } + return nil, errors.New("not confirmed, so the trial does not start; " + + "start nodkey try --telegram again and type yes when the name is yours") } return &tryTelegram{token: token, userID: who.UserID}, nil } @@ -89,7 +103,7 @@ func readTryToken(ctx context.Context, in *bufio.Reader, stdin io.Reader) ([]byt if f, ok := stdin.(*os.File); ok && isTerminal(f) { restore, err := echoOff(f) if err != nil { - return nil, fmt.Errorf("cannot hide the input: %w", err) + return nil, fmt.Errorf("cannot hide the input of the terminal: %w; run nodkey try --telegram in a normal terminal", err) } defer restore() } @@ -97,7 +111,7 @@ func readTryToken(ctx context.Context, in *bufio.Reader, stdin io.Reader) ([]byt if err != nil { return nil, err } - token := []byte(strings.TrimSpace(string(line))) + token := bytes.Clone(bytes.TrimSpace(line)) clear(line) return token, nil } @@ -117,7 +131,7 @@ func readTryLine(ctx context.Context, in *bufio.Reader) ([]byte, error) { return } if errors.Is(err, bufio.ErrBufferFull) { - err = errors.New("the line is too long") + err = errors.New("the line is too long; paste only the token, or the answer, and press Enter") } done <- result{err: err} }() diff --git a/internal/telegram/pair.go b/internal/telegram/pair.go index daeaf58..d4936ea 100644 --- a/internal/telegram/pair.go +++ b/internal/telegram/pair.go @@ -39,7 +39,9 @@ func NewPairing(ctx context.Context, token []byte) (*Pairing, error) { func newPairing(ctx context.Context, token []byte, base string) (*Pairing, error) { t, err := parseToken(bytes.Clone(token)) if err != nil { - return nil, err + // The text never shows what was typed. + return nil, errors.New("telegram: this is not a bot token, which is the bot's ID in digits, \":\", " + + "and 30 to 64 letters, digits, \"_\" or \"-\"; copy the token of the new bot from @BotFather again") } api := newClient(t, base) var me struct { @@ -49,7 +51,8 @@ func newPairing(ctx context.Context, token []byte, base string) (*Pairing, error return nil, err } if !botNamePattern.MatchString(me.Username) { - return nil, errors.New("telegram: getMe: the bot has no valid user name") + return nil, errors.New("telegram: getMe: the bot has no valid user name; " + + "make a new bot in @BotFather with /newbot, then start nodkey try --telegram again") } return &Pairing{api: api, Bot: me.Username}, nil } diff --git a/internal/telegram/pair_test.go b/internal/telegram/pair_test.go index c083542..f599e97 100644 --- a/internal/telegram/pair_test.go +++ b/internal/telegram/pair_test.go @@ -8,6 +8,9 @@ import ( "strings" "testing" "time" + + "github.com/code6x/nodkey/internal/approval" + "github.com/code6x/nodkey/internal/audit" ) const testPairCode = "abcdefghij0123456789" @@ -136,3 +139,25 @@ func TestNewWithToken(t *testing.T) { t.Fatal("the Approver does not hold its own copy of the token") } } + +// A prefix longer than the room that each message keeps for it is refused, +// and the longest notice still fits with the longest prefix. +func TestPrefixRoom(t *testing.T) { + read := func(string) ([]byte, error) { return []byte(newCanaryToken(t)), nil } + long := strings.Repeat("x", maxPrefixUnits+1) + if _, err := newApprover(testTelegramConfig(), Options{Prefix: long}, read, "http://192.0.2.1"); err == nil { + t.Fatal("no error for a prefix that is too long") + } + p := approval.Prompt{ + RequestID: testID(4), ShortCode: "k3f9", Kind: audit.KindSecrets, Client: "laptop", + Secrets: []string{"backup-token"}, Via: audit.ViaStanding, + Claim: approval.Claim{Command: strings.Repeat("😀 long command ", 2000), Reason: strings.Repeat("😀 long reason ", 2000)}, + } + tx, err := noticeText(p) + if err != nil { + t.Fatal(err) + } + if n := tx.units() + maxPrefixUnits; n > maxTextUnits { + t.Fatalf("a notice with the prefix has %d UTF-16 code units, more than %d", n, maxTextUnits) + } +} diff --git a/internal/telegram/telegram.go b/internal/telegram/telegram.go index dc2e483..0531cc3 100644 --- a/internal/telegram/telegram.go +++ b/internal/telegram/telegram.go @@ -259,6 +259,9 @@ func newApprover(cfg config.Telegram, opts Options, read func(string) ([]byte, e if cfg.UserID <= 0 { return nil, errors.New("telegram: the approver's user ID must be more than 0") } + if utf16Len(opts.Prefix) > maxPrefixUnits { + return nil, fmt.Errorf("telegram: the message prefix is longer than %d characters; use a shorter Options.Prefix", maxPrefixUnits) + } if cfg.NoticeChatID == 0 { return nil, errors.New("telegram: the notice chat ID must not be 0") } diff --git a/internal/telegram/text.go b/internal/telegram/text.go index 0295174..376393b 100644 --- a/internal/telegram/text.go +++ b/internal/telegram/text.go @@ -40,6 +40,9 @@ const ( // lastLineRoom is the room that a message keeps for its last line: // the expiry, or the result after the request ended. lastLineRoom = 100 + // maxPrefixUnits is the longest Options.Prefix. A notice keeps this + // room free for it, and so does a prompt. + maxPrefixUnits = 32 // maxAlertUnits is the longest alert text. maxAlertUnits = 3000 // clockFormat shows a time of day in the broker's local time. @@ -629,9 +632,9 @@ func expiryLine(p approval.Prompt) string { // its message ends with the line of its approval and the line of its end. func bodyLimit(p approval.Prompt) int { if p.Kind.IsPreapprove() { - return maxTextUnits - 2*lastLineRoom + return maxTextUnits - 2*lastLineRoom - maxPrefixUnits } - return maxTextUnits - lastLineRoom + return maxTextUnits - lastLineRoom - maxPrefixUnits } // promptMessage returns the message that Ask sends for p: its text and @@ -742,7 +745,7 @@ func noticeText(p approval.Prompt) (*text, error) { if err := checkPrompt(p, true); err != nil { return nil, err } - return fitBody(p, true, maxTextUnits) + return fitBody(p, true, maxTextUnits-maxPrefixUnits) } // standingEndLine says how and when a standing grant ended. It has no From 0b97ca2f1f3cf09aa3da7216757f01a2bdb0eb14 Mon Sep 17 00:00:00 2001 From: Geno Roupsky <185580+groupsky@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:44:15 +0200 Subject: [PATCH 10/10] fix: the network hint only for a failed Bot API call in nodkey try --telegram (#125) Co-Authored-By: Claude Opus 5.5 --- cmd/nodkey/try_test.go | 24 ++++++++++++++++++++++++ cmd/nodkey/trytelegram.go | 6 +++++- internal/telegram/api.go | 7 +++++++ internal/telegram/pair_test.go | 10 ++++++++++ internal/telegram/telegram.go | 2 +- 5 files changed, 47 insertions(+), 2 deletions(-) diff --git a/cmd/nodkey/try_test.go b/cmd/nodkey/try_test.go index d48d080..3c6c8d2 100644 --- a/cmd/nodkey/try_test.go +++ b/cmd/nodkey/try_test.go @@ -17,6 +17,7 @@ import ( "github.com/code6x/nodkey/internal/audit" "github.com/code6x/nodkey/internal/config" "github.com/code6x/nodkey/internal/store" + "github.com/code6x/nodkey/internal/telegram" ) // tryFiles are the files of nodkey try. Only they may use its parts. @@ -278,3 +279,26 @@ func TestTryLinesConcurrent(t *testing.T) { t.Fatal("lines are mixed") } } + +// Each error of the Telegram part says how to fix it, once: only an error +// of a Bot API call gets the hint about the network. +func TestTryTelegramErr(t *testing.T) { + for _, tc := range []struct { + err error + want string + }{ + {nil, "start nodkey try --telegram again"}, + {telegram.ErrPollConflict, "never the broker's bot"}, + {telegram.ErrTokenRefused, "from @BotFather again"}, + {errors.New("telegram: this is not a bot token; copy it again"), "telegram: this is not a bot token; copy it again"}, + } { + got := tryTelegramErr(tc.err) + if !strings.Contains(got, tc.want) || strings.Count(got, "start nodkey try --telegram again") > 1 { + t.Errorf("tryTelegramErr(%v) = %q", tc.err, got) + } + if tc.err != nil && !errors.Is(tc.err, telegram.ErrPollConflict) && !errors.Is(tc.err, telegram.ErrTokenRefused) && + strings.Contains(got, "api.telegram.org") { + t.Errorf("tryTelegramErr(%v) adds the network hint: %q", tc.err, got) + } + } +} diff --git a/cmd/nodkey/trytelegram.go b/cmd/nodkey/trytelegram.go index d08c007..b7b9c03 100644 --- a/cmd/nodkey/trytelegram.go +++ b/cmd/nodkey/trytelegram.go @@ -37,13 +37,17 @@ const tryConflictText = "Telegram says another program polls this bot, maybe a n // tryTelegramErr is the text of an error of the Telegram part of the trial. func tryTelegramErr(err error) string { switch { + case err == nil: + return "the Telegram approver stopped; start nodkey try --telegram again" case errors.Is(err, telegram.ErrPollConflict): return tryConflictText case errors.Is(err, telegram.ErrTokenRefused): return "Telegram does not accept the bot token; copy the token of the new bot from @BotFather again, " + "then start nodkey try --telegram again" + case telegram.IsCallError(err): + return err.Error() + "; check that this machine can reach api.telegram.org, then start nodkey try --telegram again" } - return err.Error() + "; check that this machine can reach api.telegram.org, then start nodkey try --telegram again" + return err.Error() } // tryInputErr is the error of a line that the person did not type. diff --git a/internal/telegram/api.go b/internal/telegram/api.go index ca26588..aac276c 100644 --- a/internal/telegram/api.go +++ b/internal/telegram/api.go @@ -91,6 +91,13 @@ func parseToken(data []byte) (botToken, error) { // apiError is an error of one Bot API call. Its text names the method and // a fixed reason, never Go's error text, the URL, the token or Telegram's // description. +// IsCallError reports whether err comes from a call of the Bot API that +// failed: no answer, or an answer that is not ok. +func IsCallError(err error) bool { + var e *apiError + return errors.As(err, &e) +} + type apiError struct { method string reason string // a fixed text diff --git a/internal/telegram/pair_test.go b/internal/telegram/pair_test.go index f599e97..dad8a05 100644 --- a/internal/telegram/pair_test.go +++ b/internal/telegram/pair_test.go @@ -161,3 +161,13 @@ func TestPrefixRoom(t *testing.T) { t.Fatalf("a notice with the prefix has %d UTF-16 code units, more than %d", n, maxTextUnits) } } + +// IsCallError is true only for an error of a Bot API call. +func TestIsCallError(t *testing.T) { + if !IsCallError(fmt.Errorf("wrapped: %w", &apiError{method: "getMe", reason: "no answer"})) { + t.Error("an error of a call is not a call error") + } + if IsCallError(errors.New("other")) || IsCallError(nil) { + t.Error("another error is a call error") + } +} diff --git a/internal/telegram/telegram.go b/internal/telegram/telegram.go index 0531cc3..65df228 100644 --- a/internal/telegram/telegram.go +++ b/internal/telegram/telegram.go @@ -260,7 +260,7 @@ func newApprover(cfg config.Telegram, opts Options, read func(string) ([]byte, e return nil, errors.New("telegram: the approver's user ID must be more than 0") } if utf16Len(opts.Prefix) > maxPrefixUnits { - return nil, fmt.Errorf("telegram: the message prefix is longer than %d characters; use a shorter Options.Prefix", maxPrefixUnits) + return nil, fmt.Errorf("telegram: the message prefix is longer than %d characters (UTF-16 code units); use a shorter Options.Prefix", maxPrefixUnits) } if cfg.NoticeChatID == 0 { return nil, errors.New("telegram: the notice chat ID must not be 0")