cap

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 25, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package cap 实现了内嵌式 Cap 工作量证明(PoW)人机验证服务端。 算法移植自 Cap 官方 JS 实现(https://github.com/tiagozip/cap), 使用项目现有的 Redis 客户端替代文件系统存储。

Index

Constants

View Source
const (
	OperationCapChallenge = "/cap/challenge"
	OperationCapRedeem    = "/cap/redeem"
)

Cap 路由使用的 Kratos operation 常量,供外部白名单引用。

Variables

This section is empty.

Functions

func Register

func Register(s *khttp.Server, c *Cap)

Register 将 Cap 人机验证 HTTP 路由挂载到 Kratos HTTP 服务器,风格与其他服务注册一致。

注册路由(均无需认证,需将 OperationCapChallenge/OperationCapRedeem 加入白名单):

POST /v1/cap/challenge — 生成 PoW challenge,返回 {challenge, token, expires}
POST /v1/cap/redeem   — 提交 PoW 解答,换取一次性验证 token

Types

type Cap

type Cap struct {
	// contains filtered or unexported fields
}

Cap is the embedded Cap CAPTCHA server backed by Redis.

func New

func New(rdb *redis.Client) *Cap

New creates a new Cap instance backed by the given Redis client.

func (*Cap) CreateChallenge

func (c *Cap) CreateChallenge(ctx context.Context, conf *ChallengeConfig) (*ChallengeResponse, error)

CreateChallenge generates a new PoW challenge, stores it in Redis, and returns it.

func (*Cap) RedeemChallenge

func (c *Cap) RedeemChallenge(ctx context.Context, token string, solutions []int) (*RedeemResponse, error)

RedeemChallenge validates a PoW solution and, if valid, returns a one-time verification token.

func (*Cap) ValidateToken

func (c *Cap) ValidateToken(ctx context.Context, token string) (bool, error)

ValidateToken consumes a one-time verification token. Returns true if the token is valid and has not been used before.

type ChallengeConfig

type ChallengeConfig struct {
	ChallengeCount      int
	ChallengeSize       int
	ChallengeDifficulty int
	ExpiresMs           int64
}

ChallengeConfig holds configuration for challenge creation.

type ChallengeParams

type ChallengeParams struct {
	C int `json:"c"`
	S int `json:"s"`
	D int `json:"d"`
}

ChallengeParams are the c/s/d fields stored in Redis and returned to the client.

type ChallengeResponse

type ChallengeResponse struct {
	Challenge ChallengeParams `json:"challenge"`
	Token     string          `json:"token"`
	Expires   int64           `json:"expires"`
}

ChallengeResponse is returned by CreateChallenge.

type RedeemResponse

type RedeemResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
	Token   string `json:"token,omitempty"`
	Expires int64  `json:"expires,omitempty"`
}

RedeemResponse is returned by RedeemChallenge.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL