From 4683460ed591bcd06040758ab4ef9de0c33be76b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=85=8E=E9=A5=BC=E6=9E=9C=E5=AD=90=E5=8D=B7=E9=B2=A8?= =?UTF-8?q?=E9=B1=BC=E8=BE=A3=E6=A4=92?= Date: Wed, 1 Jan 2025 18:59:12 +0800 Subject: [PATCH] refactor: update ID generation methods and remove obsolete test file - Renamed the GenerateMacMachineID method to GenerateSQMID and updated its implementation to generate a new SQM ID in UUID format. - Enhanced the ID generation logic by introducing a buffer pool for efficient memory management. - Removed the generator_test.go file as it was no longer needed, streamlining the codebase. - Updated the generateNewConfig function to utilize the new SQMID generation method, ensuring consistency across ID generation processes. --- cmd/cursor-id-modifier/main.go | 2 +- pkg/idgen/generator.go | 108 +++++++++++++++++++++++---------- pkg/idgen/generator_test.go | 47 -------------- 3 files changed, 76 insertions(+), 81 deletions(-) delete mode 100644 pkg/idgen/generator_test.go diff --git a/cmd/cursor-id-modifier/main.go b/cmd/cursor-id-modifier/main.go index 7560e78..89de5f3 100644 --- a/cmd/cursor-id-modifier/main.go +++ b/cmd/cursor-id-modifier/main.go @@ -240,7 +240,7 @@ func generateNewConfig(display *ui.Display, generator *idgen.Generator, oldConfi if oldConfig != nil && oldConfig.TelemetrySqmId != "" { newConfig.TelemetrySqmId = oldConfig.TelemetrySqmId - } else if sqmID, err := generator.GenerateMacMachineID(); err != nil { + } else if sqmID, err := generator.GenerateSQMID(); err != nil { log.Fatal("Failed to generate SQM ID:", err) } else { newConfig.TelemetrySqmId = sqmID diff --git a/pkg/idgen/generator.go b/pkg/idgen/generator.go index 1b68d83..3061f74 100644 --- a/pkg/idgen/generator.go +++ b/pkg/idgen/generator.go @@ -4,71 +4,113 @@ import ( "crypto/rand" "encoding/hex" "fmt" - "time" + "sync" ) // Generator handles secure ID generation for machines and devices -type Generator struct{} +type Generator struct { + bufferPool sync.Pool +} // NewGenerator creates a new ID generator func NewGenerator() *Generator { - return &Generator{} + return &Generator{ + bufferPool: sync.Pool{ + New: func() interface{} { + return make([]byte, 64) + }, + }, + } } -// Helper methods -// ------------- - -// simulateWork adds a small delay to make progress visible -func (g *Generator) simulateWork() { - time.Sleep(800 * time.Millisecond) -} +// Constants for ID generation +const ( + machineIDPrefix = "auth0|user_" + uuidFormat = "%s-%s-%s-%s-%s" +) // generateRandomHex generates a random hex string of specified length func (g *Generator) generateRandomHex(length int) (string, error) { - bytes := make([]byte, length) - if _, err := rand.Read(bytes); err != nil { + buffer := g.bufferPool.Get().([]byte) + defer g.bufferPool.Put(buffer) + + if _, err := rand.Read(buffer[:length]); err != nil { return "", fmt.Errorf("failed to generate random bytes: %w", err) } - return hex.EncodeToString(bytes), nil + return hex.EncodeToString(buffer[:length]), nil } -// Public methods -// ------------- - // GenerateMachineID generates a new machine ID with auth0|user_ prefix func (g *Generator) GenerateMachineID() (string, error) { - g.simulateWork() - - // 生成随机部分 (25字节,将产生50个十六进制字符) - randomPart, err := g.generateRandomHex(25) + randomPart, err := g.generateRandomHex(32) // 生成64字符的十六进制 if err != nil { return "", err } - // 构建完整的ID: "auth0|user_" + random - prefix := "auth0|user_" - fullID := fmt.Sprintf("%x%x%s", - []byte(prefix), // 转换前缀为十六进制 - []byte("0"), // 添加一个字符 - randomPart, // 随机部分 - ) - - return fullID, nil + return fmt.Sprintf("%x%s", []byte(machineIDPrefix), randomPart), nil } // GenerateMacMachineID generates a new 64-byte MAC machine ID func (g *Generator) GenerateMacMachineID() (string, error) { - g.simulateWork() - return g.generateRandomHex(64) + return g.generateRandomHex(32) // 生成64字符的十六进制 } // GenerateDeviceID generates a new device ID in UUID format func (g *Generator) GenerateDeviceID() (string, error) { - g.simulateWork() id, err := g.generateRandomHex(16) if err != nil { return "", err } - return fmt.Sprintf("%s-%s-%s-%s-%s", + return fmt.Sprintf(uuidFormat, id[0:8], id[8:12], id[12:16], id[16:20], id[20:32]), nil } + +// GenerateSQMID generates a new SQM ID in UUID format (with braces) +func (g *Generator) GenerateSQMID() (string, error) { + id, err := g.GenerateDeviceID() + if err != nil { + return "", err + } + return fmt.Sprintf("{%s}", id), nil +} + +// ValidateID validates the format of various ID types +func (g *Generator) ValidateID(id string, idType string) bool { + switch idType { + case "machineID", "macMachineID": + return len(id) == 64 && isHexString(id) + case "deviceID": + return isValidUUID(id) + case "sqmID": + if len(id) < 2 || id[0] != '{' || id[len(id)-1] != '}' { + return false + } + return isValidUUID(id[1 : len(id)-1]) + default: + return false + } +} + +// Helper functions +func isHexString(s string) bool { + _, err := hex.DecodeString(s) + return err == nil +} + +func isValidUUID(uuid string) bool { + if len(uuid) != 36 { + return false + } + for i, r := range uuid { + if i == 8 || i == 13 || i == 18 || i == 23 { + if r != '-' { + return false + } + continue + } + if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) { + return false + } + } + return true +} diff --git a/pkg/idgen/generator_test.go b/pkg/idgen/generator_test.go deleted file mode 100644 index 6fbb373..0000000 --- a/pkg/idgen/generator_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package idgen - -import ( - "fmt" - "strings" - "testing" -) - -func TestGenerateMachineID(t *testing.T) { - g := NewGenerator() - - fmt.Println("\n=== 开始测试 MachineID 生成 ===") - - // 运行多次测试以确保一致性 - for i := 0; i < 10; i++ { - id, err := g.GenerateMachineID() - if err != nil { - t.Fatalf("生成ID时发生错误: %v", err) - } - - fmt.Printf("\n第 %d 次测试:\n", i+1) - fmt.Printf("生成的 ID: %s\n", id) - fmt.Printf("ID 长度: %d\n", len(id)) - fmt.Printf("前缀部分: %s\n", id[:20]) - fmt.Printf("随机部分: %s\n", id[20:]) - - // 测试1: 验证总长度 - if len(id) != 74 { - t.Errorf("ID长度不正确. 期望: 74, 实际: %d", len(id)) - } - - // 测试2: 验证前缀 - expectedPrefix := "61757468307c757365725f" // "auth0|user_" 的十六进制 - if !strings.HasPrefix(id, expectedPrefix) { - t.Errorf("ID前缀不正确.\n期望前缀: %s\n实际ID: %s", expectedPrefix, id) - } - - // 测试3: 验证十六进制格式 - for _, c := range id { - if !strings.ContainsRune("0123456789abcdef", c) { - t.Errorf("ID包含非十六进制字符: %c", c) - } - } - } - - fmt.Println("\n=== 测试完成 ===") -}