Prepare verified laboratory 6 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 470d9d6f1e
commit 7d56e52fd0
335 changed files with 31206 additions and 72 deletions
+82
View File
@@ -0,0 +1,82 @@
package model
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"regexp"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
const MaxMessageRunes = 4000
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
AttachmentIDs []uuid.UUID
}
// MessageDraft — проверенное сообщение; отправитель берётся из идентификации,
// а не из тела запроса.
type MessageDraft struct {
ChatID uuid.UUID
SenderID uuid.UUID
Text string
Key string
PayloadHash string
AttachmentIDs []uuid.UUID
}
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func WithKey(d MessageDraft, key string) (MessageDraft, error) {
if !keyPattern.MatchString(key) {
return MessageDraft{}, invalidf("Idempotency-Key: 1–128 ASCII characters required")
}
canonical, _ := json.Marshal(struct {
Text string
Attachments []uuid.UUID
}{d.Text, d.AttachmentIDs})
sum := sha256.Sum256(canonical)
d.Key = key
d.PayloadHash = hex.EncodeToString(sum[:])
return d, nil
}
func NewMessageDraft(chatID, senderID uuid.UUID, text string, attachments ...[]uuid.UUID) (MessageDraft, error) {
ids := []uuid.UUID{}
if len(attachments) > 0 {
ids = slices.Clone(attachments[0])
if ids == nil {
ids = []uuid.UUID{}
}
}
if len(ids) > 10 {
return MessageDraft{}, invalidf("attachment_ids: at most 10")
}
seen := map[uuid.UUID]bool{}
for _, id := range ids {
if seen[id] {
return MessageDraft{}, invalidf("attachment_ids: duplicate")
}
seen[id] = true
}
if len(ids) == 0 || strings.TrimSpace(text) != "" {
if err := requireText("text", text, 1, MaxMessageRunes); err != nil {
return MessageDraft{}, err
}
} else if !utf8.ValidString(text) || utf8.RuneCountInString(text) > MaxMessageRunes || strings.ContainsRune(text, 0) {
return MessageDraft{}, invalidf("text: invalid optional text")
}
return MessageDraft{ChatID: chatID, SenderID: senderID, Text: text, AttachmentIDs: ids}, nil
}
func (m Message) Position() Position { return Position{CreatedAt: m.CreatedAt, ID: m.ID} }