mirror of
https://github.com/nxtrace/NTrace-core.git
synced 2026-12-03 09:36:11 +00:00
fix(cmd): 允许 -x 直接读取 NextTrace API v4 token
- 在 setup 流程中从 stdin/TTY 读取 token - 保持 stdout/stderr 分离并避免回显 token
This commit is contained in:
1 parent
f619e7b660
commit
489e31bacf
5 files changed
+189
-23
No files matched your search
@@ -639,20 +639,20 @@ export NEXTTRACE_CHUNZHENURL=http://127.0.0.1:2060
|
||||
export NEXTTRACE_DATAPROVIDER=ipinfo
|
||||
```
|
||||
|
||||
LeoMoeAPI keeps the old v3 WebSocket API as the default when `NEXTTRACE_API_V4_TOKEN` is unset. To use the NextTrace API v4 HTTP GeoIP endpoint only for the current shell session, open the token page and run the setup command through your shell:
|
||||
LeoMoeAPI keeps the old v3 WebSocket API as the default when `NEXTTRACE_API_V4_TOKEN` is unset. To use the NextTrace API v4 HTTP GeoIP endpoint only for a temporary shell session, open the token page and run the setup command directly:
|
||||
|
||||
```bash
|
||||
# Token page:
|
||||
# GET https://api.nxtrace.org/v4/api-tokens
|
||||
|
||||
# zsh/bash/sh
|
||||
eval "$(nexttrace -x)"
|
||||
nexttrace -x
|
||||
|
||||
# PowerShell
|
||||
iex (& nexttrace.exe -x)
|
||||
nexttrace.exe -x
|
||||
```
|
||||
|
||||
`nexttrace -x` writes guidance and the token page URL to stderr. Its stdout is shell code consumed by `eval` / `iex`; that shell code prompts for the token in the current shell and sets `NEXTTRACE_API_V4_TOKEN` there. Running `nexttrace -x` directly only prints the correct setup command, because a child process cannot modify its parent shell environment. The command does not write shell profiles, permanent environment variables, or `nt_config.yaml`.
|
||||
`nexttrace -x` reads the token from stdin, then starts a child shell with `NEXTTRACE_API_V4_TOKEN` set. Run NextTrace commands in that child shell, then type `exit` to return. The token naturally disappears when that shell exits. The command does not print the token to stdout and does not write shell profiles, permanent environment variables, or `nt_config.yaml`.
|
||||
|
||||
With `NEXTTRACE_API_V4_TOKEN` set and the active provider still `LeoMoeAPI`, NextTrace queries `GET https://api.nxtrace.org/v4/ipGeo?ip=<ip>` with `X-NextTrace-Token: <token>`. The request has no JSON body. Successful responses are direct GeoIP JSON mapped to the normal output fields; quota metadata is exposed only in headers (`X-NextTrace-Quota-Remaining`, `X-NextTrace-Quota-Expires-At`, `X-NextTrace-Quota-Cost`, `X-NextTrace-Quota-Source`) and does not change the default output format. Error responses prefer `{"error":{"message":"..."}}`; known statuses include `400` for empty/illegal IP, `401` unauthorized, `429` quota exhausted, and `500` internal server error. NextTrace API v4 token failures do not fall back to the old v3 WebSocket API.
|
||||
|
||||
@@ -725,7 +725,7 @@ NextTrace currently reads the following environment variables. For boolean switc
|
||||
| --- | --- | --- |
|
||||
| `NEXTTRACE_HOSTPORT` | `api.nxtrace.org` | Override the backend host or `host:port` used by LeoMoeAPI, tracemap, and FastIP flows. |
|
||||
| `NEXTTRACE_TOKEN` | unset | Pre-supplied LeoMoeAPI bearer token; when present, token fetching via PoW is skipped. |
|
||||
| `NEXTTRACE_API_V4_TOKEN` | unset | Session-only LeoMoeAPI v4 HTTP GeoIP token. When unset, LeoMoeAPI keeps using the old v3 WebSocket / PoW flow. Prefer `nexttrace -x` for current-shell setup. |
|
||||
| `NEXTTRACE_API_V4_TOKEN` | unset | Session-only LeoMoeAPI v4 HTTP GeoIP token. When unset, LeoMoeAPI keeps using the old v3 WebSocket / PoW flow. Prefer `nexttrace -x` for temporary shell setup. |
|
||||
| `NEXTTRACE_POWPROVIDER` | `api.nxtrace.org` | Select the PoW provider. The built-in non-default alias is `sakura`. |
|
||||
| `NEXTTRACE_DEPLOY_ADDR` | unset | Default listen address for `--deploy` when `--listen` is not provided. |
|
||||
| `NEXTTRACE_DEPLOY_TOKEN` | unset | Token for `--deploy` WebUI/API/WebSocket/MCP access. CLI `--deploy-token` takes precedence. |
|
||||
|
||||
+5
-5
@@ -630,20 +630,20 @@ export NEXTTRACE_CHUNZHENURL=http://127.0.0.1:2060
|
||||
export NEXTTRACE_DATAPROVIDER=ipinfo
|
||||
```
|
||||
|
||||
当 `NEXTTRACE_API_V4_TOKEN` 未设置时,LeoMoeAPI 默认仍使用旧 v3 WebSocket API。只想在当前 shell 会话启用 NextTrace API v4 HTTP GeoIP 接口时,先打开 token 页面,再让 shell 执行设置命令:
|
||||
当 `NEXTTRACE_API_V4_TOKEN` 未设置时,LeoMoeAPI 默认仍使用旧 v3 WebSocket API。只想在临时 shell 会话启用 NextTrace API v4 HTTP GeoIP 接口时,先打开 token 页面,再直接执行设置命令:
|
||||
|
||||
```bash
|
||||
# Token 页面:
|
||||
# GET https://api.nxtrace.org/v4/api-tokens
|
||||
|
||||
# zsh/bash/sh
|
||||
eval "$(nexttrace -x)"
|
||||
nexttrace -x
|
||||
|
||||
# PowerShell
|
||||
iex (& nexttrace.exe -x)
|
||||
nexttrace.exe -x
|
||||
```
|
||||
|
||||
`nexttrace -x` 会把使用提示和 token 页面 URL 输出到 stderr;stdout 是给 `eval` / `iex` 消费的 shell 代码,这段代码会在当前 shell 中提示输入 token,并设置 `NEXTTRACE_API_V4_TOKEN`。直接运行 `nexttrace -x` 只会提示正确配置命令,因为子进程不能修改父 shell 的环境变量。该命令不会写 shell profile、永久环境变量或 `nt_config.yaml`。
|
||||
`nexttrace -x` 会从 stdin 读取 token,然后启动一个已设置 `NEXTTRACE_API_V4_TOKEN` 的子 shell。请在这个子 shell 中运行 NextTrace 命令,用完输入 `exit` 返回;退出后 token 会自然失效。该命令不会把 token 打印到 stdout,也不会写 shell profile、永久环境变量或 `nt_config.yaml`。
|
||||
|
||||
设置 `NEXTTRACE_API_V4_TOKEN` 且当前数据源仍为 `LeoMoeAPI` 时,NextTrace 会请求 `GET https://api.nxtrace.org/v4/ipGeo?ip=<ip>`,并只通过 `X-NextTrace-Token: <token>` 请求头传 token;请求没有 JSON body。成功响应是直接映射到现有输出字段的 GeoIP JSON;配额信息只解析响应头(`X-NextTrace-Quota-Remaining`、`X-NextTrace-Quota-Expires-At`、`X-NextTrace-Quota-Cost`、`X-NextTrace-Quota-Source`),不改变默认输出格式。错误响应优先解析 `{"error":{"message":"..."}}`;已知状态包括 `400` 空/非法 IP、`401` unauthorized、`429` quota exhausted、`500` internal server error。NextTrace API v4 token 模式下的错误不会 fallback 到旧 v3 WebSocket API。
|
||||
|
||||
@@ -701,7 +701,7 @@ NextTrace 当前会读取下列环境变量。对于布尔开关,只识别 `1`
|
||||
| --- | --- | --- |
|
||||
| `NEXTTRACE_HOSTPORT` | `api.nxtrace.org` | 覆盖 LeoMoeAPI、tracemap、FastIP 等使用的后端地址,支持 `host` 或 `host:port`。 |
|
||||
| `NEXTTRACE_TOKEN` | 未设置 | 预置 LeoMoeAPI Bearer Token;设置后将跳过 PoW 取 token 流程。 |
|
||||
| `NEXTTRACE_API_V4_TOKEN` | 未设置 | 当前会话使用的 LeoMoeAPI v4 HTTP GeoIP token。未设置时,LeoMoeAPI 仍使用旧 v3 WebSocket / PoW 流程。建议用 `nexttrace -x` 做当前 shell 会话配置。 |
|
||||
| `NEXTTRACE_API_V4_TOKEN` | 未设置 | 临时会话使用的 LeoMoeAPI v4 HTTP GeoIP token。未设置时,LeoMoeAPI 仍使用旧 v3 WebSocket / PoW 流程。建议用 `nexttrace -x` 启动临时 shell。 |
|
||||
| `NEXTTRACE_POWPROVIDER` | `api.nxtrace.org` | 指定 PoW 服务提供方;当前内置的非默认别名为 `sakura`。 |
|
||||
| `NEXTTRACE_DEPLOY_ADDR` | 未设置 | `--deploy` 模式下,当未传 `--listen` 时使用的默认监听地址。 |
|
||||
| `NEXTTRACE_DEPLOY_TOKEN` | 未设置 | `--deploy` WebUI/API/WebSocket/MCP 访问 token。CLI `--deploy-token` 优先级更高。 |
|
||||
|
||||
@@ -1267,6 +1267,7 @@ func Execute() {
|
||||
if err := runNextTraceAPIV4TokenSetup(nextTraceAPIV4TokenSetupOptions{
|
||||
stdout: os.Stdout,
|
||||
stderr: os.Stderr,
|
||||
stdin: os.Stdin,
|
||||
stdoutIsTTY: CheckTTY(int(os.Stdout.Fd())),
|
||||
shell: *setupNextTraceAPIV4Shell,
|
||||
}); err != nil {
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/nxtrace/NTrace-core/ipgeo"
|
||||
"github.com/nxtrace/NTrace-core/util"
|
||||
)
|
||||
@@ -20,8 +24,19 @@ const (
|
||||
type nextTraceAPIV4TokenSetupOptions struct {
|
||||
stdout io.Writer
|
||||
stderr io.Writer
|
||||
stdin *os.File
|
||||
stdoutIsTTY bool
|
||||
shell string
|
||||
readToken func(*os.File, io.Writer) (string, error)
|
||||
startShell func(nextTraceAPIV4TokenShellOptions) error
|
||||
}
|
||||
|
||||
type nextTraceAPIV4TokenShellOptions struct {
|
||||
stdout io.Writer
|
||||
stderr io.Writer
|
||||
stdin *os.File
|
||||
shell string
|
||||
token string
|
||||
}
|
||||
|
||||
func resolveNextTraceAPIV4SetupShell(requested string) string {
|
||||
@@ -44,24 +59,50 @@ func runNextTraceAPIV4TokenSetup(opts nextTraceAPIV4TokenSetupOptions) error {
|
||||
if stderr == nil {
|
||||
stderr = os.Stderr
|
||||
}
|
||||
stdin := opts.stdin
|
||||
if stdin == nil {
|
||||
stdin = os.Stdin
|
||||
}
|
||||
shell := resolveNextTraceAPIV4SetupShell(opts.shell)
|
||||
|
||||
printNextTraceAPIV4TokenSetupIntro(stderr, shell)
|
||||
printNextTraceAPIV4TokenSetupIntro(stderr, shell, !opts.stdoutIsTTY)
|
||||
if opts.stdoutIsTTY {
|
||||
fmt.Fprintln(stderr, "Run the command below; it will prompt for the token and set the environment in the current shell.")
|
||||
fmt.Fprintf(stderr, "Use: %s\n", nextTraceAPIV4SetupEvalCommand(shell))
|
||||
return nil
|
||||
readToken := opts.readToken
|
||||
if readToken == nil {
|
||||
readToken = readNextTraceAPIV4Token
|
||||
}
|
||||
token, err := readToken(stdin, stderr)
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
token = strings.TrimSpace(token)
|
||||
if token == "" {
|
||||
fmt.Fprintf(stderr, "No token entered; %s was not set.\n", util.EnvNextTraceAPIV4TokenKey)
|
||||
return nil
|
||||
}
|
||||
startShell := opts.startShell
|
||||
if startShell == nil {
|
||||
startShell = startNextTraceAPIV4TokenShell
|
||||
}
|
||||
fmt.Fprintf(stderr, "Starting a child shell with %s set. Run NextTrace commands there; type exit to return.\n", util.EnvNextTraceAPIV4TokenKey)
|
||||
return startShell(nextTraceAPIV4TokenShellOptions{
|
||||
stdout: stdout,
|
||||
stderr: stderr,
|
||||
stdin: stdin,
|
||||
shell: shell,
|
||||
token: token,
|
||||
})
|
||||
}
|
||||
|
||||
_, err := fmt.Fprint(stdout, formatNextTraceAPIV4TokenSetupScript(shell))
|
||||
return err
|
||||
}
|
||||
|
||||
func printNextTraceAPIV4TokenSetupIntro(stderr io.Writer, shell string) {
|
||||
func printNextTraceAPIV4TokenSetupIntro(stderr io.Writer, shell string, includeScriptHint bool) {
|
||||
fmt.Fprintf(stderr, "Open token page: GET %s\n", ipgeo.NextTraceAPIV4TokenPageURL)
|
||||
fmt.Fprintf(stderr, "This writes only a session-scoped %s command to stdout.\n", util.EnvNextTraceAPIV4TokenKey)
|
||||
if cmd := nextTraceAPIV4SetupEvalCommand(shell); cmd != "" {
|
||||
fmt.Fprintf(stderr, "Recommended usage: %s\n", cmd)
|
||||
if includeScriptHint {
|
||||
cmd := nextTraceAPIV4SetupEvalCommand(shell)
|
||||
fmt.Fprintf(stderr, "Non-interactive script mode: %s\n", cmd)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +117,69 @@ func nextTraceAPIV4SetupEvalCommand(shell string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func readNextTraceAPIV4Token(stdin *os.File, stderr io.Writer) (string, error) {
|
||||
if stdin == nil {
|
||||
stdin = os.Stdin
|
||||
}
|
||||
if stderr == nil {
|
||||
stderr = os.Stderr
|
||||
}
|
||||
fmt.Fprint(stderr, "Paste NextTrace API v4 token: ")
|
||||
if CheckTTY(int(stdin.Fd())) {
|
||||
tokenBytes, err := term.ReadPassword(int(stdin.Fd()))
|
||||
fmt.Fprintln(stderr)
|
||||
return string(tokenBytes), err
|
||||
}
|
||||
reader := bufio.NewReader(stdin)
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil && err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
return line, err
|
||||
}
|
||||
|
||||
func startNextTraceAPIV4TokenShell(opts nextTraceAPIV4TokenShellOptions) error {
|
||||
name, args := nextTraceAPIV4TokenShellCommand(opts.shell)
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd.Env = append(os.Environ(), util.EnvNextTraceAPIV4TokenKey+"="+opts.token)
|
||||
if opts.stdin != nil {
|
||||
cmd.Stdin = opts.stdin
|
||||
} else {
|
||||
cmd.Stdin = os.Stdin
|
||||
}
|
||||
if opts.stdout != nil {
|
||||
cmd.Stdout = opts.stdout
|
||||
} else {
|
||||
cmd.Stdout = os.Stdout
|
||||
}
|
||||
if opts.stderr != nil {
|
||||
cmd.Stderr = opts.stderr
|
||||
} else {
|
||||
cmd.Stderr = os.Stderr
|
||||
}
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func nextTraceAPIV4TokenShellCommand(shell string) (string, []string) {
|
||||
switch resolveNextTraceAPIV4SetupShell(shell) {
|
||||
case nextTraceAPIV4ShellPowerShell:
|
||||
if runtime.GOOS == "windows" {
|
||||
return "powershell.exe", nil
|
||||
}
|
||||
return "pwsh", nil
|
||||
case nextTraceAPIV4ShellCMD:
|
||||
if runtime.GOOS == "windows" {
|
||||
return "cmd.exe", nil
|
||||
}
|
||||
return "cmd", nil
|
||||
default:
|
||||
if sh := strings.TrimSpace(os.Getenv("SHELL")); sh != "" {
|
||||
return sh, nil
|
||||
}
|
||||
return "/bin/sh", nil
|
||||
}
|
||||
}
|
||||
|
||||
func formatNextTraceAPIV4TokenSetupScript(shell string) string {
|
||||
switch resolveNextTraceAPIV4SetupShell(shell) {
|
||||
case nextTraceAPIV4ShellPowerShell:
|
||||
|
||||
@@ -2,6 +2,7 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -34,28 +35,77 @@ func TestFormatNextTraceAPIV4TokenSetupScriptPromptsInParentShell(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNextTraceAPIV4TokenSetupStdoutTTYDoesNotPrintOrReadToken(t *testing.T) {
|
||||
func TestRunNextTraceAPIV4TokenSetupStdoutTTYReadsTokenAndStartsChildShell(t *testing.T) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
var got nextTraceAPIV4TokenShellOptions
|
||||
startCalled := false
|
||||
err := runNextTraceAPIV4TokenSetup(nextTraceAPIV4TokenSetupOptions{
|
||||
stdout: &stdout,
|
||||
stderr: &stderr,
|
||||
stdoutIsTTY: true,
|
||||
shell: nextTraceAPIV4ShellPOSIX,
|
||||
readToken: func(*os.File, io.Writer) (string, error) {
|
||||
return " secret-token ", nil
|
||||
},
|
||||
startShell: func(opts nextTraceAPIV4TokenShellOptions) error {
|
||||
startCalled = true
|
||||
got = opts
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("runNextTraceAPIV4TokenSetup() error = %v", err)
|
||||
}
|
||||
if !startCalled {
|
||||
t.Fatal("child shell was not started")
|
||||
}
|
||||
if got.token != "secret-token" {
|
||||
t.Fatalf("token = %q, want trimmed token", got.token)
|
||||
}
|
||||
if got.shell != nextTraceAPIV4ShellPOSIX {
|
||||
t.Fatalf("shell = %q, want posix", got.shell)
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("stdout = %q, want empty", stdout.String())
|
||||
}
|
||||
if strings.Contains(stderr.String(), "secret-token") {
|
||||
t.Fatalf("stderr leaked token: %q", stderr.String())
|
||||
}
|
||||
if !strings.Contains(stderr.String(), `eval "$(nexttrace -x)"`) {
|
||||
t.Fatalf("stderr missing session setup usage: %q", stderr.String())
|
||||
if strings.Contains(stderr.String(), "eval") {
|
||||
t.Fatalf("stderr included eval guidance in direct mode: %q", stderr.String())
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "will prompt for the token") {
|
||||
t.Fatalf("stderr missing direct-run guidance: %q", stderr.String())
|
||||
if !strings.Contains(stderr.String(), "Starting a child shell") {
|
||||
t.Fatalf("stderr missing child-shell guidance: %q", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunNextTraceAPIV4TokenSetupStdoutTTYEmptyTokenDoesNotStartShell(t *testing.T) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
startCalled := false
|
||||
err := runNextTraceAPIV4TokenSetup(nextTraceAPIV4TokenSetupOptions{
|
||||
stdout: &stdout,
|
||||
stderr: &stderr,
|
||||
stdoutIsTTY: true,
|
||||
shell: nextTraceAPIV4ShellPOSIX,
|
||||
readToken: func(*os.File, io.Writer) (string, error) {
|
||||
return " ", nil
|
||||
},
|
||||
startShell: func(nextTraceAPIV4TokenShellOptions) error {
|
||||
startCalled = true
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("runNextTraceAPIV4TokenSetup() error = %v", err)
|
||||
}
|
||||
if startCalled {
|
||||
t.Fatal("child shell started for empty token")
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("stdout = %q, want empty", stdout.String())
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "was not set") {
|
||||
t.Fatalf("stderr = %q, want no-token message", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,3 +153,14 @@ func TestRunNextTraceAPIV4TokenSetupGenerationDoesNotSetEnv(t *testing.T) {
|
||||
t.Fatalf("%s = %q, want unchanged empty", util.EnvNextTraceAPIV4TokenKey, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextTraceAPIV4TokenShellCommandUsesConfiguredPOSIXShell(t *testing.T) {
|
||||
t.Setenv("SHELL", "/bin/zsh")
|
||||
name, args := nextTraceAPIV4TokenShellCommand(nextTraceAPIV4ShellPOSIX)
|
||||
if name != "/bin/zsh" {
|
||||
t.Fatalf("shell command = %q, want /bin/zsh", name)
|
||||
}
|
||||
if len(args) != 0 {
|
||||
t.Fatalf("shell args = %#v, want empty", args)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user