The main page and direct photo links open without a prompt. Each photo's pool is sealed with its own key, handed out by POST /k (served by the daemon in serve and export mode). The hold-and-solve card appears only for low-entropy clicks into a collection, too many low-entropy landings from one IP, or more than photo_limit photos per window, with escalating proof-of-work and a 429 cap. Build ids now sort chronologically within the same second. Co-Authored-By: Claude Opus 5.5 <[email protected]>
98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package protect
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/binary"
|
|
"fmt"
|
|
"hash"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
const (
|
|
SealMagic = "luphoto-sealed-1"
|
|
NonceSize = 12
|
|
SecretName = ".secret"
|
|
SecretSize = 32
|
|
)
|
|
|
|
func NewSecret() ([]byte, error) {
|
|
secret := make([]byte, SecretSize)
|
|
if _, err := rand.Read(secret); err != nil {
|
|
return nil, err
|
|
}
|
|
return secret, nil
|
|
}
|
|
|
|
func ReadSecret(buildDir string) ([]byte, error) {
|
|
secret, err := os.ReadFile(filepath.Join(buildDir, SecretName))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(secret) != SecretSize {
|
|
return nil, fmt.Errorf("build secret %s: expected %d bytes, found %d", buildDir, SecretSize, len(secret))
|
|
}
|
|
return secret, nil
|
|
}
|
|
|
|
type Keyer struct {
|
|
mac hash.Hash
|
|
buf []byte
|
|
sum []byte
|
|
}
|
|
|
|
func NewKeyer(secret []byte) *Keyer {
|
|
return &Keyer{mac: hmac.New(sha256.New, secret), buf: make([]byte, 0, 64), sum: make([]byte, 0, sha256.Size)}
|
|
}
|
|
|
|
func (k *Keyer) derive(label, hash string) [32]byte {
|
|
b := append(k.buf[:0], label...)
|
|
b = append(b, '|')
|
|
b = append(b, hash...)
|
|
k.buf = b
|
|
k.mac.Reset()
|
|
k.mac.Write(b)
|
|
k.sum = k.mac.Sum(k.sum[:0])
|
|
var out [32]byte
|
|
copy(out[:], k.sum)
|
|
return out
|
|
}
|
|
|
|
func (k *Keyer) Photo(hash string) [32]byte {
|
|
return k.derive("photo", hash)
|
|
}
|
|
|
|
func (k *Keyer) Cover() [32]byte {
|
|
return k.derive("cover", "")
|
|
}
|
|
|
|
func Seal(key [32]byte, plain []byte) (string, error) {
|
|
out := make([]byte, NonceSize+len(SealMagic)+len(plain))
|
|
if _, err := rand.Read(out[:NonceSize]); err != nil {
|
|
return "", err
|
|
}
|
|
body := out[NonceSize:]
|
|
copy(body, SealMagic)
|
|
copy(body[len(SealMagic):], plain)
|
|
XOR(key, out[:NonceSize], body)
|
|
return base64.StdEncoding.EncodeToString(out), nil
|
|
}
|
|
|
|
func XOR(key [32]byte, nonce, data []byte) {
|
|
var block [32 + NonceSize + 4]byte
|
|
copy(block[:32], key[:])
|
|
copy(block[32:], nonce)
|
|
for i := uint32(0); len(data) > 0; i++ {
|
|
binary.BigEndian.PutUint32(block[32+NonceSize:], i)
|
|
stream := sha256.Sum256(block[:])
|
|
n := min(len(stream), len(data))
|
|
for j := 0; j < n; j++ {
|
|
data[j] ^= stream[j]
|
|
}
|
|
data = data[n:]
|
|
}
|
|
}
|