Sharing refuses a key shorter than minLength characters (default 32, never under 16) or of fewer than minClasses kinds of lowercase, uppercase, digits and symbols (default 2, so random hex passes), saying so without showing it. Opening doesn't check. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package share
|
|
|
|
import (
|
|
"fmt"
|
|
"unicode"
|
|
)
|
|
|
|
// Rules are what a key's value must be to share with it: random enough
|
|
// that guessing it is out of reach, since anyone with a link can try.
|
|
type Rules struct {
|
|
MinLength int // characters
|
|
MinClasses int // kinds of character: lowercase, uppercase, digits, symbols
|
|
}
|
|
|
|
// DefaultRules take a random base64 or hex value (openssl rand -base64
|
|
// 32, or -hex 32) and refuse passwords made up to be remembered.
|
|
var DefaultRules = Rules{MinLength: 32, MinClasses: 2}
|
|
|
|
// Check reports what key lacks, without showing it.
|
|
func (r Rules) Check(key []byte) error {
|
|
r = r.withDefaults()
|
|
s := string(key)
|
|
var lower, upper, digit, symbol bool
|
|
for _, c := range s {
|
|
switch {
|
|
case unicode.IsLower(c):
|
|
lower = true
|
|
case unicode.IsUpper(c):
|
|
upper = true
|
|
case unicode.IsDigit(c):
|
|
digit = true
|
|
default:
|
|
symbol = true
|
|
}
|
|
}
|
|
kinds := 0
|
|
for _, has := range []bool{lower, upper, digit, symbol} {
|
|
if has {
|
|
kinds++
|
|
}
|
|
}
|
|
n := len([]rune(s))
|
|
if n >= r.MinLength && kinds >= r.MinClasses {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("the key's value is %d characters of %d kinds, and share.keyRules wants at least %d characters of %d kinds (lowercase, uppercase, digits, symbols): use a random one, like openssl rand -base64 32 makes",
|
|
n, kinds, r.MinLength, r.MinClasses)
|
|
}
|
|
|
|
func (r Rules) withDefaults() Rules {
|
|
if r.MinLength == 0 {
|
|
r.MinLength = DefaultRules.MinLength
|
|
}
|
|
if r.MinClasses == 0 {
|
|
r.MinClasses = DefaultRules.MinClasses
|
|
}
|
|
r.MinLength = max(r.MinLength, MinKey)
|
|
return r
|
|
}
|