first commit

This commit is contained in:
qwer-xyz
2026-06-20 14:22:31 +08:00
commit c2498911ab
793 changed files with 291660 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
package protocol
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"time"
)
// CanonicalJSON 使用 Go 标准库的 JSON 编码。
// map key 会按字典序输出,必须与面板端 stableStringify 规则保持一致。
func CanonicalJSON(value any) ([]byte, error) {
return json.Marshal(value)
}
func BodySHA256(body []byte) string {
sum := sha256.Sum256(body)
return hex.EncodeToString(sum[:])
}
func SigningPayload(method string, path string, timestamp string, nonce string, bodyHash string) string {
return strings.Join([]string{
strings.ToUpper(method),
path,
timestamp,
nonce,
strings.ToLower(bodyHash),
}, "\n")
}
func Signature(secret string, payload string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(payload))
return hex.EncodeToString(mac.Sum(nil))
}
func NewTimestamp() string {
return fmt.Sprintf("%d", time.Now().UnixMilli())
}
func NewNonce() (string, error) {
var raw [18]byte
if _, err := rand.Read(raw[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw[:]), nil
}
+49
View File
@@ -0,0 +1,49 @@
package protocol
import "testing"
func TestCanonicalJSONIsStableForMapOrder(t *testing.T) {
bodyA := map[string]any{
"version": "0.1.0",
"resources": map[string]any{
"memory": 1024,
"cpu": 8,
},
"capabilities": []any{"heartbeat", "report"},
}
bodyB := map[string]any{
"capabilities": []any{"heartbeat", "report"},
"resources": map[string]any{
"cpu": 8,
"memory": 1024,
},
"version": "0.1.0",
}
jsonA, err := CanonicalJSON(bodyA)
if err != nil {
t.Fatalf("canonical json A: %v", err)
}
jsonB, err := CanonicalJSON(bodyB)
if err != nil {
t.Fatalf("canonical json B: %v", err)
}
if string(jsonA) != string(jsonB) {
t.Fatalf("canonical json mismatch:\nA=%s\nB=%s", jsonA, jsonB)
}
if BodySHA256(jsonA) != BodySHA256(jsonB) {
t.Fatalf("body hash mismatch")
}
}
func TestSignatureChangesWithPath(t *testing.T) {
secret := "ias_test_secret"
bodyHash := BodySHA256([]byte(`{"ok":true}`))
payloadA := SigningPayload("POST", "/api/agent/heartbeat", "1777380000000", "nonce-123456", bodyHash)
payloadB := SigningPayload("POST", "/api/agent/report", "1777380000000", "nonce-123456", bodyHash)
if Signature(secret, payloadA) == Signature(secret, payloadB) {
t.Fatalf("signature should change when request path changes")
}
}