package utils import ( "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "os" "strings" "sync" "time" ) // TrainingTemplateTokenValidity 签名下载链接有效期(2026-11 需求:默认 20 天, // 覆盖一次年度需求收集窗口;过期后链接失效,需重新推送)。 const TrainingTemplateTokenValidity = 20 * 24 * time.Hour // TrainingTemplateSignedFilePath 匿名签名下载路由路径;企微 footer 链接、 // 路由注册与 noAuthAPI 白名单三方共用,防路径漂移。 const TrainingTemplateSignedFilePath = "/api/v1/training/templates/signed-file" // TrainingTemplateTokenPayload is the signed anonymous download token carried // in the WeCom markdown footer of a demand-collect broadcast. The signature // binds tenant + template key + expiry so a leaked URL can only fetch one // blank template of one tenant and dies with the collection window. type TrainingTemplateTokenPayload struct { TenantID uint64 `json:"tid"` TemplateKey string `json:"key"` ExpiresAt int64 `json:"exp"` } var ( templateTokenSecretOnce sync.Once templateTokenSecret string ) // trainingTemplateTokenSigningKey mirrors oidcStateSigningKey: dedicated env // first, JWT_SECRET fallback, per-process random as last resort (tokens then // die on restart — acceptable for dev; production sets JWT_SECRET). func trainingTemplateTokenSigningKey() string { templateTokenSecretOnce.Do(func() { if envSecret := strings.TrimSpace(os.Getenv("TRAINING_TEMPLATE_TOKEN_SECRET")); envSecret != "" { templateTokenSecret = envSecret return } if envSecret := strings.TrimSpace(os.Getenv("JWT_SECRET")); envSecret != "" { templateTokenSecret = envSecret return } randomBytes := make([]byte, 32) if _, err := rand.Read(randomBytes); err != nil { panic(fmt.Sprintf("failed to generate training template token signing key: %v", err)) } templateTokenSecret = base64.StdEncoding.EncodeToString(randomBytes) }) return templateTokenSecret } // SignTrainingTemplateToken returns a tamper-evident download token: // base64url(payload).base64url(hmac). ExpiresAt zero = now + default validity. func SignTrainingTemplateToken(payload *TrainingTemplateTokenPayload) (string, error) { if payload == nil { return "", errors.New("training template token payload is required") } if payload.TenantID == 0 { return "", errors.New("training template token tenant is required") } if strings.TrimSpace(payload.TemplateKey) == "" { return "", errors.New("training template token key is required") } if payload.ExpiresAt == 0 { payload.ExpiresAt = time.Now().Add(TrainingTemplateTokenValidity).Unix() } raw, err := json.Marshal(payload) if err != nil { return "", fmt.Errorf("marshal training template token: %w", err) } mac := hmac.New(sha256.New, []byte(trainingTemplateTokenSigningKey())) mac.Write(raw) sig := mac.Sum(nil) return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig), nil } // VerifyTrainingTemplateToken validates the HMAC and expiry of a token and // returns its payload for the anonymous download endpoint. func VerifyTrainingTemplateToken(raw string) (*TrainingTemplateTokenPayload, error) { raw = strings.TrimSpace(raw) parts := strings.Split(raw, ".") if len(parts) != 2 { return nil, errors.New("invalid training template token format") } payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) if err != nil { return nil, fmt.Errorf("decode training template token payload: %w", err) } sigBytes, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { return nil, fmt.Errorf("decode training template token signature: %w", err) } mac := hmac.New(sha256.New, []byte(trainingTemplateTokenSigningKey())) mac.Write(payloadBytes) if !hmac.Equal(mac.Sum(nil), sigBytes) { return nil, errors.New("training template token signature mismatch") } var payload TrainingTemplateTokenPayload if err := json.Unmarshal(payloadBytes, &payload); err != nil { return nil, fmt.Errorf("unmarshal training template token: %w", err) } if payload.TenantID == 0 || strings.TrimSpace(payload.TemplateKey) == "" { return nil, errors.New("training template token tenant/key is required") } if time.Now().Unix() > payload.ExpiresAt { return nil, errors.New("training template token expired") } return &payload, nil }