随机生成token

This commit is contained in:
user123
2026-01-30 18:31:29 +08:00
parent 9109960c4a
commit a965a0d773
2 changed files with 51 additions and 10 deletions

View File

@@ -140,6 +140,13 @@ configure_openclaw() {
mkdir -p "${CONFIG_DIR}"
# 生成随机 Token
if command -v openssl >/dev/null 2>&1; then
GATEWAY_TOKEN=$(openssl rand -hex 16)
else
GATEWAY_TOKEN=$(date +%s%N | sha256sum | head -c 32)
fi
echo -e "${CYAN}请选择 API 类型:${PLAIN}"
echo "1. Anthropic 官方 API"
echo "2. OpenAI 兼容 API (中转站/其他模型)"
@@ -154,9 +161,12 @@ configure_openclaw() {
cat > "${CONFIG_FILE}" <<EOF
{
"gateway": {
"mode": "local",
"mode": "token",
"bind": "loopback",
"port": 18789
"port": 18789,
"auth": {
"token": "${GATEWAY_TOKEN}"
}
},
"env": {
"ANTHROPIC_API_KEY": "${api_key}"
@@ -195,9 +205,12 @@ EOF
cat > "${CONFIG_FILE}" <<EOF
{
"gateway": {
"mode": "local",
"mode": "token",
"bind": "loopback",
"port": 18789
"port": 18789,
"auth": {
"token": "${GATEWAY_TOKEN}"
}
},
"agents": {
"defaults": {
@@ -255,7 +268,9 @@ EOF
fi
log_info "配置文件已生成: ${CONFIG_FILE}"
echo -e "${GREEN}配置文件路径: ${CONFIG_FILE}${PLAIN}"
echo -e "${GREEN}配置文件绝对路径: ${CONFIG_FILE}${PLAIN}"
echo -e "${GREEN}Gateway Token: ${GATEWAY_TOKEN}${PLAIN}"
echo -e "${YELLOW}请妥善保存此 Token用于远程连接 Gateway。${PLAIN}"
}
# 配置 Systemd 服务

View File

@@ -3,6 +3,7 @@ package sys
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -67,9 +68,15 @@ type OpenclawConfig struct {
}
type GatewayConfig struct {
Mode string `json:"mode"`
Bind string `json:"bind"`
Port int `json:"port"`
Mode string `json:"mode"`
Bind string `json:"bind"`
Port int `json:"port"`
Auth *AuthConfig `json:"auth,omitempty"`
}
type AuthConfig struct {
Mode string `json:"mode,omitempty"`
Token string `json:"token"`
}
type AgentsConfig struct {
@@ -928,11 +935,22 @@ func GenerateAndWriteConfig(opts ConfigOptions) error {
}
configFile := filepath.Join(configDir, "openclaw.json")
// 生成随机 Token
tokenBytes := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, tokenBytes); err != nil {
// 降级方案
copy(tokenBytes, []byte(fmt.Sprintf("%d", time.Now().UnixNano())))
}
token := hex.EncodeToString(tokenBytes)
config := OpenclawConfig{
Gateway: GatewayConfig{
Mode: "local",
Mode: "token",
Bind: "loopback",
Port: 18789,
Auth: &AuthConfig{
Token: token,
},
},
Tools: ToolsConfig{
Elevated: ElevatedConfig{
@@ -1018,7 +1036,15 @@ func GenerateAndWriteConfig(opts ConfigOptions) error {
return fmt.Errorf("序列化配置失败: %v", err)
}
return os.WriteFile(configFile, data, 0644)
if err := os.WriteFile(configFile, data, 0644); err != nil {
return err
}
fmt.Printf("配置文件绝对路径: %s\n", configFile)
fmt.Printf("Gateway Token: %s\n", token)
fmt.Println("请妥善保存此 Token用于远程连接 Gateway。")
return nil
}
// StartGateway 启动网关