Compare commits

...

44 Commits

Author SHA1 Message Date
Alexander Andreev 455999a9d5
Added /v2 in module name. 2023-08-12 22:39:42 +04:00
Alexander Andreev dede76d13e
Simplified file structure. 2023-08-12 22:29:01 +04:00
Alexander Andreev ce1df27e3a
Removed code for a standalone executable. go min ver was downgraded to 1.12. 2023-08-12 22:23:52 +04:00
Alexander Andreev 4d9daca977
In README.md removed version. 2023-08-12 22:12:49 +04:00
Alexander Andreev 310dfb0fe9
Updated dependencies. 2023-08-12 22:12:05 +04:00
Alexander Andreev 406fb66c17
A little change to pkgdesc. Removed unused fields. Pass a VERSION var to make. Added a v prefix for tag and made use of pkgver. pkgrel was incremented. 2023-05-06 04:52:25 +04:00
Alexander Andreev 918fb18d22
Added a VERSION variable in Makefile. 2023-05-06 04:50:32 +04:00
Alexander Andreev a5f46d9187
A little update for README.md. 2023-05-06 04:49:57 +04:00
Alexander Andreev 352576385b
Removed bin/ dir. 2023-03-05 00:32:26 +04:00
Alexander Andreev e8129849c8
Version was up to 2.0.2. 2023-03-05 00:31:07 +04:00
Alexander Andreev 7c513f9f24
Updated golang.org/x/image dependency to v0.5.0. 2023-03-05 00:30:50 +04:00
Alexander Andreev 5a16c4d678
InMemoryCaptchaDB was renamed to InMemoryDB. 2023-03-05 00:30:24 +04:00
Alexander Andreev fe2c3c8e59
CaptchaDB interface was renamed to DB. 2023-03-05 00:29:44 +04:00
Alexander Andreev 0311a391ed
Replace arav.top with arav.su. 2023-03-05 00:18:52 +04:00
Alexander Andreev 4f254db2bb
Added tests for InMemoryCaptchaDB and DwellingCaptcha. 2023-01-12 04:42:23 +04:00
Alexander Andreev e26bdd64f5
Added more comments. 2023-01-12 04:41:09 +04:00
Alexander Andreev f3e68f4c41
Added missing expiry changing. 2023-01-12 04:40:54 +04:00
Alexander Andreev f9154ab02f
Removed unnecessary guard around delete(). 2023-01-12 04:39:22 +04:00
Alexander Andreev fcb656d4ea
Module name was changet to git.arav.top/Arav/justcaptcha. 2023-01-08 18:49:33 +04:00
Alexander Andreev 9bb80f1f6c
Version updated to 2.0.1. No drastic changes were made. Internal cleaning. Hope it is ready to be correctly used as a library. 2023-01-08 18:36:39 +04:00
Alexander Andreev ee93284cdc
Added a library usage example in README. 2023-01-08 18:34:35 +04:00
Alexander Andreev 073384cc34
ExpiryDate() func was being used in just one place, so it was removed. 2023-01-08 18:21:46 +04:00
Alexander Andreev 6ab62fc43b
getURLParam() was made into a private module func. 2023-01-08 17:53:13 +04:00
Alexander Andreev ea9877f6c4
HTTP server and handlers were restructurised. 2023-01-08 17:49:03 +04:00
Alexander Andreev 49a64f553e
README updated. 2023-01-08 17:38:51 +04:00
Alexander Andreev 275e3c500b
Dependency update. 2023-01-08 17:32:31 +04:00
Alexander Andreev e4225db960
Changed defaults. Now expiry is 10 minutes and socket named just as sock. 2023-01-08 17:04:20 +04:00
Alexander Andreev b91c24998a
SystemD service moved out to the root of init dir and renamed to systemd.service. 2023-01-08 17:02:43 +04:00
Alexander Andreev d7599bdf46
HTTP server moved to internal. DwellingCaptcha moved to pkg. 2023-01-08 17:00:19 +04:00
Alexander Andreev 29e4666bd9
Mention of 404 error was removed from GET /:captcha_id description. 2022-10-21 00:03:09 +04:00
Alexander Andreev 6e4242e6cd
Return of errors was removed from Image(), Solve(), IsSolved(), and Remove() methods. 2022-10-21 00:01:19 +04:00
Alexander Andreev c0d776fa40
Return of errors was removed for methods of CaptchaDB interface. 2022-10-20 23:50:42 +04:00
Alexander Andreev cebf4b572f
README updated. 404 codes for solving was removed. 2022-10-20 23:50:02 +04:00
Alexander Andreev be2f34f629
http.Error() func is used to send error messages and codes. 2022-10-20 23:16:30 +04:00
Alexander Andreev 93e1344846
Handlers are edited to work with modified interfaces. Status codes are changed. Now 404 is not being returned if parameter ?remove was set. 2022-10-20 22:58:14 +04:00
Alexander Andreev cc30010d3f
Field expireIn -> expiry. Comments were redacted. 2022-10-20 22:56:28 +04:00
Alexander Andreev d9aba868db
db.go. InMemoryCaptchaDB was moved out. ErrorNotFound is now public. And DefaultExpiredScanInterval is now a public const. For more security a string of random data added to the end of a hash. 2022-10-20 22:55:37 +04:00
Alexander Andreev 4078bb03bc
InMemoryCaptchaDB is now within its own package alongside with an instance. 2022-10-20 22:52:13 +04:00
Alexander Andreev 0e0c91b5c2
instance.go was removed and its content was made as part of InMemoryCaptchaDB. 2022-10-20 22:51:32 +04:00
Alexander Andreev b155900579
GET / was changed to POST / for a new CAPTCHA creation. And now captcha db is being initialised in handlers. 2022-10-20 22:50:49 +04:00
Alexander Andreev aa6534aa98
DwellingCaptcha's package was renamed to dwcaptcha. 2022-10-20 22:49:46 +04:00
Alexander Andreev 07c8a90ada
README updated. 2022-10-20 22:49:08 +04:00
Alexander Andreev fa47cfa20e
Updated version to 2.0.0. 2022-10-20 22:48:20 +04:00
Alexander Andreev 2c121322cf
Updated dependencies. 2022-10-20 22:47:57 +04:00
19 changed files with 350 additions and 607 deletions

View File

@ -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

View File

@ -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.2.0" -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

View File

@ -1,73 +1,36 @@
justcaptcha ver. 1.2.0
======================
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 plain text.
if ok := inmemdb.Solve(captchaID, answer); !ok {
... // not solved
}
// solved
...
#### HTTP codes
- `200` if created (and it always being created)
Check is CAPTCHA was solved:
### Get an image for a CAPTCHA
GET /:captcha_id/image?style=
Responds with an image in JPEG format.
An optional URL query parameter `style=` set a name of a CAPTCHA style if
implemented by used CAPTCHA implementation.
#### HTTP codes
- `200` if exists
- `404` if doesn't exist
- `500` if for some reason an image wasn't created
### Submit an answer
POST /:captcha_id
Accepts `application/x-www-form-urlencoded` content type.
It takes one parameter `answer=123456`.
Responds with an empty body and one of the HTTP codes.
#### HTTP codes
- `200` if solved
- `403` if not solved
- `404` if doesn't exist
### Check if captcha is solved
GET /:captcha_id?remove
Responds with an empty body and one of the HTTP codes.
If an optional `remove` URL query parameter without a value supplied. CAPTCHA
will be removed without check if it is solved and a HTTP code `200` will be sent.
Otherwise, a `403` HTTP code will be sent, and, e.g. browser will print an error
message to console. So, in this case it helps to keep a browser's console cleaner.
If CAPTCHA doesn't exist a `404` HTTP code still will be returned.
This can be useful to remove an unused CAPTCHA from a DB without waiting for it
to be expired. E.g. when a visitor requests for a new CAPTCHA because he struggle
to solve it.
#### HTTP codes
- `200` if solved
- `403` if not solved
- `404` if doesn't exist
if ok := inmemdb.IsSolved(captchaID); !ok {
... // not solved
}
// solved
...

View File

View File

@ -1,30 +0,0 @@
# Maintainer: Alexander "Arav" Andreev <me@arav.top>
pkgname=justcaptcha
pkgver=1.2.0
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.2.0.tar.gz')
noextract=()
md5sums=('SKIP')
build() {
cd "$srcdir/$pkgname"
make DESTDIR="$pkgdir/"
}
package() {
cd "$srcdir/$pkgname"
make DESTDIR="$pkgdir/" install
}

View File

@ -20,7 +20,8 @@ func NewIntAnswer() Answer {
// Captcha interface that should be implemented by a CAPTCHA.
type Captcha interface {
// Image generates and returns a pointer to 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
// Answer returns a pregenerated answer.
Answer() Answer
@ -37,14 +38,14 @@ type Captcha interface {
// 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),
}
}
@ -52,8 +53,6 @@ func (c *BaseCaptcha) Image(style string) *image.Image {
return nil
}
// Answer generates an integer answer for a CAPTCHA or just returns
// an existing one.
func (c *BaseCaptcha) Answer() Answer {
if c.answer == "" {
c.answer = NewIntAnswer()
@ -61,8 +60,6 @@ func (c *BaseCaptcha) Answer() Answer {
return c.answer
}
// Solve sets solved field to true if given answer is right and returns a result
// of a check.
func (c *BaseCaptcha) Solve(answer Answer) bool {
c.solved = c.answer == answer
return c.solved
@ -73,11 +70,5 @@ func (c *BaseCaptcha) IsSolved() bool {
}
func (c *BaseCaptcha) Expiry() time.Time {
return c.expireIn
}
// ExpiryDate returns a date when CAPTCHA expires. It adds a passed
// expiry duration to a current time.
func ExpiryDate(expiry time.Duration) time.Time {
return time.Now().Add(expiry)
return c.expiry
}

View File

@ -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)
}
}

42
db.go Normal file
View File

@ -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)
}

View File

@ -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!")
}
}

View File

@ -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
View File

@ -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
View File

@ -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=

View File

@ -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

159
inmemdb/inmemdb.go Normal file
View File

@ -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)
}

48
inmemdb/inmemdb_test.go Normal file
View File

@ -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())
}
}

View File

@ -1,38 +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 Remove(id captcha.ID) error {
return captchaDb.Remove(id)
}
func GetExpiry() time.Duration {
return captchaDb.GetExpiry()
}

View File

@ -1,82 +0,0 @@
package handlers
import (
"fmt"
"image/jpeg"
"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)+"\"")
jpeg.Encode(w, *captchaImage, &jpeg.Options{Quality: 20})
}
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"))
isJustRemove := r.URL.Query().Has("remove")
if isJustRemove {
err := captcha.Remove(captchaID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
}
return
}
solved, err := captcha.IsSolved(captchaID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
if !solved {
w.WriteHeader(http.StatusForbidden)
}
}

View File

@ -1,147 +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)
Remove(id ID) 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 {
delete(cdb.db, id)
return c.IsSolved(), nil
}
return false, errorNotFound
}
// Remove a CAPTCHA from a database.
func (cdb *InMemoryCaptchaDB) Remove(id ID) error {
cdb.Lock()
defer cdb.Unlock()
if _, ok := cdb.db[id]; ok {
delete(cdb.db, id)
return nil
}
return errorNotFound
}

View File

@ -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
}