forked from mtusi2026/mtusi2026lab2
76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
package chat
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type cursorPayload struct {
|
|
Scope string `json:"scope"`
|
|
Owner string `json:"owner"`
|
|
CreatedAt string `json:"created_at"`
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
type cursorCodec struct {
|
|
secret [32]byte
|
|
}
|
|
|
|
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
|
|
payload, err := json.Marshal(cursorPayload{
|
|
Scope: scope,
|
|
Owner: owner,
|
|
CreatedAt: createdAt.UTC().Format(time.RFC3339Nano),
|
|
ID: id,
|
|
})
|
|
if err != nil {
|
|
panic("cannot encode cursor: " + err.Error())
|
|
}
|
|
signature := c.sign(payload)
|
|
return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(signature)
|
|
}
|
|
|
|
func (c cursorCodec) decode(raw, scope, owner string) (time.Time, string, error) {
|
|
parts := strings.Split(raw, ".")
|
|
if len(parts) != 2 {
|
|
return time.Time{}, "", errors.New("malformed cursor")
|
|
}
|
|
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
|
|
if err != nil {
|
|
return time.Time{}, "", errors.New("malformed cursor")
|
|
}
|
|
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
|
if err != nil || !hmac.Equal(signature, c.sign(payload)) {
|
|
return time.Time{}, "", errors.New("invalid cursor signature")
|
|
}
|
|
var value cursorPayload
|
|
if err := json.Unmarshal(payload, &value); err != nil {
|
|
return time.Time{}, "", errors.New("malformed cursor payload")
|
|
}
|
|
if value.Scope != scope || value.Owner != owner {
|
|
return time.Time{}, "", errors.New("cursor belongs to another resource")
|
|
}
|
|
parsedID, err := uuid.Parse(value.ID)
|
|
if err != nil || parsedID.String() != value.ID {
|
|
return time.Time{}, "", errors.New("malformed cursor id")
|
|
}
|
|
createdAt, err := time.Parse(time.RFC3339Nano, value.CreatedAt)
|
|
if err != nil {
|
|
return time.Time{}, "", errors.New("malformed cursor timestamp")
|
|
}
|
|
return createdAt, value.ID, nil
|
|
}
|
|
|
|
func (c cursorCodec) sign(payload []byte) []byte {
|
|
mac := hmac.New(sha256.New, c.secret[:])
|
|
_, _ = mac.Write(payload)
|
|
return mac.Sum(nil)
|
|
}
|