Compare commits
52 Commits
Author | SHA1 | Date |
---|---|---|
Alexander Andreev | 455999a9d5 | |
Alexander Andreev | dede76d13e | |
Alexander Andreev | ce1df27e3a | |
Alexander Andreev | 4d9daca977 | |
Alexander Andreev | 310dfb0fe9 | |
Alexander Andreev | 406fb66c17 | |
Alexander Andreev | 918fb18d22 | |
Alexander Andreev | a5f46d9187 | |
Alexander Andreev | 352576385b | |
Alexander Andreev | e8129849c8 | |
Alexander Andreev | 7c513f9f24 | |
Alexander Andreev | 5a16c4d678 | |
Alexander Andreev | fe2c3c8e59 | |
Alexander Andreev | 0311a391ed | |
Alexander Andreev | 4f254db2bb | |
Alexander Andreev | e26bdd64f5 | |
Alexander Andreev | f3e68f4c41 | |
Alexander Andreev | f9154ab02f | |
Alexander Andreev | fcb656d4ea | |
Alexander Andreev | 9bb80f1f6c | |
Alexander Andreev | ee93284cdc | |
Alexander Andreev | 073384cc34 | |
Alexander Andreev | 6ab62fc43b | |
Alexander Andreev | ea9877f6c4 | |
Alexander Andreev | 49a64f553e | |
Alexander Andreev | 275e3c500b | |
Alexander Andreev | e4225db960 | |
Alexander Andreev | b91c24998a | |
Alexander Andreev | d7599bdf46 | |
Alexander Andreev | 29e4666bd9 | |
Alexander Andreev | 6e4242e6cd | |
Alexander Andreev | c0d776fa40 | |
Alexander Andreev | cebf4b572f | |
Alexander Andreev | be2f34f629 | |
Alexander Andreev | 93e1344846 | |
Alexander Andreev | cc30010d3f | |
Alexander Andreev | d9aba868db | |
Alexander Andreev | 4078bb03bc | |
Alexander Andreev | 0e0c91b5c2 | |
Alexander Andreev | b155900579 | |
Alexander Andreev | aa6534aa98 | |
Alexander Andreev | 07c8a90ada | |
Alexander Andreev | fa47cfa20e | |
Alexander Andreev | 2c121322cf | |
Alexander Andreev | 2c22ff00e6 | |
Alexander Andreev | d24b710ee5 | |
Alexander Andreev | bc800f0472 | |
Alexander Andreev | 7e506ee982 | |
Alexander Andreev | 691659c2d0 | |
Alexander Andreev | 0b064e8977 | |
Alexander Andreev | ae67f6aa4f | |
Alexander Andreev | c90f5db3a8 |
2
LICENSE
2
LICENSE
|
@ -1,6 +1,6 @@
|
|||
The MIT License
|
||||
|
||||
Copyright (c) 2022 Alexander "Arav" Andreev <me@arav.top>
|
||||
Copyright (c) 2022,2023 Alexander "Arav" Andreev <me@arav.su>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
31
Makefile
31
Makefile
|
@ -1,31 +0,0 @@
|
|||
PACKAGE_NAME=justcaptcha
|
||||
TARGET=${PACKAGE_NAME}d
|
||||
|
||||
SYSCTL=${shell which systemctl}
|
||||
SYSDDIR_=${shell pkg-config systemd --variable=systemdsystemunitdir}
|
||||
SYSDDIR=${SYSDDIR_:/%=%}
|
||||
DESTDIR=/
|
||||
|
||||
LDFLAGS=-ldflags "-s -w -X main.version=1.1.2" -tags osusergo,netgo
|
||||
|
||||
all: ${TARGET}
|
||||
|
||||
.PHONY: ${TARGET}
|
||||
|
||||
${TARGET}:
|
||||
go build -o bin/$@ ${LDFLAGS} cmd/$@/main.go
|
||||
|
||||
run:
|
||||
bin/${TARGET} -expiry 1m -listen 127.0.0.1:19134
|
||||
|
||||
install:
|
||||
install -Dm 0755 bin/${TARGET} ${DESTDIR}usr/bin/${TARGET}
|
||||
install -Dm 0644 LICENSE ${DESTDIR}usr/share/licenses/${PACKAGE_NAME}/LICENSE
|
||||
|
||||
install -Dm 0644 init/systemd/${PACKAGE_NAME}.service ${DESTDIR}${SYSDDIR}/${PACKAGE_NAME}.service
|
||||
|
||||
uninstall:
|
||||
rm ${DESTDIR}usr/bin/${TARGET}
|
||||
rm ${DESTDIR}usr/share/licenses/${PACKAGE_NAME}/LICENSE
|
||||
|
||||
rm ${DESTDIR}${SYSDDIR}/${PACKAGE_NAME}.service
|
75
README.md
75
README.md
|
@ -1,61 +1,36 @@
|
|||
justcaptcha ver. 1.1.2
|
||||
======================
|
||||
justcaptcha
|
||||
===========
|
||||
|
||||
A simple CAPTCHA service implementation.
|
||||
A simple CAPTCHA implementation.
|
||||
|
||||
## Usage
|
||||
An example using built-in "dwelling" implementation.
|
||||
|
||||
justcaptchad -expiry 5m -listen /var/run/justcaptchad/j.sock
|
||||
Create a new CAPTCHA:
|
||||
|
||||
`-expiry` takes time for CAPTCHA to be valid for in format X{s,m,h}.
|
||||
c := dwcaptcha.NewDwellingCaptcha(expiry)
|
||||
_, id := inmemdb.New(someAdditionalDataUsedInIDGenerationUsuallyIPAddr, c)
|
||||
|
||||
`-listen` is `ip:port` or `/path/to/unix.sock` to listen on.
|
||||
Get an image for a CAPTCHA:
|
||||
|
||||
## API
|
||||
i := inmemdb.Image(captchaID, captchaStyle)
|
||||
if i == nil {
|
||||
... // do something if there was no image returned
|
||||
}
|
||||
|
||||
### Get a new captcha
|
||||
jpeg.Encode(w, *i, &jpeg.Options{Quality: 20})
|
||||
|
||||
GET /
|
||||
Solve a CAPTCHA:
|
||||
|
||||
It will return an ID of a new captcha in plaintext.
|
||||
if ok := inmemdb.Solve(captchaID, answer); !ok {
|
||||
... // not solved
|
||||
}
|
||||
// solved
|
||||
...
|
||||
|
||||
#### HTTP codes
|
||||
- `200` if created
|
||||
Check is CAPTCHA was solved:
|
||||
|
||||
### Get an image for a captcha
|
||||
|
||||
GET /:captcha_id/image?style=
|
||||
|
||||
Responds with an image (e.g. in PNG format).
|
||||
|
||||
An optional query parameter `style=` could be supplied if captcha implementation
|
||||
support different styles.
|
||||
|
||||
#### HTTP codes
|
||||
- `200` if exists
|
||||
- `404` if doesn't exist
|
||||
- `500` if for some reason Image wasn't created
|
||||
|
||||
### Submit an answer
|
||||
|
||||
POST /:captcha_id
|
||||
|
||||
It takes one form-data parameter `answer=123456`.
|
||||
|
||||
Responds with empty body and one of HTTP codes.
|
||||
|
||||
#### HTTP codes
|
||||
- `200` if solved
|
||||
- `403` if not solved
|
||||
- `404` if doesn't exist
|
||||
|
||||
### Check if captcha is solved
|
||||
|
||||
GET /:captcha_id
|
||||
|
||||
Responds with empty body and one of HTTP codes.
|
||||
|
||||
#### HTTP codes
|
||||
- `200` if solved
|
||||
- `403` if not solved
|
||||
- `404` if doesn't exist
|
||||
if ok := inmemdb.IsSolved(captchaID); !ok {
|
||||
... // not solved
|
||||
}
|
||||
// solved
|
||||
...
|
|
@ -1,30 +0,0 @@
|
|||
# Maintainer: Alexander "Arav" Andreev <me@arav.top>
|
||||
pkgname=justcaptcha
|
||||
pkgver=1.1.2
|
||||
pkgrel=1
|
||||
pkgdesc="Just a CAPTCHA service"
|
||||
arch=('i686' 'x86_64' 'arm' 'armv6h' 'armv7h' 'aarch64')
|
||||
url="https://git.arav.top/Arav/justcaptcha"
|
||||
license=('MIT')
|
||||
groups=()
|
||||
depends=()
|
||||
makedepends=('go')
|
||||
provides=('justcaptcha')
|
||||
conflicts=('justcaptcha')
|
||||
replaces=()
|
||||
backup=()
|
||||
options=()
|
||||
install=
|
||||
source=('https://git.arav.top/Arav/justcaptcha/archive/1.1.2.tar.gz')
|
||||
noextract=()
|
||||
md5sums=('SKIP')
|
||||
|
||||
build() {
|
||||
cd "$srcdir/$pkgname"
|
||||
make DESTDIR="$pkgdir/"
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$srcdir/$pkgname"
|
||||
make DESTDIR="$pkgdir/" install
|
||||
}
|
|
@ -18,34 +18,34 @@ func NewIntAnswer() Answer {
|
|||
return (Answer(ans.String()))
|
||||
}
|
||||
|
||||
// Captcha interface that should be implemented by captcha.
|
||||
// Captcha interface that should be implemented by a CAPTCHA.
|
||||
type Captcha interface {
|
||||
// Image generates and returns an image of captcha.
|
||||
// Image generates an image of a CAPTCHA according to a passed style
|
||||
// and returns a pointer to it.
|
||||
Image(style string) *image.Image
|
||||
// GetAnswer returns a pregenerated answer.
|
||||
// Answer returns a pregenerated answer.
|
||||
Answer() Answer
|
||||
// Solve compares a stored answer with a passed one.
|
||||
// Sets field Solved to true if they are equal.
|
||||
Solve(answer Answer) bool
|
||||
// IsSolved returns field IsSolved.
|
||||
// IsSolved returns if a CAPTCHA is solved or not.
|
||||
IsSolved() bool
|
||||
// Expiry returns a date after what captcha will expire.
|
||||
// Expiry returns a date after what CAPTCHA will expire.
|
||||
Expiry() time.Time
|
||||
}
|
||||
|
||||
// BaseCaptcha is a base implementation of a CAPTCHA.
|
||||
//
|
||||
// All derivatives that embed this struct only need to
|
||||
// implement Image() method.
|
||||
// All derivatives that embed this struct only need to implement
|
||||
// an Image() method.
|
||||
type BaseCaptcha struct {
|
||||
answer Answer
|
||||
solved bool
|
||||
expireIn time.Time
|
||||
answer Answer
|
||||
solved bool
|
||||
expiry time.Time
|
||||
}
|
||||
|
||||
func NewBaseCaptcha(expiry time.Duration) *BaseCaptcha {
|
||||
return &BaseCaptcha{
|
||||
expireIn: ExpiryDate(expiry),
|
||||
expiry: time.Now().Add(expiry),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -70,9 +70,5 @@ func (c *BaseCaptcha) IsSolved() bool {
|
|||
}
|
||||
|
||||
func (c *BaseCaptcha) Expiry() time.Time {
|
||||
return c.expireIn
|
||||
}
|
||||
|
||||
func ExpiryDate(expiry time.Duration) time.Time {
|
||||
return time.Now().Add(expiry)
|
||||
return c.expiry
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"justcaptcha/internal/captcha"
|
||||
"justcaptcha/internal/handlers"
|
||||
"justcaptcha/pkg/server"
|
||||
"log"
|
||||
"net/netip"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var version string
|
||||
|
||||
var listenAddress *string = flag.String("listen", "/var/run/justcaptcha/c.sock", "listen address (ip:port|unix_path)")
|
||||
var captchaExpiry *time.Duration = flag.Duration("expiry", 5*time.Minute, "CAPTCHA expiry in format XX{s,m,h}, e.g. 5m, 300s")
|
||||
var showVersion *bool = flag.Bool("v", false, "show version")
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
log.SetFlags(0)
|
||||
|
||||
if *showVersion {
|
||||
fmt.Println("justcaptchad ver.", version, "\nCopyright (c) 2022 Alexander \"Arav\" Andreev <me@arav.top>")
|
||||
return
|
||||
}
|
||||
|
||||
captcha.Init(*captchaExpiry)
|
||||
|
||||
hand := handlers.New()
|
||||
srv := server.NewHttpServer()
|
||||
|
||||
srv.GET("/", hand.New)
|
||||
srv.POST("/:captcha", hand.Solve)
|
||||
srv.GET("/:captcha", hand.IsSolved)
|
||||
srv.GET("/:captcha/image", hand.Image)
|
||||
|
||||
var network string
|
||||
if !strings.ContainsRune(*listenAddress, ':') {
|
||||
network = "unix"
|
||||
defer os.Remove(*listenAddress)
|
||||
} else {
|
||||
ap, err := netip.ParseAddrPort(*listenAddress)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
if ap.Addr().Is4() {
|
||||
network = "tcp4"
|
||||
} else if ap.Addr().Is6() {
|
||||
network = "tcp6"
|
||||
}
|
||||
}
|
||||
|
||||
if err := srv.Start(network, *listenAddress); err != nil {
|
||||
log.Fatalln("failed to start a server:", err)
|
||||
}
|
||||
|
||||
doneSignal := make(chan os.Signal, 1)
|
||||
signal.Notify(doneSignal, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
<-doneSignal
|
||||
|
||||
if err := srv.Stop(); err != nil {
|
||||
log.Fatalln("failed to properly shutdown a server:", err)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package captcha
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const DefaultExpiredScanInterval = 60 * time.Second
|
||||
|
||||
// ID is a CAPTCHA identifier.
|
||||
type ID string
|
||||
|
||||
// NewID generates an ID as a sha256 hash of additionalData (usually IP-address),
|
||||
// current time, answer and more, it adds a set of random bytes and encodes all
|
||||
// of it with base64 in raw URL variant.
|
||||
func NewID(additionalData string, answer Answer) ID {
|
||||
idHash := sha256.New()
|
||||
|
||||
idHash.Write([]byte(additionalData))
|
||||
idHash.Write([]byte(strconv.FormatInt(time.Now().UnixMicro(), 16)))
|
||||
idHash.Write([]byte(answer))
|
||||
randData := make([]byte, 32)
|
||||
rand.Read(randData)
|
||||
idHash.Write(randData)
|
||||
|
||||
return ID(base64.RawURLEncoding.EncodeToString(idHash.Sum(nil)))
|
||||
}
|
||||
|
||||
// DB interface with all necessary methods.
|
||||
type DB interface {
|
||||
New(data string, captcha Captcha) (Captcha, ID)
|
||||
GetExpiry() time.Duration
|
||||
SetExpiry(expiry time.Duration)
|
||||
Image(id ID, style string) *image.Image
|
||||
Solve(id ID, answer Answer) bool
|
||||
IsSolved(id ID) bool
|
||||
Remove(id ID)
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package dwcaptcha_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.arav.su/Arav/justcaptcha/v2/dwcaptcha"
|
||||
)
|
||||
|
||||
const expiry = 10 * time.Minute
|
||||
|
||||
func TestCaptcha(t *testing.T) {
|
||||
captcha := dwcaptcha.NewDwellingCaptcha(expiry)
|
||||
|
||||
if diff := time.Until(captcha.Expiry()) - expiry; diff >= 1*time.Microsecond {
|
||||
t.Errorf("Difference %s is more than 1 microsecond", diff.String())
|
||||
}
|
||||
|
||||
if captcha.Image("") == nil {
|
||||
t.Error("image cannot be nil, but it is!")
|
||||
}
|
||||
|
||||
if !captcha.Solve(captcha.Answer()) {
|
||||
t.Error("for whatever reason, its own answer doesn't match itself O_O")
|
||||
}
|
||||
|
||||
if !captcha.IsSolved() {
|
||||
t.Error("after last test it should be true, but it is not!")
|
||||
}
|
||||
}
|
|
@ -1,11 +1,12 @@
|
|||
package captcha
|
||||
package dwcaptcha
|
||||
|
||||
import (
|
||||
"image"
|
||||
"justcaptcha/pkg/captcha"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
captcha "git.arav.su/Arav/justcaptcha/v2"
|
||||
|
||||
"github.com/fogleman/gg"
|
||||
)
|
||||
|
11
go.mod
11
go.mod
|
@ -1,13 +1,10 @@
|
|||
module justcaptcha
|
||||
module git.arav.su/Arav/justcaptcha/v2
|
||||
|
||||
go 1.18
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/fogleman/gg v1.3.0
|
||||
github.com/julienschmidt/httprouter v1.3.0
|
||||
)
|
||||
require github.com/fogleman/gg v1.3.0
|
||||
|
||||
require (
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 // indirect
|
||||
golang.org/x/image v0.11.0 // indirect
|
||||
)
|
||||
|
|
35
go.sum
35
go.sum
|
@ -2,9 +2,36 @@ github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
|
|||
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539 h1:/eM0PCrQI2xd471rI+snWuu251/+/jpBpZqir2mPdnU=
|
||||
golang.org/x/image v0.0.0-20220722155232-062f8c9fd539/go.mod h1:doUCurBvlfPMKfmIpRIywoHmhN3VyhnoFDbvIEWF4hY=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/image v0.11.0 h1:ds2RoQvBvYTiJkwpSFDwCcDFNX7DqjL2WsUgTNk0Ooo=
|
||||
golang.org/x/image v0.11.0/go.mod h1:bglhjqbqVuEb9e9+eNR45Jfu7D+T4Qan+NhQk8Ck2P8=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
|
|
@ -1,39 +0,0 @@
|
|||
[Unit]
|
||||
Description=A simple CAPTCHA service for your website
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Restart=on-failure
|
||||
DynamicUser=yes
|
||||
ExecStart=/usr/bin/justcaptchad -expiry 5m -listen /var/run/justcaptcha/j.sock
|
||||
|
||||
ReadOnlyPaths=/
|
||||
# Set here path to directory where uploads are stored.
|
||||
NoExecPaths=/
|
||||
ExecPaths=/usr/bin/justcaptchad
|
||||
|
||||
RuntimeDirectory=justcaptcha
|
||||
|
||||
AmbientCapabilities=
|
||||
CapabilityBoundingSet=
|
||||
|
||||
LockPersonality=true
|
||||
MemoryDenyWriteExecute=true
|
||||
NoNewPrivileges=true
|
||||
PrivateDevices=true
|
||||
ProtectClock=true
|
||||
ProtectControlGroups=true
|
||||
ProtectHome=true
|
||||
ProtectKernelLogs=true
|
||||
ProtectKernelModules=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectSystem=strict
|
||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||
RestrictNamespaces=true
|
||||
RestrictRealtime=true
|
||||
RestrictSUIDSGID=true
|
||||
SystemCallArchitectures=native
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -0,0 +1,159 @@
|
|||
package inmemdb
|
||||
|
||||
import (
|
||||
"image"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
captcha "git.arav.su/Arav/justcaptcha/v2"
|
||||
)
|
||||
|
||||
// InMemoryDB implementation that lives in a memory (map).
|
||||
type InMemoryDB struct {
|
||||
sync.Mutex
|
||||
|
||||
db map[captcha.ID]captcha.Captcha
|
||||
expiry time.Duration
|
||||
expiryScanInterval time.Duration
|
||||
}
|
||||
|
||||
// NewInMemoryDB returns an initialised instance of an InMemoryDB.
|
||||
// An expiry is a scan interval for expired CAPTCHAs (if passed a longer one,
|
||||
// resets to a default (captcha.DefaultExpiredScanInterval)).
|
||||
func NewInMemoryDB(expiry time.Duration) *InMemoryDB {
|
||||
db := &InMemoryDB{
|
||||
db: make(map[captcha.ID]captcha.Captcha),
|
||||
expiry: expiry}
|
||||
|
||||
if expiry < captcha.DefaultExpiredScanInterval {
|
||||
db.expiryScanInterval = expiry
|
||||
} else {
|
||||
db.expiryScanInterval = captcha.DefaultExpiredScanInterval
|
||||
}
|
||||
|
||||
go db.cleanExpired()
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
// New accepts a CAPTCHA instance, generates an ID and store it in a database.
|
||||
// A data string is an additional random data used to generate an ID,
|
||||
// e.g. an IP-address.
|
||||
func (imcdb *InMemoryDB) New(data string, cptcha captcha.Captcha) (captcha.Captcha, captcha.ID) {
|
||||
id := captcha.NewID(data, cptcha.Answer())
|
||||
|
||||
imcdb.Lock()
|
||||
imcdb.db[id] = cptcha
|
||||
imcdb.Unlock()
|
||||
|
||||
return cptcha, id
|
||||
}
|
||||
|
||||
// GetExpiry returns an expiry for a CAPTCHA.
|
||||
func (imcdb *InMemoryDB) GetExpiry() time.Duration {
|
||||
return imcdb.expiry
|
||||
}
|
||||
|
||||
// SetExpiry changes an expiry for a CAPTCHA and a scan interval. Scan interval
|
||||
// cannot be longer than a default, so if it is, then resets to a default.
|
||||
func (imcdb *InMemoryDB) SetExpiry(expiry time.Duration) {
|
||||
imcdb.expiry = expiry
|
||||
if expiry < captcha.DefaultExpiredScanInterval {
|
||||
imcdb.expiryScanInterval = expiry
|
||||
} else {
|
||||
imcdb.expiryScanInterval = captcha.DefaultExpiredScanInterval
|
||||
}
|
||||
}
|
||||
|
||||
// Image returns a freshly generated image for a CAPTCHA with style if
|
||||
// applicable.
|
||||
func (imcdb *InMemoryDB) Image(id captcha.ID, style string) *image.Image {
|
||||
imcdb.Lock()
|
||||
defer imcdb.Unlock()
|
||||
if c, ok := imcdb.db[id]; ok {
|
||||
return c.Image(style)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Solve compares given answer with a stored one and if failed
|
||||
// deletes a CAPTCHA from database.
|
||||
func (imcdb *InMemoryDB) Solve(id captcha.ID, answer captcha.Answer) bool {
|
||||
imcdb.Lock()
|
||||
defer imcdb.Unlock()
|
||||
if c, ok := imcdb.db[id]; ok {
|
||||
ok = c.Solve(answer)
|
||||
if !ok {
|
||||
delete(imcdb.db, id)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsSolved checks if CAPTCHA was solved and removes it
|
||||
// from a database.
|
||||
func (imcdb *InMemoryDB) IsSolved(id captcha.ID) bool {
|
||||
imcdb.Lock()
|
||||
defer imcdb.Unlock()
|
||||
if c, ok := imcdb.db[id]; ok {
|
||||
delete(imcdb.db, id)
|
||||
return c.IsSolved()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Remove a CAPTCHA from a database.
|
||||
func (imcdb *InMemoryDB) Remove(id captcha.ID) {
|
||||
imcdb.Lock()
|
||||
defer imcdb.Unlock()
|
||||
delete(imcdb.db, id)
|
||||
}
|
||||
|
||||
// cleanExpired removes expired CAPTCHAs in a loop.
|
||||
func (imcdb *InMemoryDB) cleanExpired() {
|
||||
for {
|
||||
sleepFor := imcdb.expiryScanInterval - (time.Duration(time.Now().Second()) % imcdb.expiryScanInterval)
|
||||
time.Sleep(sleepFor)
|
||||
|
||||
imcdb.Lock()
|
||||
for id, captcha := range imcdb.db {
|
||||
if time.Since(captcha.Expiry()) >= imcdb.expiry {
|
||||
delete(imcdb.db, id)
|
||||
}
|
||||
}
|
||||
imcdb.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// An instance of InMemoryDB
|
||||
|
||||
var imcdb = NewInMemoryDB(captcha.DefaultExpiredScanInterval)
|
||||
|
||||
func GetExpiry() time.Duration {
|
||||
return imcdb.GetExpiry()
|
||||
}
|
||||
|
||||
func SetExpiry(expiry time.Duration) {
|
||||
imcdb.SetExpiry(expiry)
|
||||
}
|
||||
|
||||
func New(data string, captcha captcha.Captcha) (captcha.Captcha, captcha.ID) {
|
||||
return imcdb.New(data, captcha)
|
||||
}
|
||||
|
||||
func Image(id captcha.ID, style string) *image.Image {
|
||||
return imcdb.Image(id, style)
|
||||
}
|
||||
|
||||
func Solve(id captcha.ID, answer captcha.Answer) bool {
|
||||
return imcdb.Solve(id, answer)
|
||||
}
|
||||
|
||||
func IsSolved(id captcha.ID) bool {
|
||||
return imcdb.IsSolved(id)
|
||||
}
|
||||
|
||||
func Remove(id captcha.ID) {
|
||||
imcdb.Remove(id)
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package inmemdb_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
captcha "git.arav.su/Arav/justcaptcha/v2"
|
||||
"git.arav.su/Arav/justcaptcha/v2/dwcaptcha"
|
||||
"git.arav.su/Arav/justcaptcha/v2/inmemdb"
|
||||
)
|
||||
|
||||
const expiry = 10 * time.Minute
|
||||
const testData = "192.168.0.1"
|
||||
|
||||
func TestInMemDBDefaultInstance(t *testing.T) {
|
||||
if inmemdb.GetExpiry() != captcha.DefaultExpiredScanInterval {
|
||||
t.Errorf("expiration is different from a default one (%v != %v)",
|
||||
inmemdb.GetExpiry(), captcha.DefaultExpiredScanInterval)
|
||||
}
|
||||
|
||||
inmemdb.SetExpiry(expiry)
|
||||
|
||||
if expiry != inmemdb.GetExpiry() {
|
||||
t.Errorf("Expected %v, but got %v", expiry, inmemdb.GetExpiry())
|
||||
}
|
||||
|
||||
captcha, captchaID := inmemdb.New(testData, dwcaptcha.NewDwellingCaptcha(expiry))
|
||||
|
||||
if inmemdb.Image(captchaID, "") == nil {
|
||||
t.Error("nil returned instead of an image.Image struct")
|
||||
}
|
||||
|
||||
if !inmemdb.Solve(captchaID, captcha.Answer()) {
|
||||
t.Error("CAPTCHA not solved. Looks like provided ID wasn't found")
|
||||
}
|
||||
|
||||
if !inmemdb.IsSolved(captchaID) {
|
||||
t.Error("last test solved a CAPTCHA, but IsSolved() returned false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInMemDBNewInstance(t *testing.T) {
|
||||
db := inmemdb.NewInMemoryDB(expiry)
|
||||
|
||||
if db.GetExpiry() != expiry {
|
||||
t.Errorf("expected expiry %v, but got %v", expiry, db.GetExpiry())
|
||||
}
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
package captcha
|
||||
|
||||
import (
|
||||
"image"
|
||||
"justcaptcha/pkg/captcha"
|
||||
"time"
|
||||
)
|
||||
|
||||
var captchaDb captcha.CaptchaDB
|
||||
|
||||
func Init(expiry time.Duration) {
|
||||
captchaDb = captcha.NewInMemoryCaptchaDB(expiry)
|
||||
}
|
||||
|
||||
func New(data string) (captcha.Captcha, captcha.ID) {
|
||||
dc := NewDwellingCaptcha(captchaDb.GetExpiry())
|
||||
return captchaDb.New(data, dc)
|
||||
}
|
||||
|
||||
func Image(id captcha.ID, style string) (*image.Image, error) {
|
||||
return captchaDb.Image(id, style)
|
||||
}
|
||||
|
||||
func Solve(id captcha.ID, answer captcha.Answer) (bool, error) {
|
||||
return captchaDb.Solve(id, answer)
|
||||
}
|
||||
|
||||
func IsSolved(id captcha.ID) (bool, error) {
|
||||
return captchaDb.IsSolved(id)
|
||||
}
|
||||
|
||||
func GetExpiry() time.Duration {
|
||||
return captchaDb.GetExpiry()
|
||||
}
|
|
@ -1,73 +0,0 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image/png"
|
||||
"justcaptcha/internal/captcha"
|
||||
pcaptcha "justcaptcha/pkg/captcha"
|
||||
"justcaptcha/pkg/server"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type CaptchaHandlers struct{}
|
||||
|
||||
func New() *CaptchaHandlers {
|
||||
return &CaptchaHandlers{}
|
||||
}
|
||||
|
||||
func (h *CaptchaHandlers) New(w http.ResponseWriter, r *http.Request) {
|
||||
_, id := captcha.New(r.RemoteAddr)
|
||||
|
||||
fmt.Fprint(w, id)
|
||||
}
|
||||
|
||||
func (h *CaptchaHandlers) Image(w http.ResponseWriter, r *http.Request) {
|
||||
captchaID := pcaptcha.ID(server.GetURLParam(r, "captcha"))
|
||||
captchaStyle := r.URL.Query().Get("style")
|
||||
|
||||
captchaImage, err := captcha.Image(captchaID, captchaStyle)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if captchaImage == nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Add("Content-Disposition", "inline; filename=\""+string(captchaID)+"\"")
|
||||
|
||||
png.Encode(w, *captchaImage)
|
||||
}
|
||||
|
||||
func (h *CaptchaHandlers) Solve(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
|
||||
captchaID := pcaptcha.ID(server.GetURLParam(r, "captcha"))
|
||||
answer := pcaptcha.Answer(r.FormValue("answer"))
|
||||
|
||||
ok, err := captcha.Solve(captchaID, answer)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *CaptchaHandlers) IsSolved(w http.ResponseWriter, r *http.Request) {
|
||||
captchaID := pcaptcha.ID(server.GetURLParam(r, "captcha"))
|
||||
|
||||
solved, err := captcha.IsSolved(captchaID)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if !solved {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}
|
|
@ -1,136 +0,0 @@
|
|||
package captcha
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"image"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errorNotFound = errors.New("captcha not found")
|
||||
|
||||
var defaultExpiredScanInterval = 60 * time.Second
|
||||
|
||||
type ID string
|
||||
|
||||
// NewID generates an ID as a sha256 hash of additionalData, current time
|
||||
// and answer encoded with base64 in raw URL variant.
|
||||
func NewID(additionalData string, answer Answer) ID {
|
||||
idHash := sha256.New()
|
||||
|
||||
idHash.Write([]byte(additionalData))
|
||||
idHash.Write([]byte(strconv.FormatInt(time.Now().UnixMicro(), 16)))
|
||||
idHash.Write([]byte(answer))
|
||||
|
||||
return ID(base64.RawURLEncoding.EncodeToString(idHash.Sum(nil)))
|
||||
}
|
||||
|
||||
type CaptchaDB interface {
|
||||
New(data string, captcha Captcha) (Captcha, ID)
|
||||
GetExpiry() time.Duration
|
||||
Image(id ID, style string) (*image.Image, error)
|
||||
Solve(id ID, answer Answer) (bool, error)
|
||||
IsSolved(id ID) (bool, error)
|
||||
cleanExpired()
|
||||
}
|
||||
|
||||
type InMemoryCaptchaDB struct {
|
||||
sync.Mutex
|
||||
|
||||
db map[ID]Captcha
|
||||
expireIn time.Duration
|
||||
expireScanInterval time.Duration
|
||||
}
|
||||
|
||||
func NewInMemoryCaptchaDB(expire time.Duration) *InMemoryCaptchaDB {
|
||||
db := &InMemoryCaptchaDB{
|
||||
db: make(map[ID]Captcha),
|
||||
expireIn: expire}
|
||||
|
||||
if expire < defaultExpiredScanInterval {
|
||||
db.expireScanInterval = expire
|
||||
} else {
|
||||
db.expireScanInterval = defaultExpiredScanInterval
|
||||
}
|
||||
|
||||
db.cleanExpired()
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
// New accepts an Captcha instance, generates an ID and store it in a database.
|
||||
// `data` string is an additional random data used to generate an ID,
|
||||
// e.g. IP-address.
|
||||
func (cdb *InMemoryCaptchaDB) New(data string, captcha Captcha) (Captcha, ID) {
|
||||
id := NewID(data, captcha.Answer())
|
||||
|
||||
cdb.Lock()
|
||||
cdb.db[id] = captcha
|
||||
cdb.Unlock()
|
||||
|
||||
return captcha, id
|
||||
}
|
||||
|
||||
// cleanExpired starts a goroutine that deletes expired CAPTCHAs.
|
||||
func (cdb *InMemoryCaptchaDB) cleanExpired() {
|
||||
go func() {
|
||||
for {
|
||||
sleepFor := cdb.expireScanInterval - (time.Duration(time.Now().Second()) % cdb.expireScanInterval)
|
||||
time.Sleep(sleepFor)
|
||||
|
||||
cdb.Lock()
|
||||
for id, captcha := range cdb.db {
|
||||
if time.Since(captcha.Expiry()) >= cdb.expireIn {
|
||||
delete(cdb.db, id)
|
||||
}
|
||||
}
|
||||
cdb.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// GetExpiry returns time for how long captcha will last.
|
||||
func (cdb *InMemoryCaptchaDB) GetExpiry() time.Duration {
|
||||
return cdb.expireIn
|
||||
}
|
||||
|
||||
// Image returns image for a captcha.
|
||||
func (cdb *InMemoryCaptchaDB) Image(id ID, style string) (*image.Image, error) {
|
||||
cdb.Lock()
|
||||
defer cdb.Unlock()
|
||||
if c, ok := cdb.db[id]; ok {
|
||||
return c.Image(style), nil
|
||||
}
|
||||
return nil, errorNotFound
|
||||
}
|
||||
|
||||
// Solve compares given answer with a stored one and if failed
|
||||
// deletes a captcha from database.
|
||||
func (cdb *InMemoryCaptchaDB) Solve(id ID, answer Answer) (bool, error) {
|
||||
cdb.Lock()
|
||||
defer cdb.Unlock()
|
||||
if c, ok := cdb.db[id]; ok {
|
||||
ok = c.Solve(answer)
|
||||
if !ok {
|
||||
delete(cdb.db, id)
|
||||
}
|
||||
return ok, nil
|
||||
}
|
||||
return false, errorNotFound
|
||||
}
|
||||
|
||||
// IsSolved checks if captcha was solved and removes it
|
||||
// from a database.
|
||||
func (cdb *InMemoryCaptchaDB) IsSolved(id ID) (bool, error) {
|
||||
cdb.Lock()
|
||||
defer cdb.Unlock()
|
||||
if c, ok := cdb.db[id]; ok {
|
||||
ok = c.IsSolved()
|
||||
delete(cdb.db, id)
|
||||
return ok, nil
|
||||
}
|
||||
return false, errorNotFound
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
type HttpServer struct {
|
||||
server *http.Server
|
||||
router *httprouter.Router
|
||||
}
|
||||
|
||||
func NewHttpServer() *HttpServer {
|
||||
r := httprouter.New()
|
||||
return &HttpServer{
|
||||
server: &http.Server{
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
Handler: r,
|
||||
},
|
||||
router: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *HttpServer) GET(path string, handler http.HandlerFunc) {
|
||||
s.router.Handler(http.MethodGet, path, handler)
|
||||
}
|
||||
|
||||
func (s *HttpServer) POST(path string, handler http.HandlerFunc) {
|
||||
s.router.Handler(http.MethodPost, path, handler)
|
||||
}
|
||||
|
||||
func (s *HttpServer) SetNotFoundHandler(handler http.HandlerFunc) {
|
||||
s.router.NotFound = handler
|
||||
}
|
||||
|
||||
// GetURLParam wrapper around underlying router for getting URL parameters.
|
||||
func GetURLParam(r *http.Request, param string) string {
|
||||
return httprouter.ParamsFromContext(r.Context()).ByName(param)
|
||||
}
|
||||
|
||||
func (s *HttpServer) Start(network, address string) error {
|
||||
listener, err := net.Listen(network, address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if listener.Addr().Network() == "unix" {
|
||||
os.Chmod(address, 0777)
|
||||
}
|
||||
|
||||
go func() {
|
||||
if err = s.server.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *HttpServer) Stop() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := s.server.Shutdown(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Loading…
Reference in New Issue