mirror of
https://github.com/TecharoHQ/anubis.git
synced 2026-04-05 08:18:17 +00:00
Compare commits
35 Commits
Xe/embed-s
...
Xe/double-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a62bcb5e61 | ||
|
|
bb8baef871 | ||
|
|
60dc3f737b | ||
|
|
ac3d24f852 | ||
|
|
75ea1b60d5 | ||
|
|
1cf03535a5 | ||
|
|
c3ed405dbc | ||
|
|
8cdf58c9e6 | ||
|
|
1c170988c8 | ||
|
|
9439466ff2 | ||
|
|
4787aeca51 | ||
|
|
fb3637df95 | ||
|
|
26076b8520 | ||
|
|
edb84f03b7 | ||
|
|
b2d525bba4 | ||
|
|
00679aed66 | ||
|
|
03299024c5 | ||
|
|
f745d37d90 | ||
|
|
d12993e31d | ||
|
|
88b3e457ee | ||
|
|
bb2b113b63 | ||
|
|
6c283d0cd9 | ||
|
|
0037e214a1 | ||
|
|
29ae2a4b87 | ||
|
|
401e18f29f | ||
|
|
63591866aa | ||
|
|
f79d36d21e | ||
|
|
f5b5243b5e | ||
|
|
2011b83a44 | ||
|
|
8ed89a6c6e | ||
|
|
9430d0e6a5 | ||
|
|
8b9dafac51 | ||
|
|
9997130a7c | ||
|
|
e239083944 | ||
|
|
abf6c8de57 |
38
.github/ISSUE_TEMPLATE/bug_report.md
vendored
38
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,38 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: 'bug:'
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
61
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
Normal file
61
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
name: Bug report
|
||||
description: Create a report to help us improve
|
||||
|
||||
body:
|
||||
- type: textarea
|
||||
id: description-of-bug
|
||||
attributes:
|
||||
label: Describe the bug
|
||||
description: A clear and concise description of what the bug is.
|
||||
placeholder: I can reliably get an error when...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps-to-reproduce
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: |
|
||||
Steps to reproduce the behavior.
|
||||
placeholder: |
|
||||
1. Go to the following url...
|
||||
2. Click on...
|
||||
3. You get the following error: ...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected-behavior
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
description: |
|
||||
A clear and concise description of what you expected to happen.
|
||||
Ideally also describe *why* you expect it to happen.
|
||||
placeholder: Instead of displaying an error, it would...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: version-os
|
||||
attributes:
|
||||
label: Your operating system and its version.
|
||||
description: Unsure? Visit https://whatsmyos.com/
|
||||
placeholder: Android 13
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: version-browser
|
||||
attributes:
|
||||
label: Your browser and its version.
|
||||
description: Unsure? Visit https://www.whatsmybrowser.org/
|
||||
placeholder: Firefox 142
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Add any other context about the problem here.
|
||||
|
||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Security
|
||||
url: https://techaro.lol/contact
|
||||
about: Do not file security reports here. Email security@techaro.lol.
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: 'feature:'
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
39
.github/ISSUE_TEMPLATE/feature_request.yaml
vendored
Normal file
39
.github/ISSUE_TEMPLATE/feature_request.yaml
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
name: Feature request
|
||||
description: Suggest an idea for this project
|
||||
title: '[Feature request] '
|
||||
|
||||
body:
|
||||
- type: textarea
|
||||
id: description-of-bug
|
||||
attributes:
|
||||
label: Is your feature request related to a problem? Please describe.
|
||||
description: A clear and concise description of what the problem is that made you submit this report.
|
||||
placeholder: I am always frustrated, when...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: description-of-solution
|
||||
attributes:
|
||||
label: Solution you would like.
|
||||
description: A clear and concise description of what you want to happen.
|
||||
placeholder: Instead of behaving like this, there should be...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Describe alternatives you have considered.
|
||||
description: A clear and concise description of any alternative solutions or features you have considered.
|
||||
placeholder: Another workaround that would work, is...
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Add any other context (such as mock-ups, proof of concepts or screenshots) about the feature request here.
|
||||
validations:
|
||||
required: false
|
||||
9
.github/ISSUE_TEMPLATE/security.md
vendored
9
.github/ISSUE_TEMPLATE/security.md
vendored
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: Security report
|
||||
about: Do not file security reports here. Email security@techaro.lol.
|
||||
title: "security:"
|
||||
labels: ""
|
||||
assignees: Xe
|
||||
---
|
||||
|
||||
Do not file security reports here. Email security@techaro.lol.
|
||||
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -9,3 +9,4 @@ Checklist:
|
||||
- [ ] Added a description of the changes to the `[Unreleased]` section of docs/docs/CHANGELOG.md
|
||||
- [ ] Added test cases to [the relevant parts of the codebase](https://anubis.techaro.lol/docs/developer/code-quality)
|
||||
- [ ] Ran integration tests `npm run test:integration` (unsupported on Windows, please use WSL)
|
||||
- [ ] All of my commits have [verified signatures](https://anubis.techaro.lol/docs/developer/signed-commits)
|
||||
|
||||
6
.github/actions/spelling/expect.txt
vendored
6
.github/actions/spelling/expect.txt
vendored
@@ -1,4 +1,7 @@
|
||||
acs
|
||||
Actorified
|
||||
actorifiedstore
|
||||
actorify
|
||||
Aibrew
|
||||
alibaba
|
||||
alrest
|
||||
@@ -157,6 +160,7 @@ ifm
|
||||
Imagesift
|
||||
imgproxy
|
||||
impressum
|
||||
inbox
|
||||
inp
|
||||
internets
|
||||
IPTo
|
||||
@@ -214,6 +218,7 @@ nicksnyder
|
||||
nobots
|
||||
NONINFRINGEMENT
|
||||
nosleep
|
||||
nullglob
|
||||
OCOB
|
||||
ogtag
|
||||
oklch
|
||||
@@ -278,6 +283,7 @@ Seo
|
||||
setsebool
|
||||
shellcheck
|
||||
shirou
|
||||
shopt
|
||||
Sidetrade
|
||||
simprint
|
||||
sitemap
|
||||
|
||||
4
.github/workflows/docs-deploy.yml
vendored
4
.github/workflows/docs-deploy.yml
vendored
@@ -53,14 +53,14 @@ jobs:
|
||||
push: true
|
||||
|
||||
- name: Apply k8s manifests to limsa lominsa
|
||||
uses: actions-hub/kubectl@af345ed727f0268738e65be48422e463cc67c220 # v1.34.0
|
||||
uses: actions-hub/kubectl@f14933a23bc8c582b5aa7d108defd8e2cb9fa86d # v1.34.1
|
||||
env:
|
||||
KUBE_CONFIG: ${{ secrets.LIMSA_LOMINSA_KUBECONFIG }}
|
||||
with:
|
||||
args: apply -k docs/manifest
|
||||
|
||||
- name: Apply k8s manifests to limsa lominsa
|
||||
uses: actions-hub/kubectl@af345ed727f0268738e65be48422e463cc67c220 # v1.34.0
|
||||
uses: actions-hub/kubectl@f14933a23bc8c582b5aa7d108defd8e2cb9fa86d # v1.34.1
|
||||
env:
|
||||
KUBE_CONFIG: ${{ secrets.LIMSA_LOMINSA_KUBECONFIG }}
|
||||
with:
|
||||
|
||||
5
.github/workflows/smoke-tests.yml
vendored
5
.github/workflows/smoke-tests.yml
vendored
@@ -14,6 +14,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
test:
|
||||
- double_slash
|
||||
- forced-language
|
||||
- git-clone
|
||||
- git-push
|
||||
@@ -28,11 +29,11 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: latest
|
||||
|
||||
- uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
|
||||
- uses: actions/setup-go@44694675825211faa026b3c33043df3e48a5fa00 # v6.0.0
|
||||
with:
|
||||
go-version: stable
|
||||
|
||||
|
||||
10
.github/workflows/ssh-ci.yml
vendored
10
.github/workflows/ssh-ci.yml
vendored
@@ -12,12 +12,14 @@ permissions:
|
||||
jobs:
|
||||
ssh:
|
||||
if: github.repository == 'TecharoHQ/anubis'
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: alrest-techarohq
|
||||
strategy:
|
||||
matrix:
|
||||
host:
|
||||
- ubuntu@riscv64.techaro.lol
|
||||
- ci@ppc64le.techaro.lol
|
||||
- riscv64
|
||||
- ppc64le
|
||||
- aarch64-4k
|
||||
- aarch64-16k
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
@@ -33,7 +35,7 @@ jobs:
|
||||
name: id_rsa
|
||||
known_hosts: ${{ secrets.CI_SSH_KNOWN_HOSTS }}
|
||||
|
||||
- uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
|
||||
- uses: actions/setup-go@44694675825211faa026b3c33043df3e48a5fa00 # v6.0.0
|
||||
with:
|
||||
go-version: stable
|
||||
|
||||
|
||||
4
.github/workflows/zizmor.yml
vendored
4
.github/workflows/zizmor.yml
vendored
@@ -21,7 +21,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install the latest version of uv
|
||||
uses: astral-sh/setup-uv@4959332f0f014c5280e7eac8b70c90cb574c9f9b # v6.6.0
|
||||
uses: astral-sh/setup-uv@b75a909f75acd358c2196fb9a5f1299a9a8868a4 # v6.7.0
|
||||
|
||||
- name: Run zizmor 🌈
|
||||
run: uvx zizmor --format sarif . > results.sarif
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload SARIF file
|
||||
uses: github/codeql-action/upload-sarif@3c3833e0f8c1c83d449a7478aa59c036a9165498 # v3.29.11
|
||||
uses: github/codeql-action/upload-sarif@192325c86100d080feab897ff886c34abd4c83a3 # v3.30.3
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
category: zizmor
|
||||
|
||||
@@ -11,7 +11,7 @@ var Version = "devel"
|
||||
|
||||
// CookieName is the name of the cookie that Anubis uses in order to validate
|
||||
// access.
|
||||
var CookieName = "techaro.lol-anubis-auth"
|
||||
var CookieName = "techaro.lol-anubis"
|
||||
|
||||
// TestCookieName is the name of the cookie that Anubis uses in order to check
|
||||
// if cookies are enabled on the client's browser.
|
||||
|
||||
@@ -51,10 +51,12 @@ var (
|
||||
cookieExpiration = flag.Duration("cookie-expiration-time", anubis.CookieDefaultExpirationTime, "The amount of time the authorization cookie is valid for")
|
||||
cookiePrefix = flag.String("cookie-prefix", anubis.CookieName, "prefix for browser cookies created by Anubis")
|
||||
cookiePartitioned = flag.Bool("cookie-partitioned", false, "if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support")
|
||||
difficultyInJWT = flag.Bool("difficulty-in-jwt", false, "if true, adds a difficulty field in the JWT claims")
|
||||
useSimplifiedExplanation = flag.Bool("use-simplified-explanation", false, "if true, replaces the text when clicking \"Why am I seeing this?\" with a more simplified text for a non-tech-savvy audience.")
|
||||
forcedLanguage = flag.String("forced-language", "", "if set, this language is being used instead of the one from the request's Accept-Language header")
|
||||
hs512Secret = flag.String("hs512-secret", "", "secret used to sign JWTs, uses ed25519 if not set")
|
||||
cookieSecure = flag.Bool("cookie-secure", true, "if true, sets the secure flag on Anubis cookies")
|
||||
cookieSameSite = flag.String("cookie-same-site", "None", "sets the same site option on Anubis cookies, will auto-downgrade None to Lax if cookie-secure is false. Valid values are None, Lax, Strict, and Default.")
|
||||
ed25519PrivateKeyHex = flag.String("ed25519-private-key-hex", "", "private key used to sign JWTs, if not set a random one will be assigned")
|
||||
ed25519PrivateKeyHexFile = flag.String("ed25519-private-key-hex-file", "", "file name containing value for ed25519-private-key-hex")
|
||||
metricsBind = flag.String("metrics-bind", ":9090", "network address to bind metrics to")
|
||||
@@ -66,7 +68,7 @@ var (
|
||||
slogLevel = flag.String("slog-level", "INFO", "logging level (see https://pkg.go.dev/log/slog#hdr-Levels)")
|
||||
stripBasePrefix = flag.Bool("strip-base-prefix", false, "if true, strips the base prefix from requests forwarded to the target server")
|
||||
target = flag.String("target", "http://localhost:3923", "target to reverse proxy to, set to an empty string to disable proxying when only using auth request")
|
||||
targetSNI = flag.String("target-sni", "", "if set, the value of the TLS handshake hostname when forwarding requests to the target")
|
||||
targetSNI = flag.String("target-sni", "", "if set, TLS handshake hostname when forwarding requests to the target, if set to auto, use Host header")
|
||||
targetHost = flag.String("target-host", "", "if set, the value of the Host header when forwarding requests to the target")
|
||||
targetInsecureSkipVerify = flag.Bool("target-insecure-skip-verify", false, "if true, skips TLS validation for the backend")
|
||||
targetDisableKeepAlive = flag.Bool("target-disable-keepalive", false, "if true, disables HTTP keep-alive for the backend")
|
||||
@@ -81,6 +83,7 @@ var (
|
||||
versionFlag = flag.Bool("version", false, "print Anubis version")
|
||||
publicUrl = flag.String("public-url", "", "the externally accessible URL for this Anubis instance, used for constructing redirect URLs (e.g., for forwardAuth).")
|
||||
xffStripPrivate = flag.Bool("xff-strip-private", true, "if set, strip private addresses from X-Forwarded-For")
|
||||
customRealIPHeader = flag.String("custom-real-ip-header", "", "if set, read remote IP from header of this name (in case your environment doesn't set X-Real-IP header)")
|
||||
|
||||
thothInsecure = flag.Bool("thoth-insecure", false, "if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to")
|
||||
thothURL = flag.String("thoth-url", "", "if set, URL for Thoth, the IP reputation database for Anubis")
|
||||
@@ -142,6 +145,22 @@ func parseBindNetFromAddr(address string) (string, string) {
|
||||
return "", address
|
||||
}
|
||||
|
||||
func parseSameSite(s string) (http.SameSite) {
|
||||
switch strings.ToLower(s) {
|
||||
case "none":
|
||||
return http.SameSiteNoneMode
|
||||
case "lax":
|
||||
return http.SameSiteLaxMode
|
||||
case "strict":
|
||||
return http.SameSiteStrictMode
|
||||
case "default":
|
||||
return http.SameSiteDefaultMode
|
||||
default:
|
||||
log.Fatalf("invalid cookie same-site mode: %s, valid values are None, Lax, Strict, and Default", s)
|
||||
}
|
||||
return http.SameSiteDefaultMode
|
||||
}
|
||||
|
||||
func setupListener(network string, address string) (net.Listener, string) {
|
||||
formattedAddress := ""
|
||||
|
||||
@@ -217,23 +236,28 @@ func makeReverseProxy(target string, targetSNI string, targetHost string, insecu
|
||||
|
||||
if insecureSkipVerify || targetSNI != "" {
|
||||
transport.TLSClientConfig = &tls.Config{}
|
||||
if insecureSkipVerify {
|
||||
slog.Warn("TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed", "target", target)
|
||||
transport.TLSClientConfig.InsecureSkipVerify = true
|
||||
}
|
||||
if targetSNI != "" {
|
||||
transport.TLSClientConfig.ServerName = targetSNI
|
||||
}
|
||||
}
|
||||
if insecureSkipVerify {
|
||||
slog.Warn("TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed", "target", target)
|
||||
transport.TLSClientConfig.InsecureSkipVerify = true
|
||||
}
|
||||
if targetSNI != "" && targetSNI != "auto" {
|
||||
transport.TLSClientConfig.ServerName = targetSNI
|
||||
}
|
||||
|
||||
rp := httputil.NewSingleHostReverseProxy(targetUri)
|
||||
rp.Transport = transport
|
||||
|
||||
if targetHost != "" {
|
||||
if targetHost != "" || targetSNI == "auto" {
|
||||
originalDirector := rp.Director
|
||||
rp.Director = func(req *http.Request) {
|
||||
originalDirector(req)
|
||||
req.Host = targetHost
|
||||
if targetHost != "" {
|
||||
req.Host = targetHost
|
||||
}
|
||||
if targetSNI == "auto" {
|
||||
transport.TLSClientConfig.ServerName = req.Host
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,6 +341,16 @@ func main() {
|
||||
log.Fatalf("can't parse policy file: %v", err)
|
||||
}
|
||||
|
||||
// Warn if persistent storage is used without a configured signing key
|
||||
if policy.Store.IsPersistent() {
|
||||
if *hs512Secret == "" && *ed25519PrivateKeyHex == "" && *ed25519PrivateKeyHexFile == "" {
|
||||
slog.Warn("[misconfiguration] persistent storage backend is configured, but no private key is set. " +
|
||||
"Challenges will be invalidated when Anubis restarts. " +
|
||||
"Set HS512_SECRET, ED25519_PRIVATE_KEY_HEX, or ED25519_PRIVATE_KEY_HEX_FILE to ensure challenges survive service restarts. " +
|
||||
"See: https://anubis.techaro.lol/docs/admin/installation#key-generation")
|
||||
}
|
||||
}
|
||||
|
||||
ruleErrorIDs := make(map[string]string)
|
||||
for _, rule := range policy.Bots {
|
||||
if rule.Action != config.RuleDeny {
|
||||
@@ -421,8 +455,10 @@ func main() {
|
||||
WebmasterEmail: *webmasterEmail,
|
||||
OpenGraph: policy.OpenGraph,
|
||||
CookieSecure: *cookieSecure,
|
||||
CookieSameSite: parseSameSite(*cookieSameSite),
|
||||
PublicUrl: *publicUrl,
|
||||
JWTRestrictionHeader: *jwtRestrictionHeader,
|
||||
DifficultyInJWT: *difficultyInJWT,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("can't construct libanubis.Server: %v", err)
|
||||
@@ -430,6 +466,7 @@ func main() {
|
||||
|
||||
var h http.Handler
|
||||
h = s
|
||||
h = internal.CustomRealIPHeader(*customRealIPHeader, h)
|
||||
h = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)
|
||||
h = internal.XForwardedForToXRealIP(h)
|
||||
h = internal.XForwardedForUpdate(*xffStripPrivate, h)
|
||||
|
||||
@@ -46,6 +46,11 @@ func main() {
|
||||
)
|
||||
}
|
||||
|
||||
if strings.Contains(*dockerTags, ",") {
|
||||
newTags := strings.Join(strings.Split(*dockerTags, ","), "\n")
|
||||
dockerTags = &newTags
|
||||
}
|
||||
|
||||
setOutput("docker_image", strings.SplitN(*dockerTags, "\n", 2)[0])
|
||||
|
||||
version, err := run("git describe --tags --always --dirty")
|
||||
|
||||
@@ -14,6 +14,12 @@ func Zilch[T any]() T {
|
||||
type Impl[K comparable, V any] struct {
|
||||
data map[K]decayMapEntry[V]
|
||||
lock sync.RWMutex
|
||||
|
||||
// deleteCh receives decay-deletion requests from readers.
|
||||
deleteCh chan deleteReq[K]
|
||||
// stopCh stops the background cleanup worker.
|
||||
stopCh chan struct{}
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
type decayMapEntry[V any] struct {
|
||||
@@ -21,30 +27,38 @@ type decayMapEntry[V any] struct {
|
||||
expiry time.Time
|
||||
}
|
||||
|
||||
// deleteReq is a request to remove a key if its expiry timestamp still matches
|
||||
// the observed one. This prevents racing with concurrent Set updates.
|
||||
type deleteReq[K comparable] struct {
|
||||
key K
|
||||
expiry time.Time
|
||||
}
|
||||
|
||||
// New creates a new DecayMap of key type K and value type V.
|
||||
//
|
||||
// Key types must be comparable to work with maps.
|
||||
func New[K comparable, V any]() *Impl[K, V] {
|
||||
return &Impl[K, V]{
|
||||
data: make(map[K]decayMapEntry[V]),
|
||||
m := &Impl[K, V]{
|
||||
data: make(map[K]decayMapEntry[V]),
|
||||
deleteCh: make(chan deleteReq[K], 1024),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
m.wg.Add(1)
|
||||
go m.cleanupWorker()
|
||||
return m
|
||||
}
|
||||
|
||||
// expire forcibly expires a key by setting its time-to-live one second in the past.
|
||||
func (m *Impl[K, V]) expire(key K) bool {
|
||||
m.lock.RLock()
|
||||
// Use a single write lock to avoid RUnlock->Lock convoy.
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
val, ok := m.data[key]
|
||||
m.lock.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
m.lock.Lock()
|
||||
val.expiry = time.Now().Add(-1 * time.Second)
|
||||
m.data[key] = val
|
||||
m.lock.Unlock()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -53,19 +67,14 @@ func (m *Impl[K, V]) expire(key K) bool {
|
||||
// If the value does not exist, return false. Return true after
|
||||
// deletion.
|
||||
func (m *Impl[K, V]) Delete(key K) bool {
|
||||
m.lock.RLock()
|
||||
_, ok := m.data[key]
|
||||
m.lock.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
// Use a single write lock to avoid RUnlock->Lock convoy.
|
||||
m.lock.Lock()
|
||||
delete(m.data, key)
|
||||
m.lock.Unlock()
|
||||
|
||||
return true
|
||||
defer m.lock.Unlock()
|
||||
_, ok := m.data[key]
|
||||
if ok {
|
||||
delete(m.data, key)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// Get gets a value from the DecayMap by key.
|
||||
@@ -81,13 +90,12 @@ func (m *Impl[K, V]) Get(key K) (V, bool) {
|
||||
}
|
||||
|
||||
if time.Now().After(value.expiry) {
|
||||
m.lock.Lock()
|
||||
// Since previously reading m.data[key], the value may have been updated.
|
||||
// Delete the entry only if the expiry time is still the same.
|
||||
if m.data[key].expiry.Equal(value.expiry) {
|
||||
delete(m.data, key)
|
||||
// Defer decay deletion to the background worker to avoid convoy.
|
||||
select {
|
||||
case m.deleteCh <- deleteReq[K]{key: key, expiry: value.expiry}:
|
||||
default:
|
||||
// Channel full: drop request; a future Cleanup() or Get will retry.
|
||||
}
|
||||
m.lock.Unlock()
|
||||
|
||||
return Zilch[V](), false
|
||||
}
|
||||
@@ -125,3 +133,64 @@ func (m *Impl[K, V]) Len() int {
|
||||
defer m.lock.RUnlock()
|
||||
return len(m.data)
|
||||
}
|
||||
|
||||
// Close stops the background cleanup worker. It's optional to call; maps live
|
||||
// for the process lifetime in many cases. Call in tests or when you know you no
|
||||
// longer need the map to avoid goroutine leaks.
|
||||
func (m *Impl[K, V]) Close() {
|
||||
close(m.stopCh)
|
||||
m.wg.Wait()
|
||||
}
|
||||
|
||||
// cleanupWorker batches decay deletions to minimize lock contention.
|
||||
func (m *Impl[K, V]) cleanupWorker() {
|
||||
defer m.wg.Done()
|
||||
batch := make([]deleteReq[K], 0, 64)
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
flush := func() {
|
||||
if len(batch) == 0 {
|
||||
return
|
||||
}
|
||||
m.applyDeletes(batch)
|
||||
// reset batch without reallocating
|
||||
batch = batch[:0]
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case req := <-m.deleteCh:
|
||||
batch = append(batch, req)
|
||||
case <-ticker.C:
|
||||
flush()
|
||||
case <-m.stopCh:
|
||||
// Drain any remaining requests then exit
|
||||
for {
|
||||
select {
|
||||
case req := <-m.deleteCh:
|
||||
batch = append(batch, req)
|
||||
default:
|
||||
flush()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Impl[K, V]) applyDeletes(batch []deleteReq[K]) {
|
||||
now := time.Now()
|
||||
m.lock.Lock()
|
||||
for _, req := range batch {
|
||||
entry, ok := m.data[req.key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Only delete if the expiry is unchanged and already past.
|
||||
if entry.expiry.Equal(req.expiry) && now.After(entry.expiry) {
|
||||
delete(m.data, req.key)
|
||||
}
|
||||
}
|
||||
m.lock.Unlock()
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
func TestImpl(t *testing.T) {
|
||||
dm := New[string, string]()
|
||||
t.Cleanup(dm.Close)
|
||||
|
||||
dm.Set("test", "hi", 5*time.Minute)
|
||||
|
||||
@@ -28,10 +29,24 @@ func TestImpl(t *testing.T) {
|
||||
if ok {
|
||||
t.Error("got value even though it was supposed to be expired")
|
||||
}
|
||||
|
||||
// Deletion of expired entries after Get is deferred to a background worker.
|
||||
// Assert it eventually disappears from the map.
|
||||
deadline := time.Now().Add(200 * time.Millisecond)
|
||||
for time.Now().Before(deadline) {
|
||||
if dm.Len() == 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if dm.Len() != 0 {
|
||||
t.Fatalf("expected background cleanup to remove expired key; len=%d", dm.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanup(t *testing.T) {
|
||||
dm := New[string, string]()
|
||||
t.Cleanup(dm.Close)
|
||||
|
||||
dm.Set("test1", "hi1", 1*time.Second)
|
||||
dm.Set("test2", "hi2", 2*time.Second)
|
||||
|
||||
@@ -13,9 +13,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
<!-- This changes the project to: -->
|
||||
|
||||
- Document missing environment variables in installation guide: `SLOG_LEVEL`, `COOKIE_PREFIX`, `FORCED_LANGUAGE`, and `TARGET_DISABLE_KEEPALIVE` ([#1086](https://github.com/TecharoHQ/anubis/pull/1086))
|
||||
- Fixed `robots2policy` to properly group consecutive user agents into `any:` instead of only processing the last one ([#925](https://github.com/TecharoHQ/anubis/pull/925))
|
||||
- Add `-custom-real-ip-header` flag to get the original request IP from a different header than `x-real-ip`.
|
||||
- Add `contentLength` variable to bot expressions.
|
||||
- Add `COOKIE_SAME_SITE_MODE` to force anubis cookies SameSite value, and downgrade automatically from `None` to `Lax` if cookie is insecure.
|
||||
- Fix lock convoy problem in decaymap ([#1103](https://github.com/TecharoHQ/anubis/issues/1103)).
|
||||
- Fix lock convoy problem in bbolt by implementing the actor pattern ([#1103](https://github.com/TecharoHQ/anubis/issues/1103)).
|
||||
- Document missing environment variables in installation guide: `SLOG_LEVEL`, `COOKIE_PREFIX`, `FORCED_LANGUAGE`, and `TARGET_DISABLE_KEEPALIVE` ([#1086](https://github.com/TecharoHQ/anubis/pull/1086)).
|
||||
- Add validation warning when persistent storage is used without setting signing keys.
|
||||
- Fixed `robots2policy` to properly group consecutive user agents into `any:` instead of only processing the last one ([#925](https://github.com/TecharoHQ/anubis/pull/925)).
|
||||
- Add the [`s3api` storage backend](./admin/policies.mdx#s3api) to allow Anubis to use S3 API compatible object storage as its storage backend.
|
||||
- Fix a "stutter" in the cookie name prefix so the auth cookie is named `techaro.lol-anubis-auth` instead of `techaro.lol-anubis-auth-auth`.
|
||||
- Make `cmd/containerbuild` support commas for separating elements of the `--docker-tags` argument as well as newlines.
|
||||
- Add the `DIFFICULTY_IN_JWT` option, which allows one to add the `difficulty` field in the JWT claims which indicates the difficulty of the token ([#1063](https://github.com/TecharoHQ/anubis/pull/1063)).
|
||||
- Ported the client-side JS to TypeScript to avoid egregious errors in the future.
|
||||
- Fixes concurrency problems with very old browsers ([#1082](https://github.com/TecharoHQ/anubis/issues/1082)).
|
||||
- Randomly use the Refresh header instead of the meta refresh tag in the metarefresh challenge.
|
||||
- Update OpenRC service to truncate the runtime directory before starting Anubis.
|
||||
- Allow multiple consecutive slashes in a row in application paths ([#754](https://github.com/TecharoHQ/anubis/issues/754)).
|
||||
- Add option to set `targetSNI` to special keyword 'auto' to indicate that it should be automatically set to the request Host name ([424](https://github.com/TecharoHQ/anubis/issues/424)).
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
|
||||
@@ -126,6 +126,34 @@ Your directory tree should look like this, assuming your data is in `./your_fold
|
||||
|
||||
For an example directory tree using some off-the-shelf images the Tango icon set, see the [testdata](https://github.com/TecharoHQ/botstopper/tree/main/testdata/static/img) folder.
|
||||
|
||||
### Header-based overlay dispatch
|
||||
|
||||
If you run BotStopper in a multi-tenant environment where each tenant needs its own branding, BotStopper supports the ability to use request header values to direct asset reads to different folders under your `OVERLAY_FOLDER`. One of the most common ways to do this is based on the HTTP Host of the request. For example, if you set `ASSET_LOOKUP_HEADER=Host` in BotStopper's environment:
|
||||
|
||||
```text
|
||||
$OVERLAY_FOLDER
|
||||
├── static
|
||||
│ ├── css
|
||||
│ │ ├── custom.css
|
||||
│ │ └── eyesore.css
|
||||
│ └── img
|
||||
│ ├── happy.webp
|
||||
│ ├── pensive.webp
|
||||
│ └── reject.webp
|
||||
└── test.anubis.techaro.lol
|
||||
└── static
|
||||
├── css
|
||||
│ └── custom.css
|
||||
└── img
|
||||
├── happy.webp
|
||||
├── pensive.webp
|
||||
└── reject.webp
|
||||
```
|
||||
|
||||
Requests to `test.anubis.techaro.lol` will load assets in `$OVERLAY_FOLDER/test.anubis.techaro.lol/static` and all other requests will load them from `$OVERLAY_FOLDER/static`.
|
||||
|
||||
For an example, look at [the testdata folder in the BotStopper repo](https://github.com/TecharoHQ/botstopper/tree/main/testdata).
|
||||
|
||||
### Custom CSS
|
||||
|
||||
CSS customization is done mainly with CSS variables. View [the example custom CSS file](https://github.com/TecharoHQ/botstopper/blob/main/testdata/static/css/custom.css) for more information about what can be customized.
|
||||
@@ -199,7 +227,9 @@ $ du -hs *
|
||||
|
||||
## Custom HTML templates
|
||||
|
||||
If you need to completely control the HTML layout of all Anubis pages, you can customize the entire page with `USE_TEMPLATES=true`. This uses Go's standard library [html/template](https://pkg.go.dev/html/template) package to template HTML responses. In order to use this, you must define the following templates:
|
||||
If you need to completely control the HTML layout of all Anubis pages, you can customize the entire page with `USE_TEMPLATES=true`. This uses Go's standard library [html/template](https://pkg.go.dev/html/template) package to template HTML responses. Your templates can contain whatever HTML you want. The only catch is that you MUST include `{{ .Head }}` in the `<head>` element for challenge pages, and you MUST include `{{ .Body }}` in the `<body>` element for all pages.
|
||||
|
||||
In order to use this, you must define the following templates:
|
||||
|
||||
| Template path | Usage |
|
||||
| :----------------------------------------- | :---------------------------------------------- |
|
||||
@@ -207,6 +237,12 @@ If you need to completely control the HTML layout of all Anubis pages, you can c
|
||||
| `$OVERLAY_FOLDER/templates/error.tmpl` | Error pages |
|
||||
| `$OVERLAY_FOLDER/templates/impressum.tmpl` | [Impressum](./configuration/impressum.mdx) page |
|
||||
|
||||
:::note
|
||||
|
||||
Currently HTML templates don't work together with [Header-based overlay dispatch](#header-based-overlay-dispatch). This is a known issue that will be fixed soon. If you enable header-based overlay dispatch, BotStopper will use the global `templates` folder instead of using the templates present in the overlay.
|
||||
|
||||
:::
|
||||
|
||||
Here are minimal (but working) examples for each template:
|
||||
|
||||
<details>
|
||||
|
||||
@@ -20,6 +20,8 @@ Upstream: X-Forwarded-For: CF_IP
|
||||
|
||||
As a workaround, you should configure your web server to parse an alternative source (such as `CF-Connecting-IP`), or pre-process the incoming `X-Forwarded-For` with your web server to ensure it only contains the real client IP address, then pass it to Anubis as `X-Forwarded-For`.
|
||||
|
||||
If you do not control the web server upstream of Anubis, the `custom-real-ip-header` command line flag accepts a header value that Anubis will read the real client IP address from. Anubis will set the `X-Real-IP` header to the IP address found in the custom header.
|
||||
|
||||
The `X-Real-IP` header will be automatically inferred from `X-Forwarded-For` if not set, setting it explicitly is not necessary as long as `X-Forwarded-For` contains only the real client IP. However setting it explicitly can eliminate spoofed values if your web server doesn't set this.
|
||||
|
||||
See [Cloudflare](environments/cloudflare.mdx) for an example configuration.
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
Anubis supports multiple challenge methods:
|
||||
|
||||
- [Meta Refresh](./metarefresh.mdx)
|
||||
- [Preact](./preact.mdx)
|
||||
- [Proof of Work](./proof-of-work.mdx)
|
||||
|
||||
Read the documentation to know which method is best for you.
|
||||
|
||||
@@ -103,6 +103,7 @@ Anubis exposes the following variables to expressions:
|
||||
| :-------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------- |
|
||||
| `headers` | `map[string, string]` | The [headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers) of the request being processed. | `{"User-Agent": "Mozilla/5.0 Gecko/20100101 Firefox/137.0"}` |
|
||||
| `host` | `string` | The [HTTP hostname](https://web.dev/articles/url-parts#host) the request is targeted to. | `anubis.techaro.lol` |
|
||||
| `contentLength` | `int64` | The numerical value of the `Content-Length` header. |
|
||||
| `load_1m` | `double` | The current system load average over the last one minute. This is useful for making [load-based checks](#using-the-system-load-average). |
|
||||
| `load_5m` | `double` | The current system load average over the last five minutes. This is useful for making [load-based checks](#using-the-system-load-average). |
|
||||
| `load_15m` | `double` | The current system load average over the last fifteen minutes. This is useful for making [load-based checks](#using-the-system-load-average). |
|
||||
|
||||
@@ -2,8 +2,16 @@
|
||||
title: Setting up Anubis
|
||||
---
|
||||
|
||||
import EnterpriseOnly from "@site/src/components/EnterpriseOnly";
|
||||
import RandomKey from "@site/src/components/RandomKey";
|
||||
|
||||
export const EO = () => (
|
||||
<>
|
||||
<EnterpriseOnly link="./botstopper/" />
|
||||
<div style={{ marginBottom: "0.5rem" }} />
|
||||
</>
|
||||
);
|
||||
|
||||
Anubis is meant to sit between your reverse proxy (such as Nginx or Caddy) and your target service. One instance of Anubis must be used per service you are protecting.
|
||||
|
||||
<center>
|
||||
@@ -58,38 +66,46 @@ Currently the following settings are configurable via the policy file:
|
||||
|
||||
Anubis uses these environment variables for configuration:
|
||||
|
||||
| Environment Variable | Default value | Explanation |
|
||||
|:-------------------------------|:------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `BASE_PREFIX` | unset | If set, adds a global prefix to all Anubis endpoints (everything starting with `/.within.website/x/anubis/`). For example, setting this to `/myapp` would make Anubis accessible at `/myapp/` instead of `/`. This is useful when running Anubis behind a reverse proxy that routes based on path prefixes. |
|
||||
| `BIND` | `:8923` | The network address that Anubis listens on. For `unix`, set this to a path: `/run/anubis/instance.sock` |
|
||||
| `BIND_NETWORK` | `tcp` | The address family that Anubis listens on. Accepts `tcp`, `unix` and anything Go's [`net.Listen`](https://pkg.go.dev/net#Listen) supports. |
|
||||
| `COOKIE_DOMAIN` | unset | The domain the Anubis challenge pass cookie should be set to. This should be set to the domain you bought from your registrar (EG: `techaro.lol` if your webapp is running on `anubis.techaro.lol`). See this [stackoverflow explanation of cookies](https://stackoverflow.com/a/1063760) for more information.<br/><br/>Note that unlike `REDIRECT_DOMAINS`, you should never include a port number in this variable. |
|
||||
| `COOKIE_DYNAMIC_DOMAIN` | false | If set to true, automatically set cookie domain fields based on the hostname of the request. EG: if you are making a request to `anubis.techaro.lol`, the Anubis cookie will be valid for any subdomain of `techaro.lol`. |
|
||||
| `COOKIE_EXPIRATION_TIME` | `168h` | The amount of time the authorization cookie is valid for. |
|
||||
| `COOKIE_PARTITIONED` | `false` | If set to `true`, enables the [partitioned (CHIPS) flag](https://developers.google.com/privacy-sandbox/cookies/chips), meaning that Anubis inside an iframe has a different set of cookies than the domain hosting the iframe. |
|
||||
| `COOKIE_PREFIX` | `anubis-cookie` | The prefix used for browser cookies created by Anubis. Useful for customization or avoiding conflicts with other applications. |
|
||||
| `COOKIE_SECURE` | `true` | If set to `true`, enables the [Secure flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies), meaning that the cookies will only be transmitted over HTTPS. If Anubis is used in an unsecure context (plain HTTP), this will be need to be set to false |
|
||||
| `DIFFICULTY` | `4` | The difficulty of the challenge, or the number of leading zeroes that must be in successful responses. |
|
||||
| `ED25519_PRIVATE_KEY_HEX` | unset | The hex-encoded ed25519 private key used to sign Anubis responses. If this is not set, Anubis will generate one for you. This should be exactly 64 characters long. When running multiple instances on the same base domain, the key must be the same across all instances. See below for details. |
|
||||
| `ED25519_PRIVATE_KEY_HEX_FILE` | unset | Path to a file containing the hex-encoded ed25519 private key. Only one of this or its sister option may be set. |
|
||||
| `JWT_RESTRICTION_HEADER` | `X-Real-IP` | If set, the JWT is only valid if the current value of this header matches the value when the JWT was created. You can use it e.g. to restrict a JWT to the source IP of the user using `X-Real-IP`. |
|
||||
| `METRICS_BIND` | `:9090` | The network address that Anubis serves Prometheus metrics on. See `BIND` for more information. |
|
||||
| `METRICS_BIND_NETWORK` | `tcp` | The address family that the Anubis metrics server listens on. See `BIND_NETWORK` for more information. |
|
||||
| `OG_EXPIRY_TIME` | `24h` | The expiration time for the Open Graph tag cache. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
|
||||
| `OG_PASSTHROUGH` | `false` | If set to `true`, Anubis will enable Open Graph tag passthrough. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
|
||||
| `OG_CACHE_CONSIDER_HOST` | `false` | If set to `true`, Anubis will consider the host in the Open Graph tag cache key. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
|
||||
| `POLICY_FNAME` | unset | The file containing [bot policy configuration](./policies.mdx). See the bot policy documentation for more details. If unset, the default bot policy configuration is used. |
|
||||
| `PUBLIC_URL` | unset | The externally accessible URL for this Anubis instance, used for constructing redirect URLs (e.g., for Traefik forwardAuth). |
|
||||
| `REDIRECT_DOMAINS` | unset | If set, restrict the domains that Anubis can redirect to when passing a challenge.<br/><br/>If this is unset, Anubis may redirect to any domain which could cause security issues in the unlikely case that an attacker passes a challenge for your browser and then tricks you into clicking a link to your domain.<br/><br/>Note that if you are hosting Anubis on a non-standard port (`https://example:com:8443`, `http://www.example.net:8080`, etc.), you must also include the port number here. |
|
||||
| `SERVE_ROBOTS_TXT` | `false` | If set `true`, Anubis will serve a default `robots.txt` file that disallows all known AI scrapers by name and then additionally disallows every scraper. This is useful if facts and circumstances make it difficult to change the underlying service to serve such a `robots.txt` file. |
|
||||
| `SLOG_LEVEL` | `INFO` | The log level for structured logging. Valid values are `DEBUG`, `INFO`, `WARN`, and `ERROR`. Set to `DEBUG` to see all requests, evaluations, and detailed diagnostic information. |
|
||||
| `SOCKET_MODE` | `0770` | _Only used when at least one of the `*_BIND_NETWORK` variables are set to `unix`._ The socket mode (permissions) for Unix domain sockets. |
|
||||
| `STRIP_BASE_PREFIX` | `false` | If set to `true`, strips the base prefix from request paths when forwarding to the target server. This is useful when your target service expects to receive requests without the base prefix. For example, with `BASE_PREFIX=/foo` and `STRIP_BASE_PREFIX=true`, a request to `/foo/bar` would be forwarded to the target as `/bar`. |
|
||||
| `TARGET` | `http://localhost:3923` | The URL of the service that Anubis should forward valid requests to. Supports Unix domain sockets, set this to a URI like so: `unix:///path/to/socket.sock`. |
|
||||
| `USE_REMOTE_ADDRESS` | unset | If set to `true`, Anubis will take the client's IP from the network socket. For production deployments, it is expected that a reverse proxy is used in front of Anubis, which pass the IP using headers, instead. |
|
||||
| `USE_SIMPLIFIED_EXPLANATION` | false | If set to `true`, replaces the text when clicking "Why am I seeing this?" with a more simplified text for a non-tech-savvy audience. |
|
||||
| `WEBMASTER_EMAIL` | unset | If set, shows a contact email address when rendering error pages. This email address will be how users can get in contact with administrators. |
|
||||
| `XFF_STRIP_PRIVATE` | `true` | If set, strip private addresses from `X-Forwarded-For` headers. To unset this, you must set `XFF_STRIP_PRIVATE=false` or `--xff-strip-private=false`. |
|
||||
| Environment Variable | Default value | Explanation |
|
||||
| :----------------------------- | :---------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ASSET_LOOKUP_HEADER` | unset | <EO /> If set, use the contents of this header in requests when looking up custom assets in `OVERLAY_FOLDER`. See [Header-based overlay dispatch](./botstopper.mdx#header-based-overlay-dispatch) for more details. |
|
||||
| `BASE_PREFIX` | unset | If set, adds a global prefix to all Anubis endpoints (everything starting with `/.within.website/x/anubis/`). For example, setting this to `/myapp` would make Anubis accessible at `/myapp/` instead of `/`. This is useful when running Anubis behind a reverse proxy that routes based on path prefixes. |
|
||||
| `BIND` | `:8923` | The network address that Anubis listens on. For `unix`, set this to a path: `/run/anubis/instance.sock` |
|
||||
| `BIND_NETWORK` | `tcp` | The address family that Anubis listens on. Accepts `tcp`, `unix` and anything Go's [`net.Listen`](https://pkg.go.dev/net#Listen) supports. |
|
||||
| `CHALLENGE_TITLE` | unset | <EO /> If set, override the translation stack to show a custom title for challenge pages such as "Making sure your connection is secure!". See [Customizing messages](./botstopper.mdx#customizing-messages) for more details. |
|
||||
| `COOKIE_DOMAIN` | unset | The domain the Anubis challenge pass cookie should be set to. This should be set to the domain you bought from your registrar (EG: `techaro.lol` if your webapp is running on `anubis.techaro.lol`). See this [stackoverflow explanation of cookies](https://stackoverflow.com/a/1063760) for more information.<br/><br/>Note that unlike `REDIRECT_DOMAINS`, you should never include a port number in this variable. |
|
||||
| `COOKIE_DYNAMIC_DOMAIN` | false | If set to true, automatically set cookie domain fields based on the hostname of the request. EG: if you are making a request to `anubis.techaro.lol`, the Anubis cookie will be valid for any subdomain of `techaro.lol`. |
|
||||
| `COOKIE_EXPIRATION_TIME` | `168h` | The amount of time the authorization cookie is valid for. |
|
||||
| `CUSTOM_REAL_IP_HEADER` | unset | If set, Anubis will read the client's real IP address from this header, and set it in `X-Real-IP` header. |
|
||||
| `COOKIE_PARTITIONED` | `false` | If set to `true`, enables the [partitioned (CHIPS) flag](https://developers.google.com/privacy-sandbox/cookies/chips), meaning that Anubis inside an iframe has a different set of cookies than the domain hosting the iframe. |
|
||||
| `COOKIE_PREFIX` | `anubis-cookie` | The prefix used for browser cookies created by Anubis. Useful for customization or avoiding conflicts with other applications. |
|
||||
| `COOKIE_SECURE` | `true` | If set to `true`, enables the [Secure flag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies#block_access_to_your_cookies), meaning that the cookies will only be transmitted over HTTPS. If Anubis is used in an unsecure context (plain HTTP), this will be need to be set to false |
|
||||
| `COOKIE_SAME_SITE` | `None` | Controls the cookie’s [`SameSite` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value). Allowed: `None`, `Lax`, `Strict`, `Default`. `None` permits cross-site use but modern browsers require it to be **Secure**—so if `COOKIE_SECURE=false` or you serve over plain HTTP, use `Lax` (recommended) or `Strict` or the cookie will be rejected. `Default` uses the Go runtime’s `SameSiteDefaultMode`. `None` will be downgraded to `Lax` automatically if cookie is set NOT to be secure. |
|
||||
| `DIFFICULTY` | `4` | The difficulty of the challenge, or the number of leading zeroes that must be in successful responses. |
|
||||
| `DIFFICULTY_IN_JWT` | `false` | If set to `true`, adds the `difficulty` field into JWT claims, which indicates the difficulty the token has been generated. This may be useful for statistics and debugging. |
|
||||
| `ED25519_PRIVATE_KEY_HEX` | unset | The hex-encoded ed25519 private key used to sign Anubis responses. If this is not set, Anubis will generate one for you. This should be exactly 64 characters long. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. See below for details. |
|
||||
| `ED25519_PRIVATE_KEY_HEX_FILE` | unset | Path to a file containing the hex-encoded ed25519 private key. Only one of this or its sister option may be set. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. |
|
||||
| `ERROR_TITLE` | unset | <EO /> If set, override the translation stack to show a custom title for error pages such as "Something went wrong!". See [Customizing messages](./botstopper.mdx#customizing-messages) for more details. |
|
||||
| `JWT_RESTRICTION_HEADER` | `X-Real-IP` | If set, the JWT is only valid if the current value of this header matches the value when the JWT was created. You can use it e.g. to restrict a JWT to the source IP of the user using `X-Real-IP`. |
|
||||
| `METRICS_BIND` | `:9090` | The network address that Anubis serves Prometheus metrics on. See `BIND` for more information. |
|
||||
| `METRICS_BIND_NETWORK` | `tcp` | The address family that the Anubis metrics server listens on. See `BIND_NETWORK` for more information. |
|
||||
| `OG_EXPIRY_TIME` | `24h` | The expiration time for the Open Graph tag cache. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
|
||||
| `OG_PASSTHROUGH` | `false` | If set to `true`, Anubis will enable Open Graph tag passthrough. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
|
||||
| `OG_CACHE_CONSIDER_HOST` | `false` | If set to `true`, Anubis will consider the host in the Open Graph tag cache key. Prefer using [the policy file](./configuration/open-graph.mdx) to configure the Open Graph subsystem. |
|
||||
| `OVERLAY_FOLDER` | unset | <EO /> If set, treat the given path as an [overlay folder](./botstopper.mdx#custom-images-and-css), allowing you to customize CSS, fonts, images, and add other assets to BotStopper deployments. |
|
||||
| `POLICY_FNAME` | unset | The file containing [bot policy configuration](./policies.mdx). See the bot policy documentation for more details. If unset, the default bot policy configuration is used. |
|
||||
| `PUBLIC_URL` | unset | The externally accessible URL for this Anubis instance, used for constructing redirect URLs (e.g., for Traefik forwardAuth). |
|
||||
| `REDIRECT_DOMAINS` | unset | If set, restrict the domains that Anubis can redirect to when passing a challenge.<br/><br/>If this is unset, Anubis may redirect to any domain which could cause security issues in the unlikely case that an attacker passes a challenge for your browser and then tricks you into clicking a link to your domain.<br/><br/>Note that if you are hosting Anubis on a non-standard port (`https://example:com:8443`, `http://www.example.net:8080`, etc.), you must also include the port number here. |
|
||||
| `SERVE_ROBOTS_TXT` | `false` | If set `true`, Anubis will serve a default `robots.txt` file that disallows all known AI scrapers by name and then additionally disallows every scraper. This is useful if facts and circumstances make it difficult to change the underlying service to serve such a `robots.txt` file. |
|
||||
| `SLOG_LEVEL` | `INFO` | The log level for structured logging. Valid values are `DEBUG`, `INFO`, `WARN`, and `ERROR`. Set to `DEBUG` to see all requests, evaluations, and detailed diagnostic information. |
|
||||
| `SOCKET_MODE` | `0770` | _Only used when at least one of the `*_BIND_NETWORK` variables are set to `unix`._ The socket mode (permissions) for Unix domain sockets. |
|
||||
| `STRIP_BASE_PREFIX` | `false` | If set to `true`, strips the base prefix from request paths when forwarding to the target server. This is useful when your target service expects to receive requests without the base prefix. For example, with `BASE_PREFIX=/foo` and `STRIP_BASE_PREFIX=true`, a request to `/foo/bar` would be forwarded to the target as `/bar`. |
|
||||
| `TARGET` | `http://localhost:3923` | The URL of the service that Anubis should forward valid requests to. Supports Unix domain sockets, set this to a URI like so: `unix:///path/to/socket.sock`. |
|
||||
| `USE_REMOTE_ADDRESS` | unset | If set to `true`, Anubis will take the client's IP from the network socket. For production deployments, it is expected that a reverse proxy is used in front of Anubis, which pass the IP using headers, instead. |
|
||||
| `USE_SIMPLIFIED_EXPLANATION` | false | If set to `true`, replaces the text when clicking "Why am I seeing this?" with a more simplified text for a non-tech-savvy audience. |
|
||||
| `USE_TEMPLATES` | false | <EO /> If set to `true`, enable [custom HTML template support](./botstopper.mdx#custom-html-templates), allowing you to completely rewrite how BotStopper renders its HTML pages. |
|
||||
| `WEBMASTER_EMAIL` | unset | If set, shows a contact email address when rendering error pages. This email address will be how users can get in contact with administrators. |
|
||||
| `XFF_STRIP_PRIVATE` | `true` | If set, strip private addresses from `X-Forwarded-For` headers. To unset this, you must set `XFF_STRIP_PRIVATE=false` or `--xff-strip-private=false`. |
|
||||
|
||||
<details>
|
||||
<summary>Advanced configuration settings</summary>
|
||||
@@ -100,14 +116,14 @@ If you don't know or understand what these settings mean, ignore them. These are
|
||||
|
||||
:::
|
||||
|
||||
| Environment Variable | Default value | Explanation |
|
||||
| :---------------------------- | :------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `FORCED_LANGUAGE` | unset | If set, forces Anubis to display challenge pages in the specified language instead of using the browser's Accept-Language header. Use ISO 639-1 language codes (e.g., `de` for German, `fr` for French). |
|
||||
| `HS512_SECRET` | unset | Secret string for JWT HS512 algorithm. If this is not set, Anubis will use ED25519 as defined via the variables above. The longer the better; 128 chars should suffice. |
|
||||
| `TARGET_DISABLE_KEEPALIVE` | `false` | If `true`, disables HTTP keep-alive for connections to the target backend. Useful for backends that don't handle keep-alive properly. |
|
||||
| `TARGET_HOST` | unset | If set, overrides the Host header in requests forwarded to `TARGET`. |
|
||||
| `TARGET_INSECURE_SKIP_VERIFY` | `false` | If `true`, skip TLS certificate validation for targets that listen over `https`. If your backend does not listen over `https`, ignore this setting. |
|
||||
| `TARGET_SNI` | unset | If set, overrides the TLS handshake hostname in requests forwarded to `TARGET`. |
|
||||
| Environment Variable | Default value | Explanation |
|
||||
| :---------------------------- | :------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `FORCED_LANGUAGE` | unset | If set, forces Anubis to display challenge pages in the specified language instead of using the browser's Accept-Language header. Use ISO 639-1 language codes (e.g., `de` for German, `fr` for French). |
|
||||
| `HS512_SECRET` | unset | Secret string for JWT HS512 algorithm. If this is not set, Anubis will use ED25519 as defined via the variables above. The longer the better; 128 chars should suffice. **Required when using persistent storage backends** (like bbolt) to ensure challenges survive service restarts. When running multiple instances on the same base domain, the key must be the same across all instances. |
|
||||
| `TARGET_DISABLE_KEEPALIVE` | `false` | If `true`, disables HTTP keep-alive for connections to the target backend. Useful for backends that don't handle keep-alive properly. |
|
||||
| `TARGET_HOST` | unset | If set, overrides the Host header in requests forwarded to `TARGET`. |
|
||||
| `TARGET_INSECURE_SKIP_VERIFY` | `false` | If `true`, skip TLS certificate validation for targets that listen over `https`. If your backend does not listen over `https`, ignore this setting. |
|
||||
| `TARGET_SNI` | unset | If set, TLS handshake hostname when forwarding requests to the `TARGET`. If set to auto, use Host header. |
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ This page contains a non-exhaustive list with all websites using Anubis.
|
||||
- https://wiki.freepascal.org/
|
||||
- https://azurlane.koumakan.jp/
|
||||
- https://lab.civicrm.org/
|
||||
- https://git.door43.org/
|
||||
- <details>
|
||||
<summary>FreeCAD</summary>
|
||||
- https://forum.freecad.org/
|
||||
|
||||
677
docs/package-lock.json
generated
677
docs/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -25,7 +25,7 @@
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "^3.8.1",
|
||||
"@docusaurus/module-type-aliases": "^3.0.1",
|
||||
"@docusaurus/tsconfig": "^3.8.1",
|
||||
"@docusaurus/types": "^3.8.1",
|
||||
"typescript": "~5.6.2"
|
||||
@@ -45,4 +45,4 @@
|
||||
"engines": {
|
||||
"node": ">=18.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11
docs/src/components/EnterpriseOnly/index.jsx
Normal file
11
docs/src/components/EnterpriseOnly/index.jsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import styles from './styles.module.css';
|
||||
|
||||
export default function EnterpriseOnly({ link }) {
|
||||
return (
|
||||
<a className={styles.link} href={link}>
|
||||
<div className={styles.container}>
|
||||
<span className={styles.label}>BotStopper Only</span>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
18
docs/src/components/EnterpriseOnly/styles.module.css
Normal file
18
docs/src/components/EnterpriseOnly/styles.module.css
Normal file
@@ -0,0 +1,18 @@
|
||||
.link {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.container {
|
||||
background-color: #16a34a; /* green-500 */
|
||||
color: #ffffff;
|
||||
font-weight: 700;
|
||||
padding: 0.5rem 1rem; /* py-2 px-4 */
|
||||
border-radius: 9999px; /* rounded-full */
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); /* shadow-lg approximation */
|
||||
display: inline-flex; /* flex */
|
||||
align-items: center; /* items-center */
|
||||
}
|
||||
|
||||
.label {
|
||||
line-height: 1;
|
||||
}
|
||||
107
internal/actorify/actorify.go
Normal file
107
internal/actorify/actorify.go
Normal file
@@ -0,0 +1,107 @@
|
||||
// Package actorify lets you transform a parallel operation into a serialized
|
||||
// operation via the Actor pattern[1].
|
||||
//
|
||||
// [1]: https://en.wikipedia.org/wiki/Actor_model
|
||||
package actorify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
func z[Z any]() Z {
|
||||
var z Z
|
||||
return z
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrActorDied is returned when the actor inbox or reply channel was closed.
|
||||
ErrActorDied = errors.New("actorify: the actor inbox or reply channel was closed")
|
||||
)
|
||||
|
||||
// Handler is a function alias for the underlying logic the Actor should call.
|
||||
type Handler[Input, Output any] func(ctx context.Context, input Input) (Output, error)
|
||||
|
||||
// Actor is a serializing wrapper that runs a function in a background goroutine.
|
||||
// Whenever the Call method is invoked, a message is sent to the actor's inbox and then
|
||||
// the callee waits for a response. Depending on how busy the actor is, this may take
|
||||
// a moment.
|
||||
type Actor[Input, Output any] struct {
|
||||
handler Handler[Input, Output]
|
||||
inbox chan *message[Input, Output]
|
||||
}
|
||||
|
||||
type message[Input, Output any] struct {
|
||||
ctx context.Context
|
||||
arg Input
|
||||
reply chan reply[Output]
|
||||
}
|
||||
|
||||
type reply[Output any] struct {
|
||||
output Output
|
||||
err error
|
||||
}
|
||||
|
||||
// New constructs a new Actor and starts its background thread. Cancel the context and you cancel
|
||||
// the Actor.
|
||||
func New[Input, Output any](ctx context.Context, handler Handler[Input, Output]) *Actor[Input, Output] {
|
||||
result := &Actor[Input, Output]{
|
||||
handler: handler,
|
||||
inbox: make(chan *message[Input, Output], 32),
|
||||
}
|
||||
|
||||
go result.handle(ctx)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (a *Actor[Input, Output]) handle(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
close(a.inbox)
|
||||
return
|
||||
case msg, ok := <-a.inbox:
|
||||
if !ok {
|
||||
if msg.reply != nil {
|
||||
close(msg.reply)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
result, err := a.handler(msg.ctx, msg.arg)
|
||||
|
||||
reply := reply[Output]{
|
||||
output: result,
|
||||
err: err,
|
||||
}
|
||||
|
||||
msg.reply <- reply
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call calls the Actor with a given Input and returns the handler's Output.
|
||||
//
|
||||
// This only works with unary functions by design. If you need to have more inputs, define
|
||||
// a struct type to use as a container.
|
||||
func (a *Actor[Input, Output]) Call(ctx context.Context, input Input) (Output, error) {
|
||||
replyCh := make(chan reply[Output])
|
||||
|
||||
a.inbox <- &message[Input, Output]{
|
||||
arg: input,
|
||||
reply: replyCh,
|
||||
}
|
||||
|
||||
select {
|
||||
case reply, ok := <-replyCh:
|
||||
if !ok {
|
||||
return z[Output](), ErrActorDied
|
||||
}
|
||||
|
||||
return reply.output, reply.err
|
||||
case <-ctx.Done():
|
||||
return z[Output](), context.Cause(ctx)
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,22 @@ func UnchangingCache(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// CustomXRealIPHeader sets the X-Real-IP header to the value of a
|
||||
// different header.
|
||||
// Used in environments where the upstream proxy sets the request's
|
||||
// origin IP in a custom header.
|
||||
func CustomRealIPHeader(customRealIPHeaderValue string, next http.Handler) http.Handler {
|
||||
if customRealIPHeaderValue == "" {
|
||||
slog.Debug("skipping middleware, customRealIPHeaderValue is empty")
|
||||
return next
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Header.Set("X-Real-IP", r.Header.Get(customRealIPHeaderValue))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if
|
||||
// the setting is enabled by the user.
|
||||
func RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {
|
||||
|
||||
@@ -501,6 +501,12 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
|
||||
var tokenString string
|
||||
|
||||
// check if JWTRestrictionHeader is set and header is in request
|
||||
claims := jwt.MapClaims{
|
||||
"challenge": chall.ID,
|
||||
"method": rule.Challenge.Algorithm,
|
||||
"policyRule": rule.Hash(),
|
||||
"action": string(cr.Rule),
|
||||
}
|
||||
if s.opts.JWTRestrictionHeader != "" {
|
||||
if r.Header.Get(s.opts.JWTRestrictionHeader) == "" {
|
||||
lg.Error("JWTRestrictionHeader is set in config but not found in request, please check your reverse proxy config.")
|
||||
@@ -508,22 +514,13 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
|
||||
s.respondWithError(w, r, "failed to sign JWT")
|
||||
return
|
||||
} else {
|
||||
tokenString, err = s.signJWT(jwt.MapClaims{
|
||||
"challenge": chall.ID,
|
||||
"method": rule.Challenge.Algorithm,
|
||||
"policyRule": rule.Hash(),
|
||||
"action": string(cr.Rule),
|
||||
"restriction": internal.SHA256sum(r.Header.Get(s.opts.JWTRestrictionHeader)),
|
||||
})
|
||||
claims["restriction"] = internal.SHA256sum(r.Header.Get(s.opts.JWTRestrictionHeader))
|
||||
}
|
||||
} else {
|
||||
tokenString, err = s.signJWT(jwt.MapClaims{
|
||||
"challenge": chall.ID,
|
||||
"method": rule.Challenge.Algorithm,
|
||||
"policyRule": rule.Hash(),
|
||||
"action": string(cr.Rule),
|
||||
})
|
||||
}
|
||||
if s.opts.DifficultyInJWT {
|
||||
claims["difficulty"] = rule.Challenge.Difficulty
|
||||
}
|
||||
tokenString, err = s.signJWT(claims)
|
||||
|
||||
if err != nil {
|
||||
lg.Error("failed to sign JWT", "err", err)
|
||||
|
||||
@@ -299,6 +299,7 @@ func TestCookieSettings(t *testing.T) {
|
||||
CookieDomain: "127.0.0.1",
|
||||
CookiePartitioned: true,
|
||||
CookieSecure: true,
|
||||
CookieSameSite: http.SameSiteNoneMode,
|
||||
CookieExpiration: anubis.CookieDefaultExpirationTime,
|
||||
})
|
||||
|
||||
@@ -339,6 +340,65 @@ func TestCookieSettings(t *testing.T) {
|
||||
if ckie.Secure != srv.opts.CookieSecure {
|
||||
t.Errorf("wanted secure flag %v, got: %v", srv.opts.CookieSecure, ckie.Secure)
|
||||
}
|
||||
if ckie.SameSite != srv.opts.CookieSameSite {
|
||||
t.Errorf("wanted same site option %v, got: %v", srv.opts.CookieSameSite, ckie.SameSite)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieSettingsSameSiteNoneModeDowngradedToLaxWhenUnsecure(t *testing.T) {
|
||||
pol := loadPolicies(t, "testdata/zero_difficulty.yaml", 0)
|
||||
|
||||
srv := spawnAnubis(t, Options{
|
||||
Next: http.NewServeMux(),
|
||||
Policy: pol,
|
||||
|
||||
CookieDomain: "127.0.0.1",
|
||||
CookiePartitioned: true,
|
||||
CookieSecure: false,
|
||||
CookieSameSite: http.SameSiteNoneMode,
|
||||
CookieExpiration: anubis.CookieDefaultExpirationTime,
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(internal.RemoteXRealIP(true, "tcp", srv))
|
||||
defer ts.Close()
|
||||
|
||||
cli := httpClient(t)
|
||||
chall := makeChallenge(t, ts, cli)
|
||||
|
||||
resp := handleChallengeZeroDifficulty(t, ts, cli, chall)
|
||||
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
resp.Write(os.Stderr)
|
||||
t.Errorf("wanted %d, got: %d", http.StatusFound, resp.StatusCode)
|
||||
}
|
||||
|
||||
var ckie *http.Cookie
|
||||
for _, cookie := range resp.Cookies() {
|
||||
t.Logf("%#v", cookie)
|
||||
if cookie.Name == anubis.CookieName {
|
||||
ckie = cookie
|
||||
break
|
||||
}
|
||||
}
|
||||
if ckie == nil {
|
||||
t.Errorf("Cookie %q not found", anubis.CookieName)
|
||||
return
|
||||
}
|
||||
|
||||
if ckie.Domain != "127.0.0.1" {
|
||||
t.Errorf("cookie domain is wrong, wanted 127.0.0.1, got: %s", ckie.Domain)
|
||||
}
|
||||
|
||||
if ckie.Partitioned != srv.opts.CookiePartitioned {
|
||||
t.Errorf("wanted partitioned flag %v, got: %v", srv.opts.CookiePartitioned, ckie.Partitioned)
|
||||
}
|
||||
|
||||
if ckie.Secure != srv.opts.CookieSecure {
|
||||
t.Errorf("wanted secure flag %v, got: %v", srv.opts.CookieSecure, ckie.Secure)
|
||||
}
|
||||
if ckie.SameSite != http.SameSiteLaxMode {
|
||||
t.Errorf("wanted same site Lax option %v, got: %v", http.SameSiteLaxMode, ckie.SameSite)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDefaultDifficultyMatchesPolicy(t *testing.T) {
|
||||
@@ -397,7 +457,7 @@ func TestBasePrefix(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
name: "no prefix",
|
||||
basePrefix: "/",
|
||||
basePrefix: "",
|
||||
path: "/.within.website/x/cmd/anubis/api/make-challenge",
|
||||
expected: "/.within.website/x/cmd/anubis/api/make-challenge",
|
||||
},
|
||||
@@ -439,9 +499,15 @@ func TestBasePrefix(t *testing.T) {
|
||||
}
|
||||
|
||||
q := req.URL.Query()
|
||||
q.Set("redir", tc.basePrefix)
|
||||
redir := tc.basePrefix
|
||||
if tc.basePrefix == "" {
|
||||
redir = "/"
|
||||
}
|
||||
q.Set("redir", redir)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
|
||||
t.Log(req.URL.String())
|
||||
|
||||
// Test API endpoint with prefix
|
||||
resp, err := cli.Do(req)
|
||||
if err != nil {
|
||||
@@ -453,8 +519,15 @@ func TestBasePrefix(t *testing.T) {
|
||||
t.Errorf("expected status code %d, got: %d", http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("can't read body: %v", err)
|
||||
}
|
||||
|
||||
t.Log(string(data))
|
||||
|
||||
var chall challengeResp
|
||||
if err := json.NewDecoder(resp.Body).Decode(&chall); err != nil {
|
||||
if err := json.NewDecoder(bytes.NewBuffer(data)).Decode(&chall); err != nil {
|
||||
t.Fatalf("can't read challenge response body: %v", err)
|
||||
}
|
||||
|
||||
@@ -475,7 +548,7 @@ func TestBasePrefix(t *testing.T) {
|
||||
nonce++
|
||||
}
|
||||
elapsedTime := 420
|
||||
redir := "/"
|
||||
redir = "/"
|
||||
|
||||
cli.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
|
||||
@@ -61,7 +61,7 @@ type Impl interface {
|
||||
Setup(mux *http.ServeMux)
|
||||
|
||||
// Issue a new challenge to the user, called by the Anubis.
|
||||
Issue(r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)
|
||||
Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)
|
||||
|
||||
// Validate a challenge, making sure that it passes muster.
|
||||
Validate(r *http.Request, lg *slog.Logger, in *ValidateInput) error
|
||||
|
||||
@@ -23,7 +23,7 @@ type Impl struct{}
|
||||
|
||||
func (i *Impl) Setup(mux *http.ServeMux) {}
|
||||
|
||||
func (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {
|
||||
func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {
|
||||
u, err := r.URL.Parse(anubis.BasePrefix + "/.within.website/x/cmd/anubis/api/pass-challenge")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't render page: %w", err)
|
||||
@@ -35,9 +35,15 @@ func (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput)
|
||||
q.Set("id", in.Challenge.ID)
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
showMeta := in.Challenge.RandomData[0]%2 == 0
|
||||
|
||||
if !showMeta {
|
||||
w.Header().Add("Refresh", fmt.Sprintf("%d; url=%s", in.Rule.Challenge.Difficulty+1, u.String()))
|
||||
}
|
||||
|
||||
loc := localization.GetLocalizer(r)
|
||||
|
||||
result := page(u.String(), in.Rule.Challenge.Difficulty, loc)
|
||||
result := page(u.String(), in.Rule.Challenge.Difficulty, showMeta, loc)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -7,12 +7,14 @@ import (
|
||||
"github.com/TecharoHQ/anubis/lib/localization"
|
||||
)
|
||||
|
||||
templ page(redir string, difficulty int, loc *localization.SimpleLocalizer) {
|
||||
templ page(redir string, difficulty int, showMeta bool, loc *localization.SimpleLocalizer) {
|
||||
<div class="centered-div">
|
||||
<img id="image" style="width:100%;max-width:256px;" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=" + anubis.Version }/>
|
||||
<img style="display:none;" style="width:100%;max-width:256px;" src={ anubis.BasePrefix + "/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=" + anubis.Version }/>
|
||||
<p id="status">{ loc.T("loading") }</p>
|
||||
<p>{ loc.T("connection_security") }</p>
|
||||
<meta http-equiv="refresh" content={ fmt.Sprintf("%d; url=%s", difficulty+1, redir) }/>
|
||||
if showMeta {
|
||||
<meta http-equiv="refresh" content={ fmt.Sprintf("%d; url=%s", difficulty+1, redir) }/>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
32
lib/challenge/metarefresh/metarefresh_templ.go
generated
32
lib/challenge/metarefresh/metarefresh_templ.go
generated
@@ -15,7 +15,7 @@ import (
|
||||
"github.com/TecharoHQ/anubis/lib/localization"
|
||||
)
|
||||
|
||||
func page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ.Component {
|
||||
func page(redir string, difficulty int, showMeta bool, loc *localization.SimpleLocalizer) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
@@ -88,20 +88,30 @@ func page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</p><meta http-equiv=\"refresh\" content=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d; url=%s", difficulty, redir))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 16, Col: 83}
|
||||
if showMeta {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<meta http-equiv=\"refresh\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d; url=%s", difficulty+1, redir))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 17, Col: 86}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\"></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -40,9 +40,9 @@ for the JavaScript code in this page.
|
||||
|
||||
mkdir -p static/js
|
||||
|
||||
for file in js/*.jsx; do
|
||||
for file in js/*.tsx; do
|
||||
filename="${file##*/}" # Extracts "app.jsx" from "./js/app.jsx"
|
||||
output="${filename%.jsx}.js" # Changes "app.jsx" to "app.js"
|
||||
output="${filename%.tsx}.js" # Changes "app.jsx" to "app.js"
|
||||
echo $output
|
||||
|
||||
esbuild "${file}" --minify --bundle --outfile=static/"${output}" --banner:js="${LICENSE}"
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { render, h, Fragment } from 'preact';
|
||||
import { useState, useEffect } from 'preact/hooks';
|
||||
import { g, j, u, x } from "./xeact.js";
|
||||
import { Sha256 } from '@aws-crypto/sha256-js';
|
||||
|
||||
/** @jsx h */
|
||||
/** @jsxFrag Fragment */
|
||||
|
||||
function toHexString(arr) {
|
||||
return Array.from(arr)
|
||||
.map((c) => c.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
const App = () => {
|
||||
const [state, setState] = useState(null);
|
||||
const [imageURL, setImageURL] = useState(null);
|
||||
const [passed, setPassed] = useState(false);
|
||||
const [challenge, setChallenge] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
setState(j("preact_info"));
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setImageURL(state.pensive_url);
|
||||
const hash = new Sha256('');
|
||||
hash.update(state.challenge);
|
||||
setChallenge(toHexString(hash.digestSync()));
|
||||
}, [state]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setPassed(true);
|
||||
}, state.difficulty * 125);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [challenge]);
|
||||
|
||||
useEffect(() => {
|
||||
window.location.href = u(state.redir, {
|
||||
result: challenge,
|
||||
});
|
||||
}, [passed]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{imageURL !== null && (
|
||||
<img src={imageURL} style="width:100%;max-width:256px;" />
|
||||
)}
|
||||
{state !== null && (
|
||||
<>
|
||||
<p id="status">{state.loading_message}</p>
|
||||
<p>{state.connection_security_message}</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
x(g("app"));
|
||||
render(<App />, g("app"));
|
||||
87
lib/challenge/preact/js/app.tsx
Normal file
87
lib/challenge/preact/js/app.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import { render, h, Fragment } from "preact";
|
||||
import { useState, useEffect } from "preact/hooks";
|
||||
import { g, j, r, u, x } from "./xeact.js";
|
||||
import { Sha256 } from "@aws-crypto/sha256-js";
|
||||
|
||||
/** @jsx h */
|
||||
/** @jsxFrag Fragment */
|
||||
|
||||
function toHexString(arr: Uint8Array) {
|
||||
return Array.from(arr)
|
||||
.map((c) => c.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
interface PreactInfo {
|
||||
redir: string;
|
||||
challenge: string;
|
||||
difficulty: number;
|
||||
connection_security_message: string;
|
||||
loading_message: string;
|
||||
pensive_url: string;
|
||||
}
|
||||
|
||||
const App = () => {
|
||||
const [state, setState] = useState<PreactInfo>();
|
||||
const [imageURL, setImageURL] = useState<string | null>(null);
|
||||
const [passed, setPassed] = useState<boolean>(false);
|
||||
const [challenge, setChallenge] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setState(j("preact_info"));
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (state === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
setImageURL(state?.pensive_url);
|
||||
const hash = new Sha256("");
|
||||
hash.update(state.challenge);
|
||||
setChallenge(toHexString(hash.digestSync()));
|
||||
}, [state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
setPassed(true);
|
||||
}, state?.difficulty * 125);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [challenge]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (challenge === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.href = u(state.redir, {
|
||||
result: challenge,
|
||||
});
|
||||
}, [passed]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{imageURL !== null && (
|
||||
<img src={imageURL} style={{ width: "100%", maxWidth: "256px" }} />
|
||||
)}
|
||||
{state !== undefined && (
|
||||
<>
|
||||
<p id="status">{state.loading_message}</p>
|
||||
<p>{state.connection_security_message}</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
x(g("app"));
|
||||
render(<App />, g("app"));
|
||||
@@ -38,7 +38,7 @@ type impl struct{}
|
||||
|
||||
func (i *impl) Setup(mux *http.ServeMux) {}
|
||||
|
||||
func (i *impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {
|
||||
func (i *impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {
|
||||
u, err := r.URL.Parse(anubis.BasePrefix + "/.within.website/x/cmd/anubis/api/pass-challenge")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't render page: %w", err)
|
||||
|
||||
@@ -27,7 +27,7 @@ type Impl struct {
|
||||
|
||||
func (i *Impl) Setup(mux *http.ServeMux) {}
|
||||
|
||||
func (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {
|
||||
func (i *Impl) Issue(w http.ResponseWriter, r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {
|
||||
loc := localization.GetLocalizer(r)
|
||||
return page(loc), nil
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/TecharoHQ/anubis/lib/challenge"
|
||||
@@ -133,7 +134,7 @@ func TestBasic(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := i.Issue(cs.req, lg, inp); err != nil {
|
||||
if _, err := i.Issue(httptest.NewRecorder(), cs.req, lg, inp); err != nil {
|
||||
t.Errorf("can't issue challenge: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -43,9 +43,11 @@ type Options struct {
|
||||
OpenGraph config.OpenGraph
|
||||
ServeRobotsTXT bool
|
||||
CookieSecure bool
|
||||
CookieSameSite http.SameSite
|
||||
Logger *slog.Logger
|
||||
PublicUrl string
|
||||
JWTRestrictionHeader string
|
||||
DifficultyInJWT bool
|
||||
}
|
||||
|
||||
func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {
|
||||
@@ -105,7 +107,7 @@ func New(opts Options) (*Server, error) {
|
||||
opts.ED25519PrivateKey = priv
|
||||
}
|
||||
|
||||
anubis.BasePrefix = opts.BasePrefix
|
||||
anubis.BasePrefix = strings.TrimRight(opts.BasePrefix, "/")
|
||||
anubis.PublicUrl = opts.PublicUrl
|
||||
|
||||
result := &Server{
|
||||
|
||||
50
lib/http.go
50
lib/http.go
@@ -29,19 +29,19 @@ var domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[
|
||||
// internal glob matcher. Matching is case-insensitive on hostnames.
|
||||
func matchRedirectDomain(allowed []string, host string) bool {
|
||||
h := strings.ToLower(strings.TrimSpace(host))
|
||||
for _, pat := range allowed {
|
||||
p := strings.ToLower(strings.TrimSpace(pat))
|
||||
if strings.Contains(p, glob.GLOB) {
|
||||
if glob.Glob(p, h) {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if p == h {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
for _, pat := range allowed {
|
||||
p := strings.ToLower(strings.TrimSpace(pat))
|
||||
if strings.Contains(p, glob.GLOB) {
|
||||
if glob.Glob(p, h) {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if p == h {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type CookieOpts struct {
|
||||
@@ -56,6 +56,8 @@ func (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {
|
||||
var domain = s.opts.CookieDomain
|
||||
var name = anubis.CookieName
|
||||
var path = "/"
|
||||
var sameSite = s.opts.CookieSameSite
|
||||
|
||||
if cookieOpts.Name != "" {
|
||||
name = cookieOpts.Name
|
||||
}
|
||||
@@ -72,11 +74,15 @@ func (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {
|
||||
cookieOpts.Expiry = s.opts.CookieExpiration
|
||||
}
|
||||
|
||||
if s.opts.CookieSameSite == http.SameSiteNoneMode && !s.opts.CookieSecure {
|
||||
sameSite = http.SameSiteLaxMode
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: cookieOpts.Value,
|
||||
Expires: time.Now().Add(cookieOpts.Expiry),
|
||||
SameSite: http.SameSiteNoneMode,
|
||||
SameSite: sameSite,
|
||||
Domain: domain,
|
||||
Secure: s.opts.CookieSecure,
|
||||
Partitioned: s.opts.CookiePartitioned,
|
||||
@@ -88,6 +94,8 @@ func (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {
|
||||
var domain = s.opts.CookieDomain
|
||||
var name = anubis.CookieName
|
||||
var path = "/"
|
||||
var sameSite = s.opts.CookieSameSite
|
||||
|
||||
if cookieOpts.Name != "" {
|
||||
name = cookieOpts.Name
|
||||
}
|
||||
@@ -99,13 +107,16 @@ func (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {
|
||||
domain = etld
|
||||
}
|
||||
}
|
||||
if s.opts.CookieSameSite == http.SameSiteNoneMode && !s.opts.CookieSecure {
|
||||
sameSite = http.SameSiteLaxMode
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: "",
|
||||
MaxAge: -1,
|
||||
Expires: time.Now().Add(-1 * time.Minute),
|
||||
SameSite: http.SameSiteNoneMode,
|
||||
SameSite: sameSite,
|
||||
Partitioned: s.opts.CookiePartitioned,
|
||||
Domain: domain,
|
||||
Secure: s.opts.CookieSecure,
|
||||
@@ -203,7 +214,7 @@ func (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, cr policy.C
|
||||
Store: s.store,
|
||||
}
|
||||
|
||||
component, err := impl.Issue(r, lg, in)
|
||||
component, err := impl.Issue(w, r, lg, in)
|
||||
if err != nil {
|
||||
lg.Error("[unexpected] challenge component render failed, please open an issue", "err", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.
|
||||
s.respondWithError(w, r, fmt.Sprintf("%s \"RenderIndex\"", localizer.T("internal_server_error")))
|
||||
@@ -268,7 +279,12 @@ func (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg s
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.mux.ServeHTTP(w, r)
|
||||
if strings.HasPrefix(r.URL.Path, anubis.BasePrefix+anubis.StaticPath) {
|
||||
s.mux.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
s.maybeReverseProxyOrPage(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {
|
||||
|
||||
@@ -62,5 +62,6 @@
|
||||
"js_iterations": "iteracijų",
|
||||
"js_finished_reading": "Viską perskaičiau, tęskime →",
|
||||
"js_calculation_error": "Skaičiavimo klaida!",
|
||||
"js_calculation_error_msg": "Nepavyko įveikti iššūkio:"
|
||||
"js_calculation_error_msg": "Nepavyko įveikti iššūkio:",
|
||||
"missing_required_forwarded_headers": "Trūksta privalomų X-Forwarded-* antraščių"
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"iters_b": "Iters B",
|
||||
"static_check_endpoint": "Dit is gewoon een controle-eindpunt voor uw reverse proxy om te gebruiken.",
|
||||
"authorization_required": "Autorisatie vereist",
|
||||
"cookies_disabled": "Uw browser is geconfigureerd om koekjes uit te schakelen. Anubis heeft koekjes nodig om er zeker van te zijn dat u een geldige klant bent. Schakel cookies in voor dit domein",
|
||||
"cookies_disabled": "Uw browser is geconfigureerd om cookies uit te schakelen. Anubis heeft cookies nodig om er zeker van te zijn dat u een geldige klant bent. Schakel cookies in voor dit domein",
|
||||
"access_denied": "Toegang geweigerd: foutcode",
|
||||
"dronebl_entry": "DroneBL meldde een item",
|
||||
"see_dronebl_lookup": "zie",
|
||||
@@ -45,7 +45,7 @@
|
||||
"celphase": "CELPHASE",
|
||||
"js_web_crypto_error": "Uw browser heeft geen werkend web.crypto-element. Bekijkt u dit via een beveiligde context?",
|
||||
"js_web_workers_error": "Je browser ondersteunt geen web-takers (Anubis gebruikt dit om te voorkomen dat je browser bevriest). Heb je een plugin zoals JShelter geïnstalleerd?",
|
||||
"js_cookies_error": "Uw browser slaat geen cookies op. Anubis gebruikt cookies om te bepalen welke klanten geslaagd zijn voor uitdagingen door een ondertekend token in een koekje op te slaan. Schakel het opslaan van koekjes voor dit domein in. De namen van de koekjes die Anubis opslaat, kunnen zonder voorafgaande kennisgeving variëren. Koekjesnamen en -waarden maken geen deel uit van de openbare API.",
|
||||
"js_cookies_error": "Uw browser slaat geen cookies op. Anubis gebruikt cookies om te bepalen welke klanten geslaagd zijn voor uitdagingen door een ondertekend token in een cookie op te slaan. Schakel het opslaan van cookies voor dit domein in. De namen van de cookies die Anubis opslaat, kunnen zonder voorafgaande kennisgeving variëren. cookiesnamen en -waarden maken geen deel uit van de openbare API.",
|
||||
"js_context_not_secure": "Je context is niet veilig!",
|
||||
"js_context_not_secure_msg": "Probeer verbinding te maken via HTTPS of laat de beheerder weten dat HTTPS moet worden ingesteld. Zie <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#when_is_a_context_considered_secure\">MDN</a> voor meer informatie.",
|
||||
"js_calculating": "Berekenen...",
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"try_again": "Prøv att",
|
||||
"go_home": "Gå heim",
|
||||
"contact_webmaster": "eller om du synest at du ikkje burde vera blokkert, venlegast tak kontakt med administratoren på",
|
||||
"connection_security": "Venlegast vent medan vi stadfestar tryggleiken av tilkoplinga di.",
|
||||
"connection_security": "Venlegast vent medan vi stadfester tryggleiken av tilkoplinga di.",
|
||||
"javascript_required": "Du lyt diverre slå på JavaScript for å koma deg forbi denne utfordringa. Dette krevst av di KI-selskap har endra sosialkontrakten om korleis nettstadsverting fungerer. Ei ikkje-JS-løysing er i gang med å skapast.",
|
||||
"benchmark_requires_js": "JavaScript må vera slegen på for å køyre samanlikningsverktøyet.",
|
||||
"difficulty": "Vanskenivå:",
|
||||
@@ -41,7 +41,7 @@
|
||||
"oh_noes": "Å nei!",
|
||||
"benchmarking_anubis": "Samanliknar Anubis!",
|
||||
"you_are_not_a_bot": "Du er ikkje ein bot!",
|
||||
"making_sure_not_bot": "Stadfestar at du ikkje er ein bot!",
|
||||
"making_sure_not_bot": "Stadfester at du ikkje er ein bot!",
|
||||
"celphase": "CELPHASE",
|
||||
"js_web_crypto_error": "Nettlesaren din har ikkje eit fungerande web.crypto-element. Ser du dette med ei sikker tilkopling?",
|
||||
"js_web_workers_error": "Nettlesaren din støttar ikkje nettarbeidarar (Anubis brukar dette for å unngå å fryse nettlesaren din). Har du eit tillegg som JShelter installert?",
|
||||
@@ -63,4 +63,4 @@
|
||||
"js_calculation_error_msg": "Mislukkast i å rekne utfordring:",
|
||||
"missing_required_forwarded_headers": "Manglende nødvendige X-Forwarded-* headers",
|
||||
"simplified_explanation": "Dette er eit tiltak mot robotar og vondsinna førespurnader som liknar på ein CAPTCHA. Men i staden for å måtte gjere arbeidet sjølv, får nettlesaren din ei utrekningsoppgåve som han må løyse for å sikre at han er ein gyldig klient. Dette konseptet blir kalla <a href=\"https://en.wikipedia.org/wiki/Proof_of_work\">Arbeidsbevis</a>. Oppgåva blir rekna ut på nokre få sekund, og du får tilgang til nettstaden. Takk for di forståing og tålmod."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,8 @@ func (cr *CELRequest) ResolveName(name string) (any, bool) {
|
||||
switch name {
|
||||
case "remoteAddress":
|
||||
return cr.Header.Get("X-Real-Ip"), true
|
||||
case "contentLength":
|
||||
return cr.ContentLength, true
|
||||
case "host":
|
||||
return cr.Host, true
|
||||
case "method":
|
||||
|
||||
@@ -19,6 +19,7 @@ func BotEnvironment() (*cel.Env, error) {
|
||||
return New(
|
||||
// Variables exposed to CEL programs:
|
||||
cel.Variable("remoteAddress", cel.StringType),
|
||||
cel.Variable("contentLength", cel.IntType),
|
||||
cel.Variable("host", cel.StringType),
|
||||
cel.Variable("method", cel.StringType),
|
||||
cel.Variable("userAgent", cel.StringType),
|
||||
|
||||
82
lib/store/actorifiedstore.go
Normal file
82
lib/store/actorifiedstore.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis/internal/actorify"
|
||||
)
|
||||
|
||||
type unit struct{}
|
||||
|
||||
type ActorifiedStore struct {
|
||||
Interface
|
||||
|
||||
deleteActor *actorify.Actor[string, unit]
|
||||
getActor *actorify.Actor[string, []byte]
|
||||
setActor *actorify.Actor[*actorSetReq, unit]
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type actorSetReq struct {
|
||||
key string
|
||||
value []byte
|
||||
expiry time.Duration
|
||||
}
|
||||
|
||||
func NewActorifiedStore(backend Interface) *ActorifiedStore {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
result := &ActorifiedStore{
|
||||
Interface: backend,
|
||||
cancel: cancel,
|
||||
}
|
||||
|
||||
result.deleteActor = actorify.New(ctx, result.actorDelete)
|
||||
result.getActor = actorify.New(ctx, backend.Get)
|
||||
result.setActor = actorify.New(ctx, result.actorSet)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (a *ActorifiedStore) Close() { a.cancel() }
|
||||
|
||||
func (a *ActorifiedStore) Delete(ctx context.Context, key string) error {
|
||||
if _, err := a.deleteActor.Call(ctx, key); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ActorifiedStore) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return a.getActor.Call(ctx, key)
|
||||
}
|
||||
|
||||
func (a *ActorifiedStore) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {
|
||||
if _, err := a.setActor.Call(ctx, &actorSetReq{
|
||||
key: key,
|
||||
value: value,
|
||||
expiry: expiry,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ActorifiedStore) actorDelete(ctx context.Context, key string) (unit, error) {
|
||||
if err := a.Interface.Delete(ctx, key); err != nil {
|
||||
return unit{}, err
|
||||
}
|
||||
|
||||
return unit{}, nil
|
||||
}
|
||||
|
||||
func (a *ActorifiedStore) actorSet(ctx context.Context, req *actorSetReq) (unit, error) {
|
||||
if err := a.Interface.Set(ctx, req.key, req.value, req.expiry); err != nil {
|
||||
return unit{}, err
|
||||
}
|
||||
|
||||
return unit{}, nil
|
||||
}
|
||||
@@ -11,10 +11,9 @@ import (
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
// Sentinel error values used for testing and in admin-visible error messages.
|
||||
// Sentinel error value used for testing and in admin-visible error messages.
|
||||
var (
|
||||
ErrBucketDoesNotExist = errors.New("bbolt: bucket does not exist")
|
||||
ErrNotExists = errors.New("bbolt: value does not exist in store")
|
||||
ErrNotExists = errors.New("bbolt: value does not exist in store")
|
||||
)
|
||||
|
||||
// Store implements store.Interface backed by bbolt[1].
|
||||
@@ -150,6 +149,10 @@ func (s *Store) cleanup(ctx context.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) IsPersistent() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Store) cleanupThread(ctx context.Context) {
|
||||
t := time.NewTicker(time.Hour)
|
||||
defer t.Stop()
|
||||
|
||||
@@ -48,7 +48,7 @@ func (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface
|
||||
|
||||
go result.cleanupThread(ctx)
|
||||
|
||||
return result, nil
|
||||
return store.NewActorifiedStore(result), nil
|
||||
}
|
||||
|
||||
// Valid parses and validates the bbolt store Config or returns
|
||||
|
||||
@@ -37,6 +37,11 @@ type Interface interface {
|
||||
|
||||
// Set puts a value into the store that expires according to its expiry.
|
||||
Set(ctx context.Context, key string, value []byte, expiry time.Duration) error
|
||||
|
||||
// IsPersistent returns true if this storage backend persists data across
|
||||
// service restarts (e.g., bbolt, valkey). Returns false for volatile storage
|
||||
// like in-memory backends.
|
||||
IsPersistent() bool
|
||||
}
|
||||
|
||||
func z[T any]() T { return *new(T) }
|
||||
@@ -88,3 +93,7 @@ func (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Dura
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *JSON[T]) IsPersistent() bool {
|
||||
return j.Underlying.IsPersistent()
|
||||
}
|
||||
|
||||
@@ -48,6 +48,10 @@ func (i *impl) Set(_ context.Context, key string, value []byte, expiry time.Dura
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *impl) IsPersistent() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *impl) cleanupThread(ctx context.Context) {
|
||||
t := time.NewTicker(5 * time.Minute)
|
||||
defer t.Stop()
|
||||
|
||||
@@ -47,3 +47,7 @@ func (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.D
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) IsPersistent() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
51
package-lock.json
generated
51
package-lock.json
generated
@@ -10,7 +10,7 @@
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"preact": "^10.27.1"
|
||||
"preact": "^10.27.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"cssnano": "^7.1.1",
|
||||
@@ -1223,9 +1223,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/fs-extra": {
|
||||
"version": "11.3.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz",
|
||||
"integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==",
|
||||
"version": "11.3.1",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz",
|
||||
"integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -1392,9 +1392,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsonfile": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
|
||||
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz",
|
||||
"integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -2328,9 +2328,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/preact": {
|
||||
"version": "10.27.1",
|
||||
"resolved": "https://registry.npmjs.org/preact/-/preact-10.27.1.tgz",
|
||||
"integrity": "sha512-V79raXEWch/rbqoNc7nT9E4ep7lu+mI3+sBmfRD4i1M73R3WLYcCtdI0ibxGVf4eQL8ZIz2nFacqEC+rmnOORQ==",
|
||||
"version": "10.27.2",
|
||||
"resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz",
|
||||
"integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
@@ -2560,14 +2560,14 @@
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
@@ -2577,11 +2577,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby/node_modules/fdir": {
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
|
||||
"integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"picomatch": "^3 || ^4"
|
||||
},
|
||||
@@ -2592,9 +2595,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby/node_modules/picomatch": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -2721,9 +2724,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/yaml": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz",
|
||||
"integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==",
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz",
|
||||
"integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
|
||||
@@ -29,6 +29,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"preact": "^10.27.1"
|
||||
"preact": "^10.27.2"
|
||||
}
|
||||
}
|
||||
@@ -30,5 +30,6 @@ start_pre() {
|
||||
return 1
|
||||
fi
|
||||
|
||||
checkpath -d -o "${command_user?}" "/run/anubis_${instance?}"
|
||||
rm -rf "/run/anubis_${instance?}"
|
||||
checkpath -D -o "${command_user?}" "/run/anubis_${instance?}"
|
||||
}
|
||||
|
||||
25
test/cmd/httpdebug/main.go
Normal file
25
test/cmd/httpdebug/main.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
bind = flag.String("bind", ":3923", "TCP port to bind to")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
slog.Info("listening", "url", "http://localhost"+*bind)
|
||||
log.Fatal(http.ListenAndServe(*bind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
slog.Info("got request", "method", r.Method, "path", r.RequestURI)
|
||||
|
||||
fmt.Fprintln(w, r.Method, r.RequestURI)
|
||||
r.Header.Write(w)
|
||||
})))
|
||||
}
|
||||
8
test/double_slash/anubis.yaml
Normal file
8
test/double_slash/anubis.yaml
Normal file
@@ -0,0 +1,8 @@
|
||||
bots:
|
||||
- name: challenge
|
||||
user_agent_regex: CHALLENGE
|
||||
action: CHALLENGE
|
||||
|
||||
status_codes:
|
||||
CHALLENGE: 200
|
||||
DENY: 403
|
||||
178
test/double_slash/input.txt
Normal file
178
test/double_slash/input.txt
Normal file
@@ -0,0 +1,178 @@
|
||||
/wiki//bin
|
||||
/wiki//boot
|
||||
/wiki//dev
|
||||
/wiki//dev/de
|
||||
/wiki//dev/en
|
||||
/wiki//dev/en-ca
|
||||
/wiki//dev/es
|
||||
/wiki//dev/fr
|
||||
/wiki//dev/hr
|
||||
/wiki//dev/hu
|
||||
/wiki//dev/it
|
||||
/wiki//dev/ja
|
||||
/wiki//dev/ko
|
||||
/wiki//dev/pl
|
||||
/wiki//dev/pt-br
|
||||
/wiki//dev/ro
|
||||
/wiki//dev/ru
|
||||
/wiki//dev/sv
|
||||
/wiki//dev/uk
|
||||
/wiki//dev/zh-cn
|
||||
/wiki//etc
|
||||
/wiki//etc/conf.d
|
||||
/wiki//etc/env.d
|
||||
/wiki//etc/fstab
|
||||
/wiki//etc/fstab/de
|
||||
/wiki//etc/fstab/en
|
||||
/wiki//etc/fstab/es
|
||||
/wiki//etc/fstab/fr
|
||||
/wiki//etc/fstab/hu
|
||||
/wiki//etc/fstab/it
|
||||
/wiki//etc/fstab/ja
|
||||
/wiki//etc/fstab/ko
|
||||
/wiki//etc/fstab/ru
|
||||
/wiki//etc/fstab/sv
|
||||
/wiki//etc/fstab/uk
|
||||
/wiki//etc/fstab/zh-cn
|
||||
/wiki//etc/hosts
|
||||
/wiki//etc/local.d
|
||||
/wiki//etc/make.conf
|
||||
/wiki//etc/portage
|
||||
/wiki//etc/portage/bashrc
|
||||
/wiki//etc/portage/Bashrc
|
||||
/wiki//etc/portage/binrepos.conf
|
||||
/wiki//etc/portage/binrepos.conf/en
|
||||
/wiki//etc/portage/binrepos.conf/hu
|
||||
/wiki//etc/portage/binrepos.conf/ja
|
||||
/wiki//etc/portage/binrepos.conf/ru
|
||||
/wiki//etc/portage/categories
|
||||
/wiki//etc/portage/color.map
|
||||
/wiki//etc/portage/env
|
||||
/wiki//etc/portage/img/ico.png
|
||||
/wiki//etc/portage/license_groups
|
||||
/wiki//etc/portage/make.conf
|
||||
/wiki//etc/portage/make.conf/de
|
||||
/wiki//etc/portage/make.conf/de/etc/portage/make.conf
|
||||
/wiki//etc/portage/make.conf/en
|
||||
/wiki//etc/portage/make.conf/es
|
||||
/wiki//etc/portage/make.conf/fr
|
||||
/wiki//etc/portage/make.conf/hu
|
||||
/wiki//etc/portage/make.conf/it
|
||||
/wiki//etc/portage/make.conf/it/var/db/repos/gentoo/licenses
|
||||
/wiki//etc/portage/make.conf/ja
|
||||
/wiki//etc/portage/make.conf/pl
|
||||
/wiki//etc/portage/make.conf/ru
|
||||
/wiki//etc/portage/make.conf/uk
|
||||
/wiki//etc/portage/make.conf/zh-cn
|
||||
/wiki//etc/portage/make.profile
|
||||
/wiki//etc/portage/mirrors
|
||||
/wiki//etc/portage/modules
|
||||
/wiki//etc/portage/package.accept_keywords
|
||||
/wiki//etc/portage/package.env
|
||||
/wiki//etc/portage/package.license
|
||||
/wiki//etc/portage/package.license/en
|
||||
/wiki//etc/portage/package.license/es
|
||||
/wiki//etc/portage/package.license/hu
|
||||
/wiki//etc/portage/package.license/ja
|
||||
/wiki//etc/portage/package.mask
|
||||
/wiki//etc/portage/package.mask/en
|
||||
/wiki//etc/portage/package.mask/hu
|
||||
/wiki//etc/portage/package.mask/ja
|
||||
/wiki//etc/portage/package.properties
|
||||
/wiki//etc/portage/package.unmask
|
||||
/wiki//etc/portage/package.use
|
||||
/wiki//etc/portage/package.use/de
|
||||
/wiki//etc/portage/package.use/en
|
||||
/wiki//etc/portage/package.use/es
|
||||
/wiki//etc/portage/package.use/fr
|
||||
/wiki//etc/portage/package.use/hu
|
||||
/wiki//etc/portage/package.use/it
|
||||
/wiki//etc/portage/package.use/ja
|
||||
/wiki//etc/portage/package.use/ru
|
||||
/wiki//etc/portage/package.use/uk
|
||||
/wiki//etc/portage/package.use/zh-cn
|
||||
/wiki//etc/portage/patches
|
||||
/wiki//etc/portage/profile/make.defaults
|
||||
/wiki//etc/portage/profile/package.provided
|
||||
/wiki//etc/portage/profile/package.provided/etc/portage/profile/package.provided
|
||||
/wiki//etc/portage/profile/package.provided/etc/portage/profiles/package.provided
|
||||
/wiki//etc/portage/profile/package.use.mask
|
||||
/wiki//etc/portage/profiles/package.provided
|
||||
/wiki//etc/portage/profiles/package.use.mask
|
||||
/wiki//etc/portage/profiles/package.use.mask/etc/portage/profile/package.use.mask
|
||||
/wiki//etc/portage/profiles/package.use.mask/etc/portage/profiles/package.use.mask
|
||||
/wiki//etc/portage/profiles/use.mask
|
||||
/wiki//etc/portage/profile/use.mask
|
||||
/wiki//etc/portage/repos.conf
|
||||
/wiki//etc/portage/repos.conf/brother-overlay.conf
|
||||
/wiki//etc/portage/repos.conf/de
|
||||
/wiki//etc/portage/repos.conf/en
|
||||
/wiki//etc/portage/repos.conf/es
|
||||
/wiki//etc/portage/repos.conf/etc/portage/repos.conf/gentoo.conf
|
||||
/wiki//etc/portage/repos.conf/fr
|
||||
/wiki//etc/portage/repos.conf/fr/etc/portage/repos.conf/gentoo.conf
|
||||
/wiki//etc/portage/repos.conf/gentoo.conf
|
||||
/wiki//etc/portage/repos.conf/gentoo.conf/etc/portage/repos.conf/gentoo.conf
|
||||
/wiki//etc/portage/repos.conf/hr
|
||||
/wiki//etc/portage/repos.conf/hu
|
||||
/wiki//etc/portage/repos.conf/it
|
||||
/wiki//etc/portage/repos.conf/ja
|
||||
/wiki//etc/portage/repos.conf/ko
|
||||
/wiki//etc/portage/repos.conf/pl
|
||||
/wiki//etc/portage/repos.conf/pt-br
|
||||
/wiki//etc/portage/repos.conf/ru
|
||||
/wiki//etc/portage/repos.conf/uk
|
||||
/wiki//etc/portage/repos.conf/zh-cn
|
||||
/wiki//etc/portage/savedconfig
|
||||
/wiki//etc/portage/sets
|
||||
/wiki//etc/profile
|
||||
/wiki//etc/profile.env
|
||||
/wiki//etc/sandbox.conf
|
||||
/wiki//home
|
||||
/wiki//lib
|
||||
/wiki//lib64
|
||||
/wiki//media
|
||||
/wiki//mnt
|
||||
/wiki//opt
|
||||
/wiki//proc
|
||||
/wiki//proc/config.gz
|
||||
/wiki//run
|
||||
/wiki//sbin
|
||||
/wiki//srv
|
||||
/wiki//sys
|
||||
/wiki//tmp
|
||||
/wiki//usr
|
||||
/wiki//usr/bin
|
||||
/wiki//usr_move
|
||||
/wiki//usr/portage
|
||||
/wiki//usr/portage/distfiles
|
||||
/wiki//usr/portage/licenses
|
||||
/wiki//usr/portage/metadata
|
||||
/wiki//usr/portage/metadata/md5-cache
|
||||
/wiki//usr/portage/metadata/md5-cache/usr/portage/metadata/md5-cache
|
||||
/wiki//usr/portage/metadata/md5-cache/var/db/repos/gentoo//metadata/md5-cache
|
||||
/wiki//usr/portage/packages
|
||||
/wiki//usr/portage/profiles
|
||||
/wiki//usr/portage/profiles/license_groups
|
||||
/wiki//usr/portage/profiles/license_groups/usr/portage/profiles/license_groups
|
||||
/wiki//usr/portage/profiles/license_groups/var/db/repos/gentoo//profiles/license_groups
|
||||
/wiki//usr/share/doc/
|
||||
/wiki//var/cache/binpkgs
|
||||
/wiki//var/cache/distfiles
|
||||
/wiki//var/db/pkg
|
||||
/wiki//var/db/pkg%22
|
||||
/wiki//var/db/repos/gentoo
|
||||
/wiki//var/db/repos/gentoo/licenses
|
||||
/wiki//var/db/repos/gentoo/licenses/var/db/repos/gentoo//licenses
|
||||
/wiki//var/db/repos/gentoo/licenses/var/db/repos/gentoo/licenses
|
||||
/wiki//var/db/repos/gentoo/metadata
|
||||
/wiki//var/db/repos/gentoo/metadata/md5-cache
|
||||
/wiki//var/db/repos/gentoo/metadata/var/db/repos/gentoo//metadata
|
||||
/wiki//var/db/repos/gentoo/metadata/var/db/repos/gentoo/metadata
|
||||
/wiki//var/db/repos/gentoo/profiles
|
||||
/wiki//var/db/repos/gentoo/profiles/license_groups
|
||||
/wiki//var/db/repos/gentoo/profiles/package.mask
|
||||
/wiki//var/lib/portage
|
||||
/wiki//var/lib/portage/world
|
||||
/wiki//var/run
|
||||
/gcc-bugs/bug-122002-4@http.gcc.gnu.org%2Fbugzilla%2F/T/
|
||||
45
test/double_slash/test.mjs
Normal file
45
test/double_slash/test.mjs
Normal file
@@ -0,0 +1,45 @@
|
||||
import { createReadStream } from "fs";
|
||||
import { createInterface } from "readline";
|
||||
|
||||
async function getPage(path) {
|
||||
return fetch(`http://localhost:8923${path}`)
|
||||
.then(resp => {
|
||||
if (resp.status !== 200) {
|
||||
throw new Error(`wanted status 200, got status: ${resp.status}`);
|
||||
}
|
||||
return resp;
|
||||
})
|
||||
.then(resp => resp.text());
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const fin = createReadStream("input.txt");
|
||||
const rl = createInterface({
|
||||
input: fin,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
const resultSheet = {};
|
||||
|
||||
let failed = false;
|
||||
|
||||
for await (const line of rl) {
|
||||
console.log(line);
|
||||
|
||||
const resp = await getPage(line);
|
||||
resultSheet[line] = {
|
||||
match: resp.includes(`GET ${line}`),
|
||||
line: resp.split("\n")[0],
|
||||
};
|
||||
}
|
||||
|
||||
for (let [k, v] of Object.entries(resultSheet)) {
|
||||
if (!v.match) {
|
||||
failed = true;
|
||||
}
|
||||
|
||||
console.debug({ path: k, results: v });
|
||||
}
|
||||
|
||||
process.exit(failed ? 1 : 0);
|
||||
})();
|
||||
23
test/double_slash/test.sh
Executable file
23
test/double_slash/test.sh
Executable file
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
function cleanup() {
|
||||
pkill -P $$
|
||||
}
|
||||
|
||||
trap cleanup EXIT SIGINT
|
||||
|
||||
# Build static assets
|
||||
(cd ../.. && npm ci && npm run assets)
|
||||
|
||||
go tool anubis --help 2>/dev/null || :
|
||||
|
||||
go run ../cmd/httpdebug &
|
||||
|
||||
go tool anubis \
|
||||
--policy-fname ./anubis.yaml \
|
||||
--use-remote-address \
|
||||
--target=http://localhost:3923 &
|
||||
|
||||
backoff-retry node ./test.mjs
|
||||
2
test/double_slash/var/.gitignore
vendored
Normal file
2
test/double_slash/var/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
@@ -6,7 +6,7 @@ replace github.com/TecharoHQ/anubis => ..
|
||||
|
||||
require (
|
||||
github.com/TecharoHQ/anubis v1.22.0
|
||||
github.com/docker/docker v28.3.2+incompatible
|
||||
github.com/docker/docker v28.3.3+incompatible
|
||||
github.com/facebookgo/flagenv v0.0.0-20160425205200-fcd59fca7456
|
||||
github.com/google/uuid v1.6.0
|
||||
)
|
||||
|
||||
@@ -82,8 +82,8 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v28.3.2+incompatible h1:wn66NJ6pWB1vBZIilP8G3qQPqHy5XymfYn5vsqeA5oA=
|
||||
github.com/docker/docker v28.3.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI=
|
||||
github.com/docker/docker v28.3.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
|
||||
@@ -4,30 +4,37 @@ set -euo pipefail
|
||||
[ ! -z "${DEBUG:-}" ] && set -x
|
||||
|
||||
if [ "$#" -ne 1 ]; then
|
||||
echo "Usage: rigging.sh <user@host>"
|
||||
echo "Usage: rigging.sh <user@host>"
|
||||
fi
|
||||
|
||||
declare -A Hosts
|
||||
|
||||
Hosts["riscv64"]="ubuntu@riscv64.techaro.lol" # GOARCH=riscv64 GOOS=linux
|
||||
Hosts["ppc64le"]="ci@ppc64le.techaro.lol" # GOARCH=ppc64le GOOS=linux
|
||||
Hosts["aarch64-4k"]="rocky@192.168.2.52" # GOARCH=arm64 GOOS=linux 4k page size
|
||||
Hosts["aarch64-16k"]="ci@192.168.2.28" # GOARCH=arm64 GOOS=linux 16k page size
|
||||
|
||||
CIRunnerImage="ghcr.io/techarohq/anubis/ci-runner:latest"
|
||||
RunID=${GITHUB_RUN_ID:-$(uuidgen)}
|
||||
RunFolder="anubis/runs/${RunID}"
|
||||
Target="${1}"
|
||||
Target="${Hosts["$1"]}"
|
||||
|
||||
ssh "${Target}" uname -av
|
||||
ssh "${Target}" uname -av >/dev/null
|
||||
ssh "${Target}" mkdir -p "${RunFolder}"
|
||||
git archive HEAD | ssh "${Target}" tar xC "${RunFolder}"
|
||||
|
||||
ssh "${Target}" << EOF
|
||||
ssh "${Target}" <<EOF
|
||||
set -euo pipefail
|
||||
set -x
|
||||
mkdir -p "anubis/cache/{go,go-build,node}"
|
||||
mkdir -p anubis/cache/{go,go-build,node}
|
||||
podman pull ${CIRunnerImage}
|
||||
podman run --rm -it \
|
||||
-v "\$HOME/${RunFolder}:/app/anubis" \
|
||||
-v "\$HOME/anubis/cache/go:/root/go" \
|
||||
-v "\$HOME/anubis/cache/go-build:/root/.cache/go-build" \
|
||||
-v "\$HOME/anubis/cache/node:/root/.npm" \
|
||||
-v "\$HOME/${RunFolder}:/app/anubis:z" \
|
||||
-v "\$HOME/anubis/cache/go:/root/go:z" \
|
||||
-v "\$HOME/anubis/cache/go-build:/root/.cache/go-build:z" \
|
||||
-v "\$HOME/anubis/cache/node:/root/.npm:z" \
|
||||
-w /app/anubis \
|
||||
${CIRunnerImage} \
|
||||
sh /app/anubis/test/ssh-ci/in-container.sh
|
||||
ssh "${Target}" rm -rf "${RunFolder}"
|
||||
EOF
|
||||
EOF
|
||||
|
||||
19
web/build.sh
19
web/build.sh
@@ -39,9 +39,18 @@ for the JavaScript code in this page.
|
||||
mkdir -p static/locales
|
||||
cp ../lib/localization/locales/*.json static/locales/
|
||||
|
||||
for file in js/*.mjs js/worker/*.mjs; do
|
||||
esbuild "${file}" --sourcemap --bundle --minify --outfile=static/"${file}" --banner:js="${LICENSE}"
|
||||
gzip -f -k -n static/${file}
|
||||
zstd -f -k --ultra -22 static/${file}
|
||||
brotli -fZk static/${file}
|
||||
shopt -s nullglob globstar
|
||||
|
||||
for file in js/**/*.ts js/**/*.mjs; do
|
||||
out="static/${file}"
|
||||
if [[ "$file" == *.ts ]]; then
|
||||
out="static/${file%.ts}.mjs"
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$out")"
|
||||
|
||||
esbuild "$file" --sourcemap --bundle --minify --outfile="$out" --banner:js="$LICENSE"
|
||||
gzip -f -k -n "$out"
|
||||
zstd -f -k --ultra -22 "$out"
|
||||
brotli -fZk "$out"
|
||||
done
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
type ProgressCallback = (nonce: number) => void;
|
||||
|
||||
interface ProcessOptions {
|
||||
basePrefix: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
const getHardwareConcurrency = () =>
|
||||
navigator.hardwareConcurrency !== undefined ? navigator.hardwareConcurrency : 1;
|
||||
|
||||
export default function process(
|
||||
{ basePrefix, version },
|
||||
data,
|
||||
difficulty = 5,
|
||||
signal = null,
|
||||
progressCallback = null,
|
||||
threads = Math.trunc(Math.max(navigator.hardwareConcurrency / 2, 1)),
|
||||
) {
|
||||
options: ProcessOptions,
|
||||
data: string,
|
||||
difficulty: number = 5,
|
||||
signal: AbortSignal | null = null,
|
||||
progressCallback?: ProgressCallback,
|
||||
threads: number = Math.trunc(Math.max(getHardwareConcurrency() / 2, 1)),
|
||||
): Promise<string> {
|
||||
console.debug("fast algo");
|
||||
|
||||
let workerMethod = window.crypto !== undefined ? "webcrypto" : "purejs";
|
||||
@@ -16,13 +26,17 @@ export default function process(
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let webWorkerURL = `${basePrefix}/.within.website/x/cmd/anubis/static/js/worker/sha256-${workerMethod}.mjs?cacheBuster=${version}`;
|
||||
let webWorkerURL = `${options.basePrefix}/.within.website/x/cmd/anubis/static/js/worker/sha256-${workerMethod}.mjs?cacheBuster=${options.version}`;
|
||||
|
||||
console.log(webWorkerURL);
|
||||
|
||||
const workers = [];
|
||||
const workers: Worker[] = [];
|
||||
let settled = false;
|
||||
|
||||
const onAbort = () => {
|
||||
console.log("PoW aborted");
|
||||
cleanup();
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
@@ -34,12 +48,6 @@ export default function process(
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = () => {
|
||||
console.log("PoW aborted");
|
||||
cleanup();
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
|
||||
if (signal != null) {
|
||||
if (signal.aborted) {
|
||||
return onAbort();
|
||||
@@ -1,4 +1,4 @@
|
||||
import fast from "./fast.mjs";
|
||||
import fast from "./fast";
|
||||
|
||||
export default {
|
||||
fast: fast,
|
||||
@@ -1,20 +1,24 @@
|
||||
import algorithms from "./algorithms/index.mjs";
|
||||
import algorithms from "./algorithms";
|
||||
|
||||
const defaultDifficulty = 4;
|
||||
|
||||
const status = document.getElementById("status");
|
||||
const difficultyInput = document.getElementById("difficulty-input");
|
||||
const algorithmSelect = document.getElementById("algorithm-select");
|
||||
const compareSelect = document.getElementById("compare-select");
|
||||
const header = document.getElementById("table-header");
|
||||
const headerCompare = document.getElementById("table-header-compare");
|
||||
const results = document.getElementById("results");
|
||||
const status: HTMLParagraphElement = document.getElementById("status") as HTMLParagraphElement;
|
||||
const difficultyInput: HTMLInputElement = document.getElementById("difficulty-input") as HTMLInputElement;
|
||||
const algorithmSelect: HTMLSelectElement = document.getElementById("algorithm-select") as HTMLSelectElement;
|
||||
const compareSelect: HTMLSelectElement = document.getElementById("compare-select") as HTMLSelectElement;
|
||||
const header: HTMLTableRowElement = document.getElementById("table-header") as HTMLTableRowElement;
|
||||
const headerCompare: HTMLTableSectionElement = document.getElementById("table-header-compare") as HTMLTableSectionElement;
|
||||
const results: HTMLTableRowElement = document.getElementById("results") as HTMLTableRowElement;
|
||||
|
||||
const setupControls = () => {
|
||||
difficultyInput.value = defaultDifficulty;
|
||||
if (defaultDifficulty == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
difficultyInput.value = defaultDifficulty.toString();
|
||||
for (const alg of Object.keys(algorithms)) {
|
||||
const option1 = document.createElement("option");
|
||||
algorithmSelect.append(option1);
|
||||
algorithmSelect?.append(option1);
|
||||
const option2 = document.createElement("option");
|
||||
compareSelect.append(option2);
|
||||
option1.value = option1.innerText = option2.value = option2.innerText = alg;
|
||||
@@ -116,13 +120,13 @@ const benchmarkLoop = async (controller) => {
|
||||
await benchmarkLoop(controller);
|
||||
};
|
||||
|
||||
let controller = null;
|
||||
let controller: AbortController | null = null;
|
||||
const reset = () => {
|
||||
stats.time = stats.iters = 0;
|
||||
comparison.time = comparison.iters = 0;
|
||||
results.innerHTML = status.innerText = "";
|
||||
|
||||
const table = results.parentElement;
|
||||
const table = results.parentElement as HTMLElement;
|
||||
if (compareSelect.value !== "NONE") {
|
||||
table.style.gridTemplateColumns = "repeat(4,auto)";
|
||||
header.style.display = "none";
|
||||
@@ -1,12 +1,21 @@
|
||||
import algorithms from "./algorithms/index.mjs";
|
||||
import algorithms from "./algorithms";
|
||||
|
||||
// from Xeact
|
||||
const u = (url = "", params = {}) => {
|
||||
const u = (url: string = "", params: Record<string, any> = {}) => {
|
||||
let result = new URL(url, window.location.href);
|
||||
Object.entries(params).forEach(([k, v]) => result.searchParams.set(k, v));
|
||||
return result.toString();
|
||||
};
|
||||
|
||||
const j = (id: string): any | null => {
|
||||
const elem = document.getElementById(id);
|
||||
if (elem === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(elem.textContent);
|
||||
};
|
||||
|
||||
const imageURL = (mood, cacheBuster, basePrefix) =>
|
||||
u(`${basePrefix}/.within.website/x/cmd/anubis/static/img/${mood}.webp`, {
|
||||
cacheBuster,
|
||||
@@ -14,9 +23,10 @@ const imageURL = (mood, cacheBuster, basePrefix) =>
|
||||
|
||||
// Detect available languages by loading the manifest
|
||||
const getAvailableLanguages = async () => {
|
||||
const basePrefix = JSON.parse(
|
||||
document.getElementById("anubis_base_prefix").textContent,
|
||||
);
|
||||
const basePrefix = j("anubis_base_prefix");
|
||||
if (basePrefix === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${basePrefix}/.within.website/x/cmd/anubis/static/locales/manifest.json`);
|
||||
@@ -38,9 +48,11 @@ const getBrowserLanguage = async () =>
|
||||
|
||||
// Load translations from JSON files
|
||||
const loadTranslations = async (lang) => {
|
||||
const basePrefix = JSON.parse(
|
||||
document.getElementById("anubis_base_prefix").textContent,
|
||||
);
|
||||
const basePrefix = j("anubis_base_prefix");
|
||||
if (basePrefix === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${basePrefix}/.within.website/x/cmd/anubis/static/locales/${lang}.json`);
|
||||
return await response.json();
|
||||
@@ -54,9 +66,10 @@ const loadTranslations = async (lang) => {
|
||||
};
|
||||
|
||||
const getRedirectUrl = () => {
|
||||
const publicUrl = JSON.parse(
|
||||
document.getElementById("anubis_public_url").textContent,
|
||||
);
|
||||
const publicUrl = j("anubis_public_url");
|
||||
if (publicUrl === null) {
|
||||
return;
|
||||
}
|
||||
if (publicUrl && window.location.href.startsWith(publicUrl)) {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get('redir');
|
||||
@@ -91,16 +104,14 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
value: navigator.cookieEnabled,
|
||||
},
|
||||
];
|
||||
const status = document.getElementById("status");
|
||||
const image = document.getElementById("image");
|
||||
const title = document.getElementById("title");
|
||||
const progress = document.getElementById("progress");
|
||||
const anubisVersion = JSON.parse(
|
||||
document.getElementById("anubis_version").textContent,
|
||||
);
|
||||
const basePrefix = JSON.parse(
|
||||
document.getElementById("anubis_base_prefix").textContent,
|
||||
);
|
||||
|
||||
const status: HTMLParagraphElement = document.getElementById("status") as HTMLParagraphElement;
|
||||
const image: HTMLImageElement = document.getElementById("image") as HTMLImageElement;
|
||||
const title: HTMLHeadingElement = document.getElementById("title") as HTMLHeadingElement;
|
||||
const progress: HTMLDivElement = document.getElementById("progress") as HTMLDivElement;
|
||||
|
||||
const anubisVersion = j("anubis_version");
|
||||
const basePrefix = j("anubis_base_prefix");
|
||||
const details = document.querySelector("details");
|
||||
let userReadDetails = false;
|
||||
|
||||
@@ -132,9 +143,7 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
}
|
||||
}
|
||||
|
||||
const { challenge, rules } = JSON.parse(
|
||||
document.getElementById("anubis_challenge").textContent,
|
||||
);
|
||||
const { challenge, rules } = j("anubis_challenge");
|
||||
|
||||
const process = algorithms[rules.algorithm];
|
||||
if (!process) {
|
||||
@@ -182,7 +191,9 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
const probability = Math.pow(1 - likelihood, iters);
|
||||
const distance = (1 - Math.pow(probability, 2)) * 100;
|
||||
progress["aria-valuenow"] = distance;
|
||||
progress.firstElementChild.style.width = `${distance}%`;
|
||||
if (progress.firstElementChild !== null) {
|
||||
(progress.firstElementChild as HTMLElement).style.width = `${distance}%`;
|
||||
}
|
||||
|
||||
if (probability < 0.1 && !showingApology) {
|
||||
status.append(
|
||||
@@ -197,7 +208,7 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
console.log({ hash, nonce });
|
||||
|
||||
if (userReadDetails) {
|
||||
const container = document.getElementById("progress");
|
||||
const container: HTMLDivElement = document.getElementById("progress") as HTMLDivElement;
|
||||
|
||||
// Style progress bar as a continue button
|
||||
container.style.display = "flex";
|
||||
@@ -6,7 +6,7 @@ const calculateSHA256 = (text) => {
|
||||
return hash.digest();
|
||||
};
|
||||
|
||||
function toHexString(arr) {
|
||||
function toHexString(arr: Uint8Array): string {
|
||||
return Array.from(arr)
|
||||
.map((c) => c.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
@@ -1,10 +1,11 @@
|
||||
const encoder = new TextEncoder();
|
||||
const calculateSHA256 = async (input) => {
|
||||
|
||||
const calculateSHA256 = async (input: string) => {
|
||||
const data = encoder.encode(input);
|
||||
return await crypto.subtle.digest("SHA-256", data);
|
||||
};
|
||||
|
||||
const toHexString = (byteArray) => {
|
||||
const toHexString = (byteArray: Uint8Array) => {
|
||||
return byteArray.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user