Documentation
¶
Index ¶
- Constants
- Variables
- func BuildOtpAuthMigrationURI(accounts []OtpAuthMigrationAccount, opts *OtpAuthMigrationOptions) (string, error)
- func CreateSecret() ([]byte, error)
- func DecodeBase32(dst []byte, src string) (int, error)
- func EncodeBase32(data []byte) string
- func GenHotpDefault(secret []byte, counter uint64) (string, error)
- func GenTotpDefault(secret []byte) (string, error)
- func VerifyHotpDefault(secret []byte, code string, counter uint64) (bool, error)
- func VerifyTotpDefault(secret []byte, code string) (bool, error)
- type Algorithm
- type ClockSkewDetector
- func (d *ClockSkewDetector) CurrentOffset() int64
- func (d *ClockSkewDetector) DisableAutoAdjust()
- func (d *ClockSkewDetector) EnableAutoAdjust()
- func (d *ClockSkewDetector) IsAutoAdjust() bool
- func (d *ClockSkewDetector) Record(matchedOffset int64, windowUsed uint64)
- func (d *ClockSkewDetector) Report() SkewReport
- func (d *ClockSkewDetector) Reset()
- type GenOtpError
- type HMACProvider
- type HMACProviderFunc
- type HOTP
- func NewHOTP(secret []byte, algorithm Algorithm, digits uint32) (*HOTP, error)
- func NewHOTPFromHMACProvider(provider HMACProvider, algorithm Algorithm, digits uint32) (*HOTP, error)
- func NewHOTPFromSecretProvider(provider SecretProvider, algorithm Algorithm, digits uint32) (*HOTP, error)
- func NewHotpFromConfig(secret []byte, c HotpConfig) (*HOTP, error)
- func (h *HOTP) ClearSecret()
- func (h *HOTP) GenBound(counter uint64, context *OtpContext) (string, error)
- func (h *HOTP) Generate(counter uint64) (string, error)
- func (h *HOTP) Verify(code string, counter uint64) (bool, error)
- func (h *HOTP) VerifyBatch(reqs []HOTPVerifyRequest) []VerifyResult
- func (h *HOTP) VerifyBound(code string, counter uint64, context *OtpContext) (bool, error)
- func (h *HOTP) VerifyBoundBatch(reqs []HOTPVerifyBoundRequest) []VerifyResult
- func (h *HOTP) VerifyWithResync(code string, counter uint64, lookAhead uint64) (uint64, bool, error)
- type HOTPVerifyBoundRequest
- type HOTPVerifyRequest
- type HotpBuilder
- type HotpConfig
- type InMemoryReplayStore
- type KeyGen
- type Metrics
- func (m *Metrics) GetErrors() uint64
- func (m *Metrics) GetHotpGenerations() uint64
- func (m *Metrics) GetHotpVerifications() uint64
- func (m *Metrics) GetTotpGenerations() uint64
- func (m *Metrics) GetTotpVerifications() uint64
- func (m *Metrics) IncrementError()
- func (m *Metrics) IncrementHotpGeneration()
- func (m *Metrics) IncrementHotpVerification()
- func (m *Metrics) IncrementTotpGeneration()
- func (m *Metrics) IncrementTotpVerification()
- func (m *Metrics) Reset()
- type OtpAuthMigrationAccount
- type OtpAuthMigrationOptions
- type OtpAuthMigrationPayload
- type OtpAuthUri
- func (u *OtpAuthUri) Algorithm(algorithm Algorithm) *OtpAuthUri
- func (u *OtpAuthUri) Build() string
- func (u *OtpAuthUri) Counter(counter uint64) *OtpAuthUri
- func (u *OtpAuthUri) Digits(digits uint32) *OtpAuthUri
- func (u *OtpAuthUri) Issuer(issuer string) *OtpAuthUri
- func (u *OtpAuthUri) Period(period uint64) *OtpAuthUri
- func (u *OtpAuthUri) String() string
- type OtpContext
- type OtpContextBuilder
- func (b *OtpContextBuilder) Build() *OtpContext
- func (b *OtpContextBuilder) Custom(key, value string) *OtpContextBuilder
- func (b *OtpContextBuilder) Device(deviceID string) *OtpContextBuilder
- func (b *OtpContextBuilder) DistanceClass(class string) *OtpContextBuilder
- func (b *OtpContextBuilder) GeoBucket(bucket string) *OtpContextBuilder
- func (b *OtpContextBuilder) IP(ip string) *OtpContextBuilder
- func (b *OtpContextBuilder) Origin(origin string) *OtpContextBuilder
- func (b *OtpContextBuilder) Region(region string) *OtpContextBuilder
- func (b *OtpContextBuilder) Session(session string) *OtpContextBuilder
- type OtpType
- type ReplayStore
- type SecretProvider
- type SecretProviderFunc
- type SkewRecommend
- type SkewReport
- type TOTP
- func NewTOTP(secret []byte, algorithm Algorithm, digits uint32, period uint64) (*TOTP, error)
- func NewTOTPFromHMACProvider(provider HMACProvider, algorithm Algorithm, digits uint32, period uint64) (*TOTP, error)
- func NewTOTPFromSecretProvider(provider SecretProvider, algorithm Algorithm, digits uint32, period uint64) (*TOTP, error)
- func NewTotpFromConfig(secret []byte, c TotpConfig) (*TOTP, error)
- func (t *TOTP) ClearSecret()
- func (t *TOTP) GenBound(context *OtpContext, timeVal *uint64) (string, error)
- func (t *TOTP) Generate(timeVal *uint64) (string, error)
- func (t *TOTP) Verify(code string, timeVal *uint64, window uint64) (bool, error)
- func (t *TOTP) VerifyBatch(reqs []TOTPVerifyRequest) []VerifyResult
- func (t *TOTP) VerifyBound(code string, context *OtpContext, timeVal *uint64, window uint64) (bool, error)
- func (t *TOTP) VerifyBoundBatch(reqs []TOTPVerifyBoundRequest) []VerifyResult
- func (t *TOTP) VerifyTracking(code string, timeVal *uint64, window uint64, detector *ClockSkewDetector) (bool, error)
- type TOTPVerifyBoundRequest
- type TOTPVerifyRequest
- type TotpBuilder
- type TotpConfig
- type Verifier
- type VerifyResult
Examples ¶
Constants ¶
const ( DistanceClassSameArea = "same_area" DistanceClassNearby = "nearby" DistanceClassFar = "far" )
const ( MinSecretBytes = 16 DefaultSecretBytes = 20 )
Variables ¶
var ( ErrInvalidSecret = errors.New("invalid secret key") ErrInvalidCode = errors.New("invalid OTP code") ErrInvalidDigits = errors.New("invalid number of digits") ErrInvalidAlgorithm = errors.New("invalid algorithm") ErrInvalidCounter = errors.New("invalid counter value") ErrInvalidTime = errors.New("invalid time value") ErrVerificationFailed = errors.New("OTP verification failed") ErrRateLimited = errors.New("rate limited") ErrReplayAttack = errors.New("replay attack detected") ErrDstTooSmall = errors.New("destination buffer too small") ErrSecretProvider = errors.New("secret provider failure") ErrHMACProvider = errors.New("HMAC provider failure") ErrInvalidURI = errors.New("invalid otpauth URI") ErrInvalidMigration = errors.New("invalid otpauth-migration payload") )
Functions ¶
func BuildOtpAuthMigrationURI ¶ added in v1.2.2
func BuildOtpAuthMigrationURI( accounts []OtpAuthMigrationAccount, opts *OtpAuthMigrationOptions, ) (string, error)
func CreateSecret ¶
func EncodeBase32 ¶
func GenTotpDefault ¶
func VerifyHotpDefault ¶
Types ¶
type ClockSkewDetector ¶
type ClockSkewDetector struct {
// contains filtered or unexported fields
}
func NewClockSkewDetector ¶
func NewClockSkewDetector(capacity int) *ClockSkewDetector
func (*ClockSkewDetector) CurrentOffset ¶
func (d *ClockSkewDetector) CurrentOffset() int64
func (*ClockSkewDetector) DisableAutoAdjust ¶
func (d *ClockSkewDetector) DisableAutoAdjust()
func (*ClockSkewDetector) EnableAutoAdjust ¶
func (d *ClockSkewDetector) EnableAutoAdjust()
func (*ClockSkewDetector) IsAutoAdjust ¶
func (d *ClockSkewDetector) IsAutoAdjust() bool
func (*ClockSkewDetector) Record ¶
func (d *ClockSkewDetector) Record(matchedOffset int64, windowUsed uint64)
func (*ClockSkewDetector) Report ¶
func (d *ClockSkewDetector) Report() SkewReport
func (*ClockSkewDetector) Reset ¶
func (d *ClockSkewDetector) Reset()
type GenOtpError ¶
type GenOtpError struct {
Message string
}
func NewGenOtpError ¶
func NewGenOtpError(msg string) *GenOtpError
func (*GenOtpError) Error ¶
func (e *GenOtpError) Error() string
type HMACProvider ¶ added in v1.1.2
HMACProvider computes HMACs without exporting raw secret material to the library process. This is intended for HSM-native, KMS-native, or remote signing flows where the OTP secret must remain non-exportable.
type HMACProviderFunc ¶ added in v1.1.2
HMACProviderFunc adapts a function into an HMACProvider.
type HOTP ¶
type HOTP struct {
// contains filtered or unexported fields
}
func NewHOTPFromHMACProvider ¶ added in v1.1.2
func NewHOTPFromHMACProvider(provider HMACProvider, algorithm Algorithm, digits uint32) (*HOTP, error)
Example ¶
package main
import (
"crypto/hmac"
"crypto/sha256"
"fmt"
"github.com/robby031/genotp-go"
)
func main() {
secret := []byte("12345678901234567890")
provider := genotp.HMACProviderFunc(func(algorithm genotp.Algorithm, message []byte) ([]byte, error) {
// Replace this with a real HSM/KMS MAC call.
mac := hmac.New(sha256.New, secret)
mac.Write(message)
return mac.Sum(nil), nil
})
hotp, err := genotp.NewHOTPFromHMACProvider(provider, genotp.SHA256, 6)
if err != nil {
fmt.Println("build error:", err)
return
}
code, err := hotp.Generate(12)
if err != nil {
fmt.Println("generate error:", err)
return
}
fmt.Println(code)
}
Output: 360470
func NewHOTPFromSecretProvider ¶ added in v1.1.2
func NewHOTPFromSecretProvider(provider SecretProvider, algorithm Algorithm, digits uint32) (*HOTP, error)
func NewHotpFromConfig ¶
func NewHotpFromConfig(secret []byte, c HotpConfig) (*HOTP, error)
func (*HOTP) ClearSecret ¶
func (h *HOTP) ClearSecret()
func (*HOTP) GenBound ¶
func (h *HOTP) GenBound(counter uint64, context *OtpContext) (string, error)
func (*HOTP) VerifyBatch ¶ added in v1.1.2
func (h *HOTP) VerifyBatch(reqs []HOTPVerifyRequest) []VerifyResult
VerifyBatch verifies a batch of HOTP codes sequentially and returns one result per request. Each item preserves the same semantics as Verify.
func (*HOTP) VerifyBound ¶
func (*HOTP) VerifyBoundBatch ¶ added in v1.1.2
func (h *HOTP) VerifyBoundBatch(reqs []HOTPVerifyBoundRequest) []VerifyResult
VerifyBoundBatch verifies a batch of context-bound HOTP codes sequentially and returns one result per request. Each item preserves the same semantics as VerifyBound.
type HOTPVerifyBoundRequest ¶ added in v1.1.2
type HOTPVerifyBoundRequest struct {
Code string
Counter uint64
Context *OtpContext
}
type HOTPVerifyRequest ¶ added in v1.1.2
type HotpBuilder ¶
type HotpBuilder struct {
// contains filtered or unexported fields
}
func NewHotpBuilder ¶
func NewHotpBuilder() *HotpBuilder
func (*HotpBuilder) Algorithm ¶
func (b *HotpBuilder) Algorithm(algorithm Algorithm) *HotpBuilder
func (*HotpBuilder) Build ¶
func (b *HotpBuilder) Build() (*HOTP, error)
func (*HotpBuilder) Digits ¶
func (b *HotpBuilder) Digits(digits uint32) *HotpBuilder
func (*HotpBuilder) Secret ¶
func (b *HotpBuilder) Secret(secret []byte) *HotpBuilder
type HotpConfig ¶
func NewHotpConfig ¶
func NewHotpConfig() HotpConfig
func (HotpConfig) WithAlgorithm ¶
func (c HotpConfig) WithAlgorithm(algorithm Algorithm) HotpConfig
func (HotpConfig) WithDigits ¶
func (c HotpConfig) WithDigits(digits uint32) HotpConfig
type InMemoryReplayStore ¶
type InMemoryReplayStore struct {
// contains filtered or unexported fields
}
func NewInMemoryReplayStore ¶
func NewInMemoryReplayStore(maxSize int) *InMemoryReplayStore
func (*InMemoryReplayStore) CheckAndRecord ¶
func (*InMemoryReplayStore) Reset ¶
func (s *InMemoryReplayStore) Reset() error
func (*InMemoryReplayStore) Size ¶
func (s *InMemoryReplayStore) Size() int
type KeyGen ¶
type KeyGen struct{}
func (*KeyGen) FillSecret ¶
func (*KeyGen) GenerateDefaultSecret ¶
type Metrics ¶
type Metrics struct {
HotpGenerations atomic.Uint64
HotpVerifications atomic.Uint64
TotpGenerations atomic.Uint64
TotpVerifications atomic.Uint64
Errors atomic.Uint64
}
func NewMetrics ¶
func NewMetrics() *Metrics
func (*Metrics) GetHotpGenerations ¶
func (*Metrics) GetHotpVerifications ¶
func (*Metrics) GetTotpGenerations ¶
func (*Metrics) GetTotpVerifications ¶
func (*Metrics) IncrementError ¶
func (m *Metrics) IncrementError()
func (*Metrics) IncrementHotpGeneration ¶
func (m *Metrics) IncrementHotpGeneration()
func (*Metrics) IncrementHotpVerification ¶
func (m *Metrics) IncrementHotpVerification()
func (*Metrics) IncrementTotpGeneration ¶
func (m *Metrics) IncrementTotpGeneration()
func (*Metrics) IncrementTotpVerification ¶
func (m *Metrics) IncrementTotpVerification()
type OtpAuthMigrationAccount ¶ added in v1.2.2
type OtpAuthMigrationAccount struct {
Type OtpType `json:"type"`
Label string `json:"label"`
Issuer string `json:"issuer,omitempty"`
SecretB32 string `json:"secretB32"`
Algorithm Algorithm `json:"algorithm"`
Digits uint32 `json:"digits"`
Period uint64 `json:"period"`
Counter uint64 `json:"counter"`
}
type OtpAuthMigrationOptions ¶ added in v1.2.2
type OtpAuthMigrationPayload ¶ added in v1.2.2
type OtpAuthMigrationPayload struct {
Accounts []OtpAuthMigrationAccount `json:"accounts"`
Version int32 `json:"version"`
BatchSize int32 `json:"batchSize"`
BatchIndex int32 `json:"batchIndex"`
BatchID int32 `json:"batchId"`
}
func ParseOtpAuthMigrationURI ¶ added in v1.2.2
func ParseOtpAuthMigrationURI(raw string) (*OtpAuthMigrationPayload, error)
type OtpAuthUri ¶
type OtpAuthUri struct {
// contains filtered or unexported fields
}
func NewOtpAuthUri ¶
func NewOtpAuthUri(typ OtpType, label, secret string) *OtpAuthUri
func (*OtpAuthUri) Algorithm ¶
func (u *OtpAuthUri) Algorithm(algorithm Algorithm) *OtpAuthUri
func (*OtpAuthUri) Build ¶
func (u *OtpAuthUri) Build() string
func (*OtpAuthUri) Counter ¶
func (u *OtpAuthUri) Counter(counter uint64) *OtpAuthUri
func (*OtpAuthUri) Digits ¶
func (u *OtpAuthUri) Digits(digits uint32) *OtpAuthUri
func (*OtpAuthUri) Issuer ¶
func (u *OtpAuthUri) Issuer(issuer string) *OtpAuthUri
func (*OtpAuthUri) Period ¶
func (u *OtpAuthUri) Period(period uint64) *OtpAuthUri
func (*OtpAuthUri) String ¶
func (u *OtpAuthUri) String() string
type OtpContext ¶
type OtpContext struct {
// contains filtered or unexported fields
}
func NewOtpContext ¶
func NewOtpContext() *OtpContext
func OtpContextFromBytes ¶
func OtpContextFromBytes(b []byte) *OtpContext
func (*OtpContext) Bytes ¶
func (c *OtpContext) Bytes() []byte
func (*OtpContext) IsEmpty ¶
func (c *OtpContext) IsEmpty() bool
type OtpContextBuilder ¶
type OtpContextBuilder struct {
// contains filtered or unexported fields
}
func NewOtpContextBuilder ¶
func NewOtpContextBuilder() *OtpContextBuilder
func (*OtpContextBuilder) Build ¶
func (b *OtpContextBuilder) Build() *OtpContext
func (*OtpContextBuilder) Custom ¶
func (b *OtpContextBuilder) Custom(key, value string) *OtpContextBuilder
func (*OtpContextBuilder) Device ¶
func (b *OtpContextBuilder) Device(deviceID string) *OtpContextBuilder
func (*OtpContextBuilder) DistanceClass ¶ added in v1.1.2
func (b *OtpContextBuilder) DistanceClass(class string) *OtpContextBuilder
DistanceClass binds the OTP to a coarse proximity class. Invalid values are ignored to preserve builder ergonomics and compatibility.
func (*OtpContextBuilder) GeoBucket ¶ added in v1.1.2
func (b *OtpContextBuilder) GeoBucket(bucket string) *OtpContextBuilder
GeoBucket binds the OTP to a coarse location bucket generated by the application, such as a grid cell or geohash prefix chosen by the caller.
func (*OtpContextBuilder) IP ¶
func (b *OtpContextBuilder) IP(ip string) *OtpContextBuilder
func (*OtpContextBuilder) Origin ¶
func (b *OtpContextBuilder) Origin(origin string) *OtpContextBuilder
func (*OtpContextBuilder) Region ¶ added in v1.1.2
func (b *OtpContextBuilder) Region(region string) *OtpContextBuilder
Region binds the OTP to a coarse, application-defined area label such as "id-lmg-bluluk" or "us-nyc-midtown". This is intentionally more stable than raw latitude/longitude for production OTP flows.
func (*OtpContextBuilder) Session ¶
func (b *OtpContextBuilder) Session(session string) *OtpContextBuilder
type ReplayStore ¶
type SecretProvider ¶ added in v1.1.2
SecretProvider resolves secret material on demand for provider-backed HOTP and TOTP instances. Implementations may fetch from wrapped storage, a KMS unwrap flow, or other external secret managers.
type SecretProviderFunc ¶ added in v1.1.2
SecretProviderFunc adapts a function into a SecretProvider.
func (SecretProviderFunc) Secret ¶ added in v1.1.2
func (f SecretProviderFunc) Secret() ([]byte, error)
type SkewRecommend ¶
type SkewRecommend int
const ( InsufficientData SkewRecommend = iota NoActionNeeded ConsistentDrift WidenWindowOrCheckNtp )
func (SkewRecommend) String ¶
func (r SkewRecommend) String() string
type SkewReport ¶
type SkewReport struct {
SampleCount int
MeanOffset float64
NonZeroCount int
EdgeHitRatio float64
Recommend SkewRecommend
}
type TOTP ¶
type TOTP struct {
// contains filtered or unexported fields
}
func NewTOTPFromHMACProvider ¶ added in v1.1.2
func NewTOTPFromSecretProvider ¶ added in v1.1.2
func NewTOTPFromSecretProvider(provider SecretProvider, algorithm Algorithm, digits uint32, period uint64) (*TOTP, error)
Example ¶
package main
import (
"fmt"
"github.com/robby031/genotp-go"
)
func main() {
encryptedSecret := []byte("wrapped-user-secret")
provider := genotp.SecretProviderFunc(func() ([]byte, error) {
// Replace this with a real KMS decrypt or secret manager fetch.
_ = encryptedSecret
return []byte("12345678901234567890"), nil
})
totp, err := genotp.NewTOTPFromSecretProvider(provider, genotp.SHA1, 6, 30)
if err != nil {
fmt.Println("build error:", err)
return
}
timeVal := uint64(1234567890)
code, err := totp.Generate(&timeVal)
if err != nil {
fmt.Println("generate error:", err)
return
}
fmt.Println(code)
}
Output: 005924
func NewTotpFromConfig ¶
func NewTotpFromConfig(secret []byte, c TotpConfig) (*TOTP, error)
func (*TOTP) ClearSecret ¶
func (t *TOTP) ClearSecret()
func (*TOTP) GenBound ¶
func (t *TOTP) GenBound(context *OtpContext, timeVal *uint64) (string, error)
func (*TOTP) VerifyBatch ¶ added in v1.1.2
func (t *TOTP) VerifyBatch(reqs []TOTPVerifyRequest) []VerifyResult
VerifyBatch verifies a batch of TOTP codes sequentially and returns one result per request. Each item preserves the same semantics as Verify.
func (*TOTP) VerifyBound ¶
func (*TOTP) VerifyBoundBatch ¶ added in v1.1.2
func (t *TOTP) VerifyBoundBatch(reqs []TOTPVerifyBoundRequest) []VerifyResult
VerifyBoundBatch verifies a batch of context-bound TOTP codes sequentially and returns one result per request. Each item preserves the same semantics as VerifyBound.
func (*TOTP) VerifyTracking ¶
type TOTPVerifyBoundRequest ¶ added in v1.1.2
type TOTPVerifyBoundRequest struct {
Code string
Context *OtpContext
Time *uint64
Window uint64
}
type TOTPVerifyRequest ¶ added in v1.1.2
type TotpBuilder ¶
type TotpBuilder struct {
// contains filtered or unexported fields
}
func NewTotpBuilder ¶
func NewTotpBuilder() *TotpBuilder
func (*TotpBuilder) Algorithm ¶
func (b *TotpBuilder) Algorithm(algorithm Algorithm) *TotpBuilder
func (*TotpBuilder) Build ¶
func (b *TotpBuilder) Build() (*TOTP, error)
func (*TotpBuilder) Digits ¶
func (b *TotpBuilder) Digits(digits uint32) *TotpBuilder
func (*TotpBuilder) Period ¶
func (b *TotpBuilder) Period(period uint64) *TotpBuilder
func (*TotpBuilder) Secret ¶
func (b *TotpBuilder) Secret(secret []byte) *TotpBuilder
type TotpConfig ¶
func NewTotpConfig ¶
func NewTotpConfig() TotpConfig
func (TotpConfig) WithAlgorithm ¶
func (c TotpConfig) WithAlgorithm(algorithm Algorithm) TotpConfig
func (TotpConfig) WithDigits ¶
func (c TotpConfig) WithDigits(digits uint32) TotpConfig
func (TotpConfig) WithPeriod ¶
func (c TotpConfig) WithPeriod(period uint64) TotpConfig
type Verifier ¶
type Verifier struct {
// contains filtered or unexported fields
}
func NewVerifier ¶
func NewVerifierWithCapacity ¶
func NewVerifierWithStore ¶
func NewVerifierWithStore(maxAttempts uint32, store ReplayStore, ttl time.Duration) *Verifier
func (*Verifier) ClearUsedCodes ¶
func (v *Verifier) ClearUsedCodes()
func (*Verifier) IsRateLimited ¶
func (*Verifier) ResetAttempts ¶
func (v *Verifier) ResetAttempts()
func (*Verifier) VerifyWithContext ¶
func (v *Verifier) VerifyWithContext(code, expected string, issuedContext, requestContext *OtpContext) bool
func (*Verifier) VerifyWithReplayProtection ¶
type VerifyResult ¶ added in v1.1.2
VerifyResult holds the outcome of a single batch verification item.