Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c750e53221 | ||
|
|
2c63384606 | ||
|
|
4231440b69 | ||
|
|
08ad7b0a79 | ||
|
|
b7665e9acc | ||
|
|
b37094e481 | ||
|
|
7cc642f8b8 | ||
|
|
0358e137f1 | ||
|
|
14ed31fddc | ||
|
|
50c29e4595 |
@@ -71,10 +71,10 @@ jobs:
|
||||
services=$(sh ci/changed-services.sh)
|
||||
echo "changed since the last deployment: ${services:-nothing}"
|
||||
case " $services " in
|
||||
*" backend "*|*" worker "*|*" forum "*|*" horoscope-api "*) ;;
|
||||
*" backend "*|*" worker "*|*" forum "*|*" mcp "*|*" horoscope-api "*) ;;
|
||||
*) echo "no Rust service changed: tests skipped"; exit 0 ;;
|
||||
esac
|
||||
cargo test --locked -p backend -p worker -p forum -p object-storage -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates
|
||||
cargo test --locked -p backend -p worker -p forum -p mcp -p object-storage -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates
|
||||
|
||||
build:
|
||||
needs: test
|
||||
@@ -127,7 +127,7 @@ jobs:
|
||||
set -eu
|
||||
apk add --no-cache -q curl jq
|
||||
prod=$(git ls-remote origin refs/heads/prod | cut -c1-12)
|
||||
for svc in horoscope-api backend worker forum frontend; do
|
||||
for svc in horoscope-api backend worker forum mcp frontend; do
|
||||
name="sorsfonalak-$svc"
|
||||
page=1
|
||||
: > versions.tsv
|
||||
@@ -152,7 +152,7 @@ jobs:
|
||||
if: always()
|
||||
run: |
|
||||
docker logout "$REGISTRY" || true
|
||||
for svc in horoscope-api backend worker forum frontend; do
|
||||
for svc in horoscope-api backend worker forum mcp frontend; do
|
||||
docker images "$IMAGE_PREFIX-$svc" --format '{{.Repository}}:{{.Tag}}' | xargs -r docker rmi >/dev/null 2>&1 || true
|
||||
done
|
||||
docker image prune -f >/dev/null
|
||||
|
||||
Generated
+365
-27
@@ -189,6 +189,7 @@ dependencies = [
|
||||
"argon2",
|
||||
"axum",
|
||||
"axum-extra",
|
||||
"base64 0.22.1",
|
||||
"db",
|
||||
"deunicode",
|
||||
"email-templates",
|
||||
@@ -205,7 +206,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"service-kit",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"sqlx",
|
||||
"thiserror",
|
||||
"time",
|
||||
@@ -249,7 +250,7 @@ version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -261,6 +262,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -350,6 +360,12 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.2"
|
||||
@@ -446,6 +462,49 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
@@ -465,7 +524,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"rand 0.9.5",
|
||||
"serde",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"sqlx",
|
||||
"time",
|
||||
"uuid",
|
||||
@@ -477,7 +536,7 @@ version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"pem-rfc7468",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -503,12 +562,23 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"const-oid 0.9.6",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid 0.10.3",
|
||||
"crypto-common 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.7"
|
||||
@@ -526,6 +596,12 @@ version = "0.15.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||
|
||||
[[package]]
|
||||
name = "dyn-clone"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
@@ -720,7 +796,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"service-kit",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"sqlx",
|
||||
"thiserror",
|
||||
"time",
|
||||
@@ -732,6 +808,21 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-executor",
|
||||
"futures-io",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-channel"
|
||||
version = "0.3.34"
|
||||
@@ -776,6 +867,17 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.34"
|
||||
@@ -794,8 +896,10 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-macro",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"memchr",
|
||||
@@ -818,7 +922,7 @@ name = "geo-tz"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"deunicode",
|
||||
"jiff",
|
||||
"jiff 0.2.42",
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
@@ -938,7 +1042,7 @@ version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -959,7 +1063,7 @@ dependencies = [
|
||||
"axum",
|
||||
"geo-tz",
|
||||
"http-body-util",
|
||||
"jiff",
|
||||
"jiff 0.2.42",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"service-kit",
|
||||
@@ -1035,6 +1139,15 @@ version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
@@ -1178,6 +1291,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "1.1.0"
|
||||
@@ -1239,6 +1358,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.1",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1259,8 +1380,22 @@ version = "0.2.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fefca06093eeaed707a905795e68206da0edca4edef23d2a3997a3ddbee462aa"
|
||||
dependencies = [
|
||||
"jiff-core",
|
||||
"jiff-static",
|
||||
"jiff-core 0.1.4",
|
||||
"jiff-static 0.2.42",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"portable-atomic-util",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f"
|
||||
dependencies = [
|
||||
"jiff-core 1.0.2",
|
||||
"jiff-static 1.0.3",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"portable-atomic-util",
|
||||
@@ -1276,18 +1411,39 @@ dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-core"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "0.2.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d3213549742662eea1a18e6c5af9be5dfbabeb7611ab71356a54928ec398f0"
|
||||
dependencies = [
|
||||
"jiff-core",
|
||||
"jiff-core 0.1.4",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jiff-static"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8"
|
||||
dependencies = [
|
||||
"jiff-core 1.0.2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.107"
|
||||
@@ -1483,6 +1639,26 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "mcp"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"http-body-util",
|
||||
"reqwest",
|
||||
"rmcp",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"service-kit",
|
||||
"sha2 0.10.9",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
@@ -1490,7 +1666,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1641,7 +1817,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"hmac",
|
||||
"reqwest",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror",
|
||||
"time",
|
||||
"tokio",
|
||||
@@ -1694,6 +1870,12 @@ dependencies = [
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||
|
||||
[[package]]
|
||||
name = "pdf-writer"
|
||||
version = "0.15.0"
|
||||
@@ -2060,6 +2242,26 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ref-cast"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
|
||||
dependencies = [
|
||||
"ref-cast-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ref-cast-impl"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
@@ -2155,6 +2357,56 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc4fa9a7558c480e1817c0f02e9a73782001ac1f47fb9d26cc073915963282ea"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.1",
|
||||
"bytes",
|
||||
"futures",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"indexmap",
|
||||
"jiff 1.0.3",
|
||||
"libc",
|
||||
"pastey",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"rand 0.10.3",
|
||||
"rmcp-macros",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.2",
|
||||
"sse-stream",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tokio-util",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"unicode-general-category",
|
||||
"unicode-normalization",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp-macros"
|
||||
version = "3.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43c1bf063ba32333267a8bc282ec33ae0edf56bf74890118cb0c7bf910a7a1c0"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_json",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.20.0"
|
||||
@@ -2176,8 +2428,8 @@ version = "0.9.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"digest",
|
||||
"const-oid 0.9.6",
|
||||
"digest 0.10.7",
|
||||
"num-bigint-dig",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
@@ -2262,6 +2514,31 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"ref-cast",
|
||||
"schemars_derive",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars_derive"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_derive_internals",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
@@ -2298,6 +2575,17 @@ dependencies = [
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive_internals"
|
||||
version = "0.30.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
@@ -2355,7 +2643,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2366,7 +2654,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2400,7 +2699,7 @@ version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
@@ -2538,7 +2837,7 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"smallvec",
|
||||
"thiserror",
|
||||
"time",
|
||||
@@ -2577,7 +2876,7 @@ dependencies = [
|
||||
"quote",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"sqlx-core",
|
||||
"sqlx-mysql",
|
||||
"sqlx-postgres",
|
||||
@@ -2599,7 +2898,7 @@ dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
"crc",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
"dotenvy",
|
||||
"either",
|
||||
"futures-channel",
|
||||
@@ -2620,7 +2919,7 @@ dependencies = [
|
||||
"rsa",
|
||||
"serde",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"smallvec",
|
||||
"sqlx-core",
|
||||
"stringprep",
|
||||
@@ -2659,7 +2958,7 @@ dependencies = [
|
||||
"rand 0.8.8",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"smallvec",
|
||||
"sqlx-core",
|
||||
"stringprep",
|
||||
@@ -2696,6 +2995,19 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sse-stream"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -2722,6 +3034,12 @@ dependencies = [
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
@@ -2966,6 +3284,20 @@ dependencies = [
|
||||
"tungstenite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-util"
|
||||
version = "0.7.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"libc",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
@@ -3156,6 +3488,12 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-general-category"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
@@ -3589,7 +3927,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"service-kit",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"sqlx",
|
||||
"time",
|
||||
"tokio",
|
||||
|
||||
@@ -15,6 +15,7 @@ members = [
|
||||
"services/backend",
|
||||
"services/worker",
|
||||
"services/forum",
|
||||
"services/mcp",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
# Needs the full history and the tags (git fetch --unshallow --tags).
|
||||
#
|
||||
# frontend services/frontend/
|
||||
# backend, worker, forum their folder, the shared crates/, Cargo.toml, Cargo.lock
|
||||
# backend, worker, forum, mcp their folder, the shared crates/, Cargo.toml, Cargo.lock
|
||||
# horoscope-api the same, and scripts/fetch-deps.sh
|
||||
set -u
|
||||
ALL="horoscope-api backend worker forum frontend"
|
||||
ALL="horoscope-api backend worker forum mcp frontend"
|
||||
prev=$(git describe --tags --abbrev=0 --match 'v*' HEAD 2>/dev/null) || { echo "$ALL"; exit 0; }
|
||||
files=$(git diff --name-only "$prev" HEAD) || { echo "$ALL"; exit 0; }
|
||||
changed() { printf '%s\n' "$files" | grep -Eq "$1"; }
|
||||
rust='^(crates/|Cargo\.toml$|Cargo\.lock$)'
|
||||
out=""
|
||||
changed "^services/horoscope-api/|^scripts/fetch-deps\.sh$|$rust" && out="$out horoscope-api"
|
||||
for svc in backend worker forum; do
|
||||
for svc in backend worker forum mcp; do
|
||||
changed "^services/$svc/|$rust" && out="$out $svc"
|
||||
done
|
||||
changed '^services/frontend/' && out="$out frontend"
|
||||
|
||||
@@ -28,6 +28,10 @@ pub enum Kind {
|
||||
/// A detailed analysis of a famous person's chart, about them in the third
|
||||
/// person, for the public pages (the name comes with the data, see [`with_name`]).
|
||||
Celebrity,
|
||||
/// The free weekly horoscope: the week's sky on the member's own chart, a
|
||||
/// title and a few paragraphs. Written by the summary's model; its prompt
|
||||
/// is not edited on the admin page (so it is not in [`Kind::ALL`]).
|
||||
Weekly,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -44,6 +48,7 @@ impl Kind {
|
||||
Kind::Forecast => "forecast",
|
||||
Kind::Question => "question",
|
||||
Kind::Celebrity => "celebrity",
|
||||
Kind::Weekly => "weekly",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +60,7 @@ impl Kind {
|
||||
"forecast" => Some(Kind::Forecast),
|
||||
"question" => Some(Kind::Question),
|
||||
"celebrity" => Some(Kind::Celebrity),
|
||||
"weekly" => Some(Kind::Weekly),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -153,7 +159,7 @@ fn sections_in(kind: Kind, language: &str) -> Vec<(&'static str, &'static str)>
|
||||
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS_HU,
|
||||
Kind::Synastry => &SYNASTRY_SECTIONS_HU,
|
||||
Kind::Forecast => &FORECAST_SECTIONS_HU,
|
||||
Kind::Summary | Kind::Question => &[],
|
||||
Kind::Summary | Kind::Question | Kind::Weekly => &[],
|
||||
};
|
||||
sections(kind).iter().zip(hu).map(|(&(key, en), &hu)| (key, if language == "hu" { hu } else { en })).collect()
|
||||
}
|
||||
@@ -163,7 +169,7 @@ fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
|
||||
Kind::Natal | Kind::Celebrity => &NATAL_SECTIONS,
|
||||
Kind::Synastry => &SYNASTRY_SECTIONS,
|
||||
Kind::Forecast => &FORECAST_SECTIONS,
|
||||
Kind::Summary | Kind::Question => &[],
|
||||
Kind::Summary | Kind::Question | Kind::Weekly => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +190,17 @@ pub fn schema(kind: Kind) -> Value {
|
||||
}
|
||||
});
|
||||
}
|
||||
if kind == Kind::Weekly {
|
||||
return json!({
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["title", "text"],
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Short, evocative title for this week (at most 6 words)"},
|
||||
"text": {"type": "string", "description": "3 short paragraphs separated by a blank line, 150-220 words in all"}
|
||||
}
|
||||
});
|
||||
}
|
||||
if kind == Kind::Summary {
|
||||
return json!({
|
||||
"type": "object",
|
||||
@@ -269,6 +286,13 @@ fn hungarian_system(kind: Kind) -> String {
|
||||
előrejelzés kb. 1500–2000 szó.",
|
||||
),
|
||||
Kind::Question => unreachable!("questions have their own prompt"),
|
||||
Kind::Weekly => (
|
||||
"személyes heti horoszkópot (a hét égboltja az olvasó saját születési képletén; ingyenes, hétfőnként új)",
|
||||
SECOND_PERSON_HU,
|
||||
"Terjedelem: 3 rövid bekezdés, összesen 150–220 szó. Az első a hét fő témája a két-három legerősebb \
|
||||
tranzitból; a második a hét kulcsnapjai (a hét napjainak nevével: „szerdán”, „a hét végén”); a harmadik \
|
||||
egy konkrét, a hétre szóló javaslat. Ne sorold fel az összes tranzitot.",
|
||||
),
|
||||
Kind::Celebrity => (
|
||||
"portrét egy híres ember születési képletéről (az olvasó nem ő maga, hanem egy érdeklődő látogató)",
|
||||
THIRD_PERSON_HU,
|
||||
@@ -315,6 +339,9 @@ használhatsz.
|
||||
if kind == Kind::Celebrity {
|
||||
text.push_str(CELEBRITY_RULES_HU);
|
||||
}
|
||||
if kind == Kind::Weekly {
|
||||
text.push_str(WEEKLY_RULES_HU);
|
||||
}
|
||||
text.push_str(HUNGARIAN_TERMS);
|
||||
if kind == Kind::Forecast {
|
||||
text.push_str(HUNGARIAN_FORECAST_TERMS);
|
||||
@@ -341,6 +368,23 @@ rajzolódik ki, aki…”), mert lehet, hogy már nem él. Ne állíts semmit az
|
||||
kijelentést.
|
||||
- Az „advice” mező nem neki szóló tanács, hanem zárógondolat: egy bekezdés, amely összefogja a portrét.";
|
||||
|
||||
const WEEKLY_RULES_HU: &str = "
|
||||
|
||||
A heti horoszkóp szabályai:
|
||||
- Ez nem jellemrajz, hanem a hétről szól: a születési képletet csak ott említsd, ahol egy tranzit érinti.
|
||||
- Úgy súlyozz, ahogy egy asztrológus: a lassú bolygók (Jupitertől a Plútóig) tranzitjai a hét háttere; a gyors \
|
||||
bolygók pontos fényszögei a Napra, a Holdra, az Aszcendensre, az MC-re és a horoszkóp uralkodójára a hét eseményes \
|
||||
napjai; a Hold jegyváltásai a hét hangulatának hullámzása; az újhold, a telihold és a retrográd fordulók csak akkor \
|
||||
hangsúlyosak, ha a képletet érintik.
|
||||
- Témákról, hangulatokról és lehetőségekről írj, ne biztos eseményekről: „jó nap arra, hogy”, „hozhat”, „azt kéri \
|
||||
tőled”. Semmit betegségről, halálról, balesetről, terhességről, pénz nyereségéről vagy elvesztéséről. A feszült \
|
||||
fényszögeket is kihívásként és lehetőségként írd le, ne riogass.
|
||||
- Csak az adatokban szereplő napokat használd. A napokat a hét napjainak nevével említsd (hétfő, kedd, …), \
|
||||
dátumszám nélkül.
|
||||
- Ne reklámozz, és ne említs más elemzést vagy szolgáltatást.
|
||||
- Kifejezések: tranzit („a Mars tranzitja a Napod felett”), retrográd, újhold, telihold, a Hold jegyváltása. A \
|
||||
születési képlet pontjait „a születési Vénuszod”, „a Holdad” formában említsd, ne „natális”-ként.";
|
||||
|
||||
const FORECAST_RULES_HU: &str = "
|
||||
|
||||
Az előrejelzés szabályai:
|
||||
@@ -408,6 +452,10 @@ pub fn default_system(kind: Kind, language: &str) -> String {
|
||||
}
|
||||
let (role, reader) = match kind {
|
||||
Kind::Question => unreachable!("questions have their own prompt"),
|
||||
Kind::Weekly => (
|
||||
"a personal weekly horoscope (the week's sky on the reader's own natal chart; free, new every Monday)",
|
||||
"Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
|
||||
),
|
||||
Kind::Celebrity => (
|
||||
"a portrait of a famous person's natal chart (the reader is not that person but an interested visitor)",
|
||||
"Write about them in the third person singular, by name: the full name in the summary, later also the \
|
||||
@@ -455,6 +503,9 @@ and no medical, legal or financial advice.
|
||||
length = match kind {
|
||||
Kind::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
|
||||
paragraphs; the whole forecast about 1500-2000 words.",
|
||||
Kind::Weekly => "Length: 3 short paragraphs, 150-220 words in all. The first is the main theme of the \
|
||||
week from the two or three strongest transits; the second the key days (by weekday name: \"on \
|
||||
Wednesday\", \"at the weekend\"); the third one concrete suggestion for the week. Do not list every transit.",
|
||||
Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
|
||||
(if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
|
||||
a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
|
||||
@@ -468,9 +519,25 @@ and no medical, legal or financial advice.
|
||||
if kind == Kind::Celebrity {
|
||||
text.push_str(CELEBRITY_RULES);
|
||||
}
|
||||
if kind == Kind::Weekly {
|
||||
text.push_str(WEEKLY_RULES);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
const WEEKLY_RULES: &str = "
|
||||
|
||||
Weekly horoscope rules:
|
||||
- This is not a portrait but the week: mention the natal chart only where a transit touches it.
|
||||
- Weigh as an astrologer would: the slow planets' transits (Jupiter to Pluto) are the background of the week; the \
|
||||
fast planets' exact aspects to the Sun, Moon, Ascendant, Midheaven and chart ruler mark its eventful days; the Moon's \
|
||||
sign changes are the ebb and flow of the mood; new and full moons and stations matter where they touch the chart.
|
||||
- Write about themes, moods and opportunities, never certain events: \"a good day to\", \"may bring\", \"asks you \
|
||||
to\". Nothing about illness, death, accidents, pregnancy, or winning or losing money. Describe tense aspects as \
|
||||
challenges and chances, without alarm.
|
||||
- Use only the days in the data, and name them by weekday (Monday, Tuesday, ...), without dates.
|
||||
- No sales talk, and do not mention any other analysis or service.";
|
||||
|
||||
const CELEBRITY_RULES: &str = "
|
||||
|
||||
Rules for a famous person's portrait:
|
||||
@@ -651,6 +718,8 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
|
||||
user.push_str(chart_text);
|
||||
if kind == Kind::Summary {
|
||||
user.push_str(if hu { "\nMost írd meg a rövid összefoglalót." } else { "\nWrite the short summary now." });
|
||||
} else if kind == Kind::Weekly {
|
||||
user.push_str(if hu { "\nMost írd meg a heti horoszkópot." } else { "\nWrite the weekly horoscope now." });
|
||||
} else {
|
||||
user.push_str(if hu {
|
||||
"\nA megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom):\n"
|
||||
@@ -672,6 +741,7 @@ pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>)
|
||||
Kind::Summary => "chart_summary",
|
||||
Kind::Question => "question_answer",
|
||||
Kind::Forecast => "forecast_analysis",
|
||||
Kind::Weekly => "weekly_horoscope",
|
||||
},
|
||||
schema: schema(kind),
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn date_of(jd_ut: f64, offset_hours: f64) -> String {
|
||||
}
|
||||
|
||||
/// The zodiac of the natal chart, geocentric (transits are not topocentric).
|
||||
fn frame_of(natal: &NatalChart) -> Frame {
|
||||
pub(crate) fn frame_of(natal: &NatalChart) -> Frame {
|
||||
let o = natal.settings.options;
|
||||
Frame { sidereal: (o.zodiac == ZodiacType::Sidereal).then_some(o.ayanamsa), topocentric: None }
|
||||
}
|
||||
@@ -70,7 +70,7 @@ fn natal_lon(natal: &NatalChart, id: PointId) -> Option<f64> {
|
||||
natal.points.iter().find(|p| p.id == id).map(|p| p.position.longitude)
|
||||
}
|
||||
|
||||
fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||
pub(crate) fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||
let houses = natal.houses.as_ref()?;
|
||||
let mut cusps = [0.0; 12];
|
||||
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
||||
@@ -82,7 +82,7 @@ fn cusps_of(natal: &NatalChart) -> Option<[f64; 12]> {
|
||||
/// The natal points transits and progressions are measured to: the ten
|
||||
/// planets and, with a known birth time, the Ascendant and the Midheaven.
|
||||
/// Without a birth time the Moon is left out (it may be 7° off).
|
||||
fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
|
||||
pub(crate) fn natal_targets(natal: &NatalChart) -> Vec<(PointId, f64)> {
|
||||
let known = natal.angles.is_some();
|
||||
let mut out: Vec<(PointId, f64)> = Body::PLANETS
|
||||
.iter()
|
||||
@@ -129,15 +129,15 @@ type Window = (f64, f64);
|
||||
type Crossings = (Vec<Window>, Vec<(f64, bool)>);
|
||||
|
||||
/// Longitude and daily motion sampled at equal steps.
|
||||
struct Samples {
|
||||
pub(crate) struct Samples {
|
||||
start: f64,
|
||||
step: f64,
|
||||
lon: Vec<f64>,
|
||||
speed: Vec<f64>,
|
||||
pub(crate) lon: Vec<f64>,
|
||||
pub(crate) speed: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Samples {
|
||||
fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
||||
pub(crate) fn take(from: f64, to: f64, step: f64, at: &dyn Fn(f64) -> Result<(f64, f64)>) -> Result<Self> {
|
||||
let n = ((to - from) / step).ceil() as usize + 1;
|
||||
let mut lon = Vec::with_capacity(n);
|
||||
let mut speed = Vec::with_capacity(n);
|
||||
@@ -149,7 +149,7 @@ impl Samples {
|
||||
Ok(Self { start: from, step, lon, speed })
|
||||
}
|
||||
|
||||
fn jd(&self, i: usize) -> f64 {
|
||||
pub(crate) fn jd(&self, i: usize) -> f64 {
|
||||
self.start + i as f64 * self.step
|
||||
}
|
||||
}
|
||||
@@ -230,22 +230,30 @@ pub struct Contact {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
#[serde(skip)]
|
||||
peak_jd: f64,
|
||||
pub(crate) peak_jd: f64,
|
||||
}
|
||||
|
||||
/// One year of a natal chart.
|
||||
struct Year<'a> {
|
||||
engine: &'a dyn Ephemeris,
|
||||
natal: &'a NatalChart,
|
||||
frame: Frame,
|
||||
start: f64,
|
||||
end: f64,
|
||||
offset: f64,
|
||||
cusps: Option<[f64; 12]>,
|
||||
/// What counts as a contact: the orb, the aspects, and whether the periods
|
||||
/// within orb are listed.
|
||||
pub(crate) struct ContactRule<'a> {
|
||||
pub(crate) orb: f64,
|
||||
pub(crate) aspects: &'a [AspectKind],
|
||||
pub(crate) with_periods: bool,
|
||||
}
|
||||
|
||||
/// One year of a natal chart (or any shorter span: see [`crate::week`]).
|
||||
pub(crate) struct Year<'a> {
|
||||
pub(crate) engine: &'a dyn Ephemeris,
|
||||
pub(crate) natal: &'a NatalChart,
|
||||
pub(crate) frame: Frame,
|
||||
pub(crate) start: f64,
|
||||
pub(crate) end: f64,
|
||||
pub(crate) offset: f64,
|
||||
pub(crate) cusps: Option<[f64; 12]>,
|
||||
}
|
||||
|
||||
impl Year<'_> {
|
||||
fn date(&self, jd: f64) -> String {
|
||||
pub(crate) fn date(&self, jd: f64) -> String {
|
||||
date_of(jd, self.offset)
|
||||
}
|
||||
|
||||
@@ -254,17 +262,17 @@ impl Year<'_> {
|
||||
}
|
||||
|
||||
/// Contacts of one moving planet (sampled in `s`) with the natal points.
|
||||
fn contacts(
|
||||
pub(crate) fn contacts(
|
||||
&self,
|
||||
planet: PointId,
|
||||
s: &Samples,
|
||||
lon_at: &dyn Fn(f64) -> Result<f64>,
|
||||
targets: &[(PointId, f64)],
|
||||
with_periods: bool,
|
||||
rule: &ContactRule,
|
||||
) -> Result<Vec<Contact>> {
|
||||
let mut out = Vec::new();
|
||||
for &(natal_point, natal) in targets {
|
||||
for aspect in ASPECTS {
|
||||
for &aspect in rule.aspects {
|
||||
let a = aspect.angle();
|
||||
let mut points = vec![natal + a];
|
||||
if a != 0.0 && a != 180.0 {
|
||||
@@ -272,7 +280,7 @@ impl Year<'_> {
|
||||
}
|
||||
let (mut windows, mut exact) = (Vec::new(), Vec::new());
|
||||
for target in points {
|
||||
let (w, e) = crossings(s, target, ORB, lon_at)?;
|
||||
let (w, e) = crossings(s, target, rule.orb, lon_at)?;
|
||||
windows.extend(w);
|
||||
exact.extend(e);
|
||||
}
|
||||
@@ -289,7 +297,7 @@ impl Year<'_> {
|
||||
.map(|i| (i, separation(s.lon[i], natal)))
|
||||
.map(|(i, sep)| (i, (sep - a).abs()))
|
||||
.min_by(|x, y| x.1.total_cmp(&y.1))
|
||||
.unwrap_or((0, ORB));
|
||||
.unwrap_or((0, rule.orb));
|
||||
let (peak_jd, min_orb) = match exact.first() {
|
||||
Some(&(jd, _)) => (jd, 0.0),
|
||||
None => (s.jd(closest_i), closest),
|
||||
@@ -301,7 +309,7 @@ impl Year<'_> {
|
||||
aspect,
|
||||
nature: aspect.nature(),
|
||||
exact: exact.iter().map(|&(jd, retrograde)| Exact { date: self.date(jd), retrograde }).collect(),
|
||||
periods: if with_periods {
|
||||
periods: if rule.with_periods {
|
||||
windows
|
||||
.iter()
|
||||
.map(|&(from, to)| DateRange { start: self.date(from), end: self.date(to) })
|
||||
@@ -319,7 +327,7 @@ impl Year<'_> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
|
||||
pub(crate) fn position(&self, body: Body, jd: f64) -> Result<(f64, f64)> {
|
||||
let s = self.engine.position(body, jd, &self.frame)?;
|
||||
Ok((s.longitude, s.speed_longitude))
|
||||
}
|
||||
@@ -333,7 +341,8 @@ impl Year<'_> {
|
||||
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||
let s = Samples::take(self.start - MARGIN_DAYS, self.end + MARGIN_DAYS, 1.0, &at)?;
|
||||
let planet = PointId::from_planet(body);
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, true)?);
|
||||
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: true };
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||
if let Some(cusps) = self.cusps {
|
||||
houses.push(self.house_changes(planet, &s, &cusps));
|
||||
}
|
||||
@@ -378,7 +387,8 @@ impl Year<'_> {
|
||||
// A progressed planet meeting its own natal place only matters for the Moon (the progressed lunar return).
|
||||
let own: Vec<(PointId, f64)> =
|
||||
targets.iter().copied().filter(|&(id, _)| id != planet || body == Body::Moon).collect();
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &own, false)?);
|
||||
let rule = ContactRule { orb: ORB, aspects: &ASPECTS, with_periods: false };
|
||||
contacts.extend(self.contacts(planet, &s, &lon_at, &own, &rule)?);
|
||||
}
|
||||
let start = ZodiacPosition::new(s.lon[0]);
|
||||
let mut sign_changes = Vec::new();
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
||||
//! without touching the chart logic. [`synastry`] compares two charts;
|
||||
//! [`forecast`] looks at one year of a chart (solar return, transits,
|
||||
//! progressions, profection, eclipses); [`sky`] is the sky by date, the same
|
||||
//! for everyone (lunar phases, retrograde periods).
|
||||
//! progressions, profection, eclipses); [`week`] is one week of a chart (the
|
||||
//! weekly horoscope); [`sky`] is the sky by date, the same for everyone (lunar
|
||||
//! phases, retrograde periods).
|
||||
|
||||
pub mod angle;
|
||||
pub mod chart;
|
||||
@@ -17,6 +18,7 @@ pub mod sky;
|
||||
pub mod synastry;
|
||||
pub mod time;
|
||||
pub mod types;
|
||||
pub mod week;
|
||||
|
||||
#[cfg(feature = "swisseph")]
|
||||
pub mod swiss;
|
||||
@@ -29,3 +31,4 @@ pub use engine::{
|
||||
pub use forecast::{Forecast, calculate_forecast, solar_return};
|
||||
pub use synastry::{Synastry, calculate_synastry};
|
||||
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
||||
pub use week::{Week, calculate_week};
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! One week of a natal chart, for the weekly horoscope: the planets' aspects
|
||||
//! to the natal points during the week (with the day each is exact), where
|
||||
//! the planets stand at the start, the Moon's sign changes, the main lunar
|
||||
//! phases, and the planets' stations and sign changes.
|
||||
//!
|
||||
//! The aspects use the yearly forecast's machinery ([`crate::forecast`]) on a
|
||||
//! seven-day span, with the Sun to Pluto as the moving planets (the Moon
|
||||
//! would touch every natal point in a week, so only its signs are given).
|
||||
//! Dates are calendar days at a fixed UTC offset given by the caller.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::chart::{AspectKind, NatalChart, PointId, ZodiacPosition, house_of};
|
||||
use crate::engine::{EngineError, Ephemeris};
|
||||
use crate::forecast::{Contact, ContactRule, Samples, Year, cusps_of, frame_of, natal_targets};
|
||||
use crate::sky::{LunationKind, RETROGRADING, lunations, moon_ingresses, stations};
|
||||
use crate::types::{Body, ZodiacSign};
|
||||
|
||||
type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
/// The moving planets: everything but the Moon.
|
||||
const MOVING: [Body; 9] = [
|
||||
Body::Sun,
|
||||
Body::Mercury,
|
||||
Body::Venus,
|
||||
Body::Mars,
|
||||
Body::Jupiter,
|
||||
Body::Saturn,
|
||||
Body::Uranus,
|
||||
Body::Neptune,
|
||||
Body::Pluto,
|
||||
];
|
||||
/// The major aspects only: a week has room for the strong themes.
|
||||
const ASPECTS: [AspectKind; 5] =
|
||||
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
||||
/// Orb of a contact, degrees: within it at some time during the week.
|
||||
pub const WEEK_ORB: f64 = 1.0;
|
||||
/// Sampling step, days (Mercury moves at most about 2° a day).
|
||||
const STEP: f64 = 0.25;
|
||||
/// Days sampled around the week, so a pass beginning before it is found whole.
|
||||
const MARGIN_DAYS: f64 = 20.0;
|
||||
|
||||
/// A planet at the start of the week.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekPosition {
|
||||
pub planet: PointId,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
pub retrograde: bool,
|
||||
/// Natal house (birth time known).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
/// A planet (or the Moon) entering a sign.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekIngress {
|
||||
pub date: String,
|
||||
pub planet: PointId,
|
||||
pub sign: ZodiacSign,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
/// A new moon, quarter or full moon.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekLunation {
|
||||
pub date: String,
|
||||
pub kind: LunationKind,
|
||||
/// Where the Moon is.
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
/// A planet standing still before turning retrograde or direct.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct WeekStation {
|
||||
pub date: String,
|
||||
pub planet: PointId,
|
||||
pub retrograde: bool,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
}
|
||||
|
||||
/// One week of a natal chart.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Week {
|
||||
/// First and last day (Monday and Sunday).
|
||||
pub start: String,
|
||||
pub end: String,
|
||||
/// The planets' aspects to the natal points, by their peak inside the week.
|
||||
pub contacts: Vec<Contact>,
|
||||
pub positions: Vec<WeekPosition>,
|
||||
/// The Moon's sign at the start, and its sign changes.
|
||||
pub moon_sign: ZodiacSign,
|
||||
pub moon_ingresses: Vec<WeekIngress>,
|
||||
/// The other planets' sign changes.
|
||||
pub ingresses: Vec<WeekIngress>,
|
||||
pub lunations: Vec<WeekLunation>,
|
||||
pub stations: Vec<WeekStation>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The week from `start_jd` (the first moment of Monday) to `end_jd` (the
|
||||
/// first moment of the next Monday); dates are given at `offset_hours` from UTC.
|
||||
pub fn calculate_week(
|
||||
engine: &dyn Ephemeris,
|
||||
natal: &NatalChart,
|
||||
start_jd: f64,
|
||||
end_jd: f64,
|
||||
offset_hours: f64,
|
||||
) -> Result<Week> {
|
||||
if end_jd <= start_jd || end_jd - start_jd > 8.0 {
|
||||
return Err(EngineError::Calculation("a week is at most eight days".into()));
|
||||
}
|
||||
let span = Year {
|
||||
engine,
|
||||
natal,
|
||||
frame: frame_of(natal),
|
||||
start: start_jd,
|
||||
// The next Monday's first moment belongs to the next week.
|
||||
end: end_jd - 1.0 / 86_400.0,
|
||||
offset: offset_hours,
|
||||
cusps: cusps_of(natal),
|
||||
};
|
||||
let house = |lon: f64| span.cusps.as_ref().map(|c| house_of(lon, c));
|
||||
// The last day is the day before the next Monday.
|
||||
let last_day = span.date(end_jd - 0.5 / 24.0);
|
||||
let targets = natal_targets(natal);
|
||||
let rule = ContactRule { orb: WEEK_ORB, aspects: &ASPECTS, with_periods: false };
|
||||
|
||||
let mut contacts = Vec::new();
|
||||
let mut positions = Vec::new();
|
||||
let mut ingresses = Vec::new();
|
||||
for body in MOVING {
|
||||
let at = |jd: f64| span.position(body, jd);
|
||||
let lon_at = |jd: f64| at(jd).map(|(l, _)| l);
|
||||
let s = Samples::take(start_jd - MARGIN_DAYS, end_jd + MARGIN_DAYS, STEP, &at)?;
|
||||
let planet = PointId::from_planet(body);
|
||||
contacts.extend(span.contacts(planet, &s, &lon_at, &targets, &rule)?);
|
||||
|
||||
let (lon, speed) = at(start_jd)?;
|
||||
positions.push(WeekPosition {
|
||||
planet,
|
||||
position: ZodiacPosition::new(lon),
|
||||
retrograde: speed < 0.0,
|
||||
house: house(lon),
|
||||
});
|
||||
// Sign changes inside the week, to the sample (a few hours).
|
||||
for i in 1..s.lon.len() {
|
||||
let jd = s.jd(i);
|
||||
if jd <= start_jd || jd > end_jd {
|
||||
continue;
|
||||
}
|
||||
let sign = ZodiacSign::from_longitude(s.lon[i]);
|
||||
if sign != ZodiacSign::from_longitude(s.lon[i - 1]) {
|
||||
ingresses.push(WeekIngress { date: span.date(jd), planet, sign, house: house(s.lon[i]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
contacts.sort_by(|a, b| a.peak_jd.total_cmp(&b.peak_jd));
|
||||
|
||||
let moon_start = span.position(Body::Moon, start_jd)?.0;
|
||||
let moon_ingresses = moon_ingresses(engine, start_jd, end_jd)?
|
||||
.into_iter()
|
||||
.map(|(jd, sign)| {
|
||||
let lon = span.position(Body::Moon, jd + 1.0 / 24.0).map(|(l, _)| l).unwrap_or(sign.index() as f64 * 30.0);
|
||||
WeekIngress { date: span.date(jd), planet: PointId::Moon, sign, house: house(lon) }
|
||||
})
|
||||
.collect();
|
||||
let lunations = lunations(engine, start_jd, end_jd)?
|
||||
.into_iter()
|
||||
.map(|l| WeekLunation {
|
||||
date: span.date(l.jd_ut),
|
||||
kind: l.kind,
|
||||
position: ZodiacPosition::new(l.moon_longitude),
|
||||
house: house(l.moon_longitude),
|
||||
})
|
||||
.collect();
|
||||
let mut week_stations = Vec::new();
|
||||
for body in RETROGRADING {
|
||||
for st in stations(engine, body, start_jd, end_jd)? {
|
||||
week_stations.push(WeekStation {
|
||||
date: span.date(st.jd_ut),
|
||||
planet: PointId::from_planet(body),
|
||||
retrograde: st.retrograde,
|
||||
position: ZodiacPosition::new(st.longitude),
|
||||
});
|
||||
}
|
||||
}
|
||||
week_stations.sort_by(|a, b| a.date.cmp(&b.date));
|
||||
ingresses.sort_by(|a, b| a.date.cmp(&b.date));
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
if natal.angles.is_none() {
|
||||
warnings
|
||||
.push("Birth time unknown: no houses or angles, and the natal Moon is left out of the contacts.".into());
|
||||
}
|
||||
Ok(Week {
|
||||
start: span.date(start_jd),
|
||||
end: last_day,
|
||||
contacts,
|
||||
positions,
|
||||
moon_sign: ZodiacSign::from_longitude(moon_start),
|
||||
moon_ingresses,
|
||||
ingresses,
|
||||
lunations,
|
||||
stations: week_stations,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
@@ -217,3 +217,37 @@ fn solar_return_and_forecast() {
|
||||
assert!(f.eclipses.iter().any(|e| e.date == "2026-08-28"));
|
||||
serde_json::to_string(&f).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_week() {
|
||||
use astro_engine::calculate_week;
|
||||
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
|
||||
let natal = calculate_chart(engine(), &input).unwrap();
|
||||
// Monday 30 November 2026, 0:00 in Budapest (UTC+1), to the next Monday.
|
||||
let start = 2_461_374.5 - 1.0 / 24.0;
|
||||
assert_eq!(astro_engine::forecast::date_of(start, 1.0), "2026-11-30");
|
||||
let w = calculate_week(engine(), &natal, start, start + 7.0, 1.0).unwrap();
|
||||
assert_eq!((w.start.as_str(), w.end.as_str()), ("2026-11-30", "2026-12-06"));
|
||||
assert_eq!(w.positions.len(), 9);
|
||||
assert!(w.positions.iter().all(|p| p.house.is_some()));
|
||||
// Every contact is within orb during the week, with its peak and exact hits inside it.
|
||||
assert!(!w.contacts.is_empty());
|
||||
for c in &w.contacts {
|
||||
assert!(c.min_orb <= 1.0, "{c:?}");
|
||||
assert!(c.peak.as_str() >= w.start.as_str() && c.peak.as_str() <= w.end.as_str(), "{c:?}");
|
||||
assert!(c.exact.iter().all(|e| e.date >= w.start && e.date <= w.end), "{c:?}");
|
||||
assert_ne!(c.planet, astro_engine::chart::PointId::Moon);
|
||||
}
|
||||
// The Moon changes sign every two or three days, each time into the next sign.
|
||||
assert!((2..=4).contains(&w.moon_ingresses.len()), "{:?}", w.moon_ingresses);
|
||||
let mut sign = w.moon_sign;
|
||||
for i in &w.moon_ingresses {
|
||||
assert_eq!(i.sign.index(), (sign.index() + 1) % 12);
|
||||
sign = i.sign;
|
||||
}
|
||||
// About one main lunar phase a week.
|
||||
assert!((1..=2).contains(&w.lunations.len()), "{:?}", w.lunations);
|
||||
let json = serde_json::to_value(&w).unwrap();
|
||||
assert!(json["contacts"][0]["planet"].is_string());
|
||||
assert!(json["positions"][0]["sign"].is_string());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
-- The free weekly horoscope: the week's sky on a member's own chart (from
|
||||
-- the horoscope service), its text (an analysis of kind 'weekly', written by
|
||||
-- the summary's model), and the Monday e-mail that says it is there (on for
|
||||
-- everyone, the members of today too; it can be turned off).
|
||||
|
||||
CREATE TABLE weekly_skies (
|
||||
chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
-- The chart's data when it was calculated: new birth data, new week sky.
|
||||
chart_hash text NOT NULL,
|
||||
-- The Monday the week starts on (Hungarian time).
|
||||
week_start date NOT NULL,
|
||||
result jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (chart_id, chart_hash, week_start)
|
||||
);
|
||||
|
||||
ALTER TABLE analyses ADD COLUMN week_start date;
|
||||
|
||||
ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check;
|
||||
ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check
|
||||
CHECK (kind IN ('natal', 'synastry', 'summary', 'forecast', 'tarot', 'celebrity', 'weekly'));
|
||||
|
||||
ALTER TABLE analyses DROP CONSTRAINT analyses_target;
|
||||
ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK (
|
||||
(kind IN ('natal', 'summary', 'celebrity') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL)
|
||||
OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'tarot' AND tarot IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||
OR (kind = 'weekly' AND chart_id IS NOT NULL AND week_start IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||
);
|
||||
|
||||
-- The Monday e-mail: on unless the member turns it off. The token opens the
|
||||
-- page of every e-mail setting from an e-mail's footer (no login needed).
|
||||
ALTER TABLE users ADD COLUMN weekly_email boolean NOT NULL DEFAULT true;
|
||||
ALTER TABLE users ADD COLUMN weekly_email_sent_on date;
|
||||
ALTER TABLE users ADD COLUMN email_token uuid NOT NULL DEFAULT gen_random_uuid();
|
||||
CREATE UNIQUE INDEX users_email_token ON users (email_token);
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Where a new member came from, for the admin statistics. Set once, at
|
||||
-- sign-up, from that visit: the kind of source (Facebook, a search engine,
|
||||
-- typed in…), the referring site's address without its path, or the link's
|
||||
-- campaign tags, and the device type. Nothing is stored about visitors who
|
||||
-- do not sign up. NULL for the members who signed up before this.
|
||||
ALTER TABLE users ADD COLUMN signup_source text
|
||||
CHECK (signup_source IN ('facebook', 'instagram', 'messenger', 'tiktok', 'google', 'bing', 'search',
|
||||
'email', 'app', 'other', 'direct'));
|
||||
ALTER TABLE users ADD COLUMN signup_detail text CHECK (char_length(signup_detail) <= 200);
|
||||
ALTER TABLE users ADD COLUMN signup_device text CHECK (signup_device IN ('mobile', 'tablet', 'desktop'));
|
||||
@@ -0,0 +1,61 @@
|
||||
-- Claude (or another MCP client) connected to the admin tools through OAuth
|
||||
-- (docs/mcp.md). An admin approves the connection on the site; the client
|
||||
-- then holds a short access token and a refresh token. Every secret is
|
||||
-- stored as its SHA-256 hash, like the sessions.
|
||||
|
||||
-- The clients that registered themselves (RFC 7591), only with an allowed
|
||||
-- return address (Claude's callback, or a local one for Claude Code).
|
||||
CREATE TABLE oauth_clients (
|
||||
id text PRIMARY KEY,
|
||||
name text NOT NULL CHECK (char_length(name) <= 100),
|
||||
redirect_uris text[] NOT NULL,
|
||||
-- NULL: a public client, proven by PKCE alone.
|
||||
secret_hash bytea,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_used_at timestamptz
|
||||
);
|
||||
|
||||
-- One approved connection: who allowed which client. Revoking it ends all
|
||||
-- of its tokens.
|
||||
CREATE TABLE oauth_grants (
|
||||
id uuid PRIMARY KEY,
|
||||
client_id text NOT NULL REFERENCES oauth_clients (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
scope text NOT NULL,
|
||||
-- The MCP server the tokens are for (RFC 8707).
|
||||
resource text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_used_at timestamptz,
|
||||
revoked_at timestamptz
|
||||
);
|
||||
CREATE INDEX oauth_grants_user_idx ON oauth_grants (user_id);
|
||||
|
||||
-- The one-time code the approval sends back to the client (10 minutes).
|
||||
CREATE TABLE oauth_codes (
|
||||
code_hash bytea PRIMARY KEY,
|
||||
client_id text NOT NULL REFERENCES oauth_clients (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
redirect_uri text NOT NULL,
|
||||
code_challenge text NOT NULL,
|
||||
scope text NOT NULL,
|
||||
resource text,
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz,
|
||||
-- The connection made with it: a second use of the code revokes it.
|
||||
grant_id uuid REFERENCES oauth_grants (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- An access token (an hour) and its refresh token (30 days). A refresh makes
|
||||
-- a new pair; the old refresh token sent again revokes the whole connection.
|
||||
CREATE TABLE oauth_tokens (
|
||||
id uuid PRIMARY KEY,
|
||||
grant_id uuid NOT NULL REFERENCES oauth_grants (id) ON DELETE CASCADE,
|
||||
access_hash bytea NOT NULL UNIQUE,
|
||||
access_expires_at timestamptz NOT NULL,
|
||||
refresh_hash bytea NOT NULL UNIQUE,
|
||||
refresh_expires_at timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
refreshed_at timestamptz
|
||||
);
|
||||
CREATE INDEX oauth_tokens_grant_idx ON oauth_tokens (grant_id);
|
||||
CREATE INDEX oauth_tokens_expiry_idx ON oauth_tokens (refresh_expires_at);
|
||||
@@ -141,6 +141,58 @@ pub async fn user_by_session(pool: &PgPool, token: &str) -> Result<Option<(Uuid,
|
||||
Ok(row.map(|r| (r.session_id, r.user)))
|
||||
}
|
||||
|
||||
/// A valid OAuth access token of an MCP client (`oauth_tokens`): the
|
||||
/// connection it belongs to and what it was allowed.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OauthAccess {
|
||||
pub grant_id: Uuid,
|
||||
pub scope: String,
|
||||
pub resource: Option<String>,
|
||||
}
|
||||
|
||||
/// The connection and user of a valid (unexpired, not revoked) OAuth access
|
||||
/// token; notes the connection's last use (at most once a minute).
|
||||
pub async fn user_by_oauth_token(pool: &PgPool, token: &str) -> Result<Option<(OauthAccess, User)>, sqlx::Error> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
grant_id: Uuid,
|
||||
scope: String,
|
||||
resource: Option<String>,
|
||||
#[sqlx(flatten)]
|
||||
user: User,
|
||||
}
|
||||
let row: Option<Row> = sqlx::query_as(
|
||||
"SELECT g.id AS grant_id, g.scope, g.resource, u.id, u.email, u.email_verified_at, u.display_name, \
|
||||
u.locale, u.roles, u.created_at, u.last_login_at \
|
||||
FROM oauth_tokens t JOIN oauth_grants g ON g.id = t.grant_id JOIN users u ON u.id = g.user_id \
|
||||
WHERE t.access_hash = $1 AND t.access_expires_at > now() AND g.revoked_at IS NULL",
|
||||
)
|
||||
.bind(token_hash(token))
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
let Some(row) = row else { return Ok(None) };
|
||||
sqlx::query(
|
||||
"UPDATE oauth_grants SET last_used_at = now() \
|
||||
WHERE id = $1 AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds')",
|
||||
)
|
||||
.bind(row.grant_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(Some((OauthAccess { grant_id: row.grant_id, scope: row.scope, resource: row.resource }, row.user)))
|
||||
}
|
||||
|
||||
/// Revokes every OAuth connection of a user (log out everywhere, a new password).
|
||||
pub async fn revoke_oauth_grants<'e, E>(executor: E, user_id: Uuid) -> Result<(), sqlx::Error>
|
||||
where
|
||||
E: sqlx::PgExecutor<'e>,
|
||||
{
|
||||
sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE user_id = $1 AND revoked_at IS NULL")
|
||||
.bind(user_id)
|
||||
.execute(executor)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -182,6 +182,7 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered,
|
||||
("purchase_confirmation", _) => purchase_confirmation(lang, payload, url)?,
|
||||
("gift", _) => gift(lang, payload, url)?,
|
||||
("gift_package", _) => gift_package(lang, payload, url)?,
|
||||
("weekly_horoscope", _) => weekly_horoscope(lang, payload, url)?,
|
||||
// The forum is Hungarian only.
|
||||
("forum_reply", _) => forum_reply(payload, url)?,
|
||||
("forum_digest", _) => forum_digest(payload, url)?,
|
||||
@@ -602,6 +603,117 @@ fn name(payload: &Value, field: &str) -> Option<String> {
|
||||
(!name.is_empty()).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// Monday's notice that the weekly horoscope is there: only that, the text
|
||||
/// itself is read on the site after logging in.
|
||||
fn weekly_horoscope(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let start = field(payload, "week_start")?;
|
||||
let end = field(payload, "week_end")?;
|
||||
let range = week_range(lang, &start, &end).ok_or(TemplateError::MissingField("week_start"))?;
|
||||
let greeting = match (lang, name(payload, "display_name")) {
|
||||
(Lang::Hu, Some(n)) => format!("Szia {n}!"),
|
||||
(Lang::Hu, None) => "Szia!".to_owned(),
|
||||
(Lang::En, Some(n)) => format!("Hi {n},"),
|
||||
(Lang::En, None) => "Hi,".to_owned(),
|
||||
};
|
||||
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
||||
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
|
||||
Ok(match lang {
|
||||
Lang::Hu => Content {
|
||||
subject: "Itt a heti horoszkópod".into(),
|
||||
preheader: Some(format!("{range}: belépés után a Heti horoszkóp oldalon olvashatod.")),
|
||||
greeting,
|
||||
intro: format!(
|
||||
"Itt a heti horoszkópod {} {range} közötti hétre. Belépés után a Heti horoszkóp oldalon olvashatod.",
|
||||
// "az április 6–12.", "a november 30."
|
||||
if range.starts_with(['a', 'á', 'e', 'é', 'i', 'í', 'o', 'ó', 'ö', 'ő', 'u', 'ú', 'ü', 'ű']) {
|
||||
"az"
|
||||
} else {
|
||||
"a"
|
||||
}
|
||||
),
|
||||
quote: None,
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Megnézem",
|
||||
url,
|
||||
note: "A saját képletedből és a hét égboltjából készül.".into(),
|
||||
reason: Some(
|
||||
"Azért kapod ezt a levelet, mert van képleted a Sorsfonalakon. Ha nem kéred, az alábbi linken vagy a \
|
||||
Profil oldalon kikapcsolhatod."
|
||||
.into(),
|
||||
),
|
||||
unsubscribe: Some(("Leiratkozás, értesítések beállítása", unsubscribe_url)),
|
||||
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||
},
|
||||
Lang::En => Content {
|
||||
subject: "Your weekly horoscope is here".into(),
|
||||
preheader: Some(format!("{range}: log in to read it on the Weekly horoscope page.")),
|
||||
greeting,
|
||||
intro: format!(
|
||||
"Your weekly horoscope for {range} is here. Log in to read it on the Weekly horoscope page."
|
||||
),
|
||||
quote: None,
|
||||
points: None,
|
||||
code: None,
|
||||
button: "Read it",
|
||||
url,
|
||||
note: "It is written from your own chart and the week's sky.".into(),
|
||||
reason: Some(
|
||||
"You get this e-mail because you have a chart on Sorsfonalak. If you do not want it, turn it off with \
|
||||
the link below or on your Profile page."
|
||||
.into(),
|
||||
),
|
||||
unsubscribe: Some(("Unsubscribe, e-mail settings", unsubscribe_url)),
|
||||
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// "november 30. – december 6." or "december 7–13." (no year).
|
||||
fn week_range(lang: Lang, start: &str, end: &str) -> Option<String> {
|
||||
let parse = |iso: &str| -> Option<(usize, u32)> {
|
||||
let mut parts = iso.splitn(3, '-').skip(1);
|
||||
let m: usize = parts.next()?.parse().ok()?;
|
||||
let d: u32 = parts.next()?.get(..2)?.parse().ok()?;
|
||||
Some((m.checked_sub(1).filter(|&i| i < 12)?, d))
|
||||
};
|
||||
let ((m1, d1), (m2, d2)) = (parse(start)?, parse(end)?);
|
||||
const HU: [&str; 12] = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
const EN: [&str; 12] = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
Some(match (lang, m1 == m2) {
|
||||
(Lang::Hu, true) => format!("{} {d1}–{d2}.", HU[m1]),
|
||||
(Lang::Hu, false) => format!("{} {d1}. – {} {d2}.", HU[m1], HU[m2]),
|
||||
(Lang::En, true) => format!("{d1}–{d2} {}", EN[m1]),
|
||||
(Lang::En, false) => format!("{d1} {} – {d2} {}", EN[m1], EN[m2]),
|
||||
})
|
||||
}
|
||||
|
||||
/// The confirmation of a purchase: what was bought, and that the buyer asked
|
||||
/// for immediate delivery and so gave up the 14-day withdrawal right (the
|
||||
/// confirmation 45/2014. Korm. rendelet 29. § asks for).
|
||||
@@ -1227,6 +1339,31 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weekly_horoscope_only_says_it_is_there() {
|
||||
let payload = json!({
|
||||
"url": "https://sorsfonalak.test/heti-horoszkop",
|
||||
"display_name": "Kata",
|
||||
"week_start": "2026-11-30",
|
||||
"week_end": "2026-12-06",
|
||||
"unsubscribe_url": "https://sorsfonalak.test/ertesitesek?token=abc",
|
||||
"unsubscribe_post_url": "https://sorsfonalak.test/api/v1/public/weekly/unsubscribe?token=abc",
|
||||
});
|
||||
let hu = render("weekly_horoscope", "hu", &payload).unwrap();
|
||||
assert_eq!(hu.subject, "Itt a heti horoszkópod");
|
||||
assert!(hu.text.contains("a november 30. – december 6. közötti hétre"), "{}", hu.text);
|
||||
assert!(
|
||||
hu.text.contains("Leiratkozás, értesítések beállítása: https://sorsfonalak.test/ertesitesek?token=abc")
|
||||
);
|
||||
assert!(hu.html.contains(r#"href="https://sorsfonalak.test/heti-horoszkop""#));
|
||||
assert!(hu.unsubscribe_post_url.is_some());
|
||||
let mut same_month = payload.clone();
|
||||
same_month["week_start"] = json!("2026-12-07");
|
||||
same_month["week_end"] = json!("2026-12-13");
|
||||
let en = render("weekly_horoscope", "en", &same_month).unwrap();
|
||||
assert!(en.text.contains("for 7–13 December is here"), "{}", en.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waitlist_confirmation_has_the_leave_link() {
|
||||
let hu = render("waitlist_joined", "hu", &invitation_payload()).unwrap();
|
||||
|
||||
@@ -48,6 +48,11 @@ impl HoroscopeClient {
|
||||
self.post("/v1/forecast", request).await
|
||||
}
|
||||
|
||||
/// `POST /v1/week`: one week of a natal chart (the weekly horoscope's sky).
|
||||
pub async fn week(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||
self.post("/v1/week", request).await
|
||||
}
|
||||
|
||||
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
|
||||
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
|
||||
self.get("/v1/sky", &[]).await
|
||||
|
||||
@@ -23,6 +23,16 @@
|
||||
header_up X-Real-IP {client_ip}
|
||||
}
|
||||
}
|
||||
# The admin tools for Claude (docs/mcp.md) and their OAuth metadata; the
|
||||
# login, the approval and the tokens are the frontend's and the backend's.
|
||||
handle /mcp* {
|
||||
reverse_proxy mcp:8084 {
|
||||
header_up X-Real-IP {client_ip}
|
||||
}
|
||||
}
|
||||
handle /.well-known/oauth-protected-resource* {
|
||||
reverse_proxy mcp:8084
|
||||
}
|
||||
handle {
|
||||
reverse_proxy frontend:3000 {
|
||||
# The address the backend trusts (rate limits, share visits); it
|
||||
|
||||
+3
-2
@@ -9,11 +9,11 @@ A runner egyszerre egy feladatot futtat; ha a main is buildelne, minden kitett c
|
||||
|
||||
A lépések:
|
||||
|
||||
Csak az épül és indul újra, ami az előző élesítés óta változott (`ci/changed-services.sh`: az előző élesítés `v*` taghez képest nézi a változott fájlokat). A frontend a `services/frontend` mappától függ; a backend, a worker és a fórum a saját mappájától és a közös Rust-csomagoktól (`crates/`, `Cargo.toml`, `Cargo.lock`); a horoscope-api ezektől és a `scripts/fetch-deps.sh`-tól. Ha nincs előző tag, vagy kétséges a helyzet, minden épül.
|
||||
Csak az épül és indul újra, ami az előző élesítés óta változott (`ci/changed-services.sh`: az előző élesítés `v*` taghez képest nézi a változott fájlokat). A frontend a `services/frontend` mappától függ; a backend, a worker, a fórum és az MCP-szerver a saját mappájától és a közös Rust-csomagoktól (`crates/`, `Cargo.toml`, `Cargo.lock`); a horoscope-api ezektől és a `scripts/fetch-deps.sh`-tól. Ha nincs előző tag, vagy kétséges a helyzet, minden épül.
|
||||
|
||||
1. **test**: `cargo test` a Rust-szolgáltatásokra, egy Postgres szolgáltatás-konténerrel. Kimarad, ha egyik Rust-szolgáltatás sem változott.
|
||||
2. **build** (csak prod): megépíti a változott image-eket, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-<szolgáltatás>` címre. A frontend buildje a TypeScript-típusokat is ellenőrzi, és megkapja a verzióját (`APP_VERSION`, a commit): ebből lesz a Next `deploymentId`-je és a `/api/version` válasza.
|
||||
3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, a szerveren lévő `.env`-be csak a megépült szolgáltatások címkéjét írja be (`TAG_BACKEND`, `TAG_FRONTEND`, `TAG_FORUM`, `TAG_WORKER`, `TAG_HOROSCOPE_API`; ahol nincs ilyen, a régi `TAG` érvényes), majd `docker compose pull && up -d`: csak a változott konténerek indulnak újra. Az adatbázis-migrációk a backend (és a fórum) indulásakor futnak le.
|
||||
3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, a szerveren lévő `.env`-be csak a megépült szolgáltatások címkéjét írja be (`TAG_BACKEND`, `TAG_FRONTEND`, `TAG_FORUM`, `TAG_MCP`, `TAG_WORKER`, `TAG_HOROSCOPE_API`; ahol nincs ilyen, a régi `TAG` érvényes), majd `docker compose pull && up -d`: csak a változott konténerek indulnak újra. Az adatbázis-migrációk a backend (és a fórum) indulásakor futnak le.
|
||||
4. **release** (csak prod, a deploy után): létrehoz egy `v<év.hónap.nap>-<hash>` taget és Gitea-release-t az előző release óta bekerült commitok listájával (repó → Releases). A következő élesítés ehhez a taghez méri a változást.
|
||||
|
||||
Új frontend-verziónál a nyitva hagyott oldalak maguk veszik észre (`VersionWatcher`, 5 percenként és amikor a fül előtérbe kerül): ha a látogató nem csinál semmit és nincs beírt szöveg, újratöltődik, különben egy „Frissült az oldal” sáv kínálja fel a frissítést. Linkre kattintva a Next magától teljes újratöltést csinál.
|
||||
@@ -109,4 +109,5 @@ A híres emberek fotóit a backend S3-kompatibilis tárolóba teszi, fotónként
|
||||
- Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. Az otthoni TrueNAS naponta lehúzza (Rsync Task, Pull, SSH) a `nasbackup` felhasználóval, aki csak ezt a mappát olvashatja (`authorized_keys`: `command="/usr/bin/rrsync -ro /opt/sorsfonalak/backups",restrict`); a NAS-on a régi mentések is megmaradnak.
|
||||
- Vásárlási értesítő: a `worker` `notify` feladata minden kifizetett vásárlásról egyszer szól Telegramon („🛒 Vásárlás: Páros csomag, 6 000 Ft”, a vevő adatai nélkül), a számlázástól függetlenül. Beállítás: `TELEGRAM_BOT_TOKEN` a `.env.secrets`-ben, `TELEGRAM_CHAT_ID` a `.env`-ben; ha bármelyik hiányzik, nincs értesítés.
|
||||
- Monitorozás: a `beszel-agent` (Beszel, CPU/memória/lemez/konténerek) a NAS-on futó Beszel hubnak ad adatot, Tailscale-en át. Csak a szerver Tailscale-címén figyel (`100.69.226.118:45876`), az internet felé nem nyit portot; a hub kapcsolódik hozzá. Bekapcsolás a `.env`-ben: `COMPOSE_PROFILES=monitoring` és `BESZEL_KEY=<a hub nyilvános kulcsa>`, utána `docker compose up -d beszel-agent`. A hubban a rendszer címe `100.69.226.118`, port `45876`.
|
||||
- MCP-szerver (`mcp`, `docs/mcp.md`): az admin eszközök Claude-hoz, a `https://sorsfonalak.hu/mcp` címen (a Caddy a `/mcp` és a `/.well-known/oauth-protected-resource` útvonalat viszi hozzá). Nem kell hozzá DNS-bejegyzés és titok; adatbázist nem használ, minden hívása a frontend `/api/v1` proxyján át a backendhez megy. A kapcsolt alkalmazások: Admin → Claude.
|
||||
- Visszatöltés: `gunzip -c backups/sorsfonalak-<dátum>.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak`
|
||||
|
||||
@@ -113,6 +113,8 @@ services:
|
||||
# Cloudflare Turnstile on the e-mail sign-up and reset forms (the
|
||||
# TURNSTILE_SECRET_KEY is in .env.secrets). Without both: no check.
|
||||
TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-}
|
||||
# The MCP server's address, the audience of its tokens (docs/mcp.md).
|
||||
MCP_RESOURCE_URL: https://${DOMAIN}/mcp
|
||||
# The log also goes to the logs volume, one file a day, kept 30 days
|
||||
# (deploy/README.md: Logs).
|
||||
LOG_DIR: /logs
|
||||
@@ -137,8 +139,9 @@ services:
|
||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG_WORKER:-${TAG:-latest}}
|
||||
environment:
|
||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary.
|
||||
WORKER_TASKS: email,cleanup,invoices,notify,forum
|
||||
# forum: the forum's digests, daily sky thread, listener e-mails, weekly summary;
|
||||
# weekly: Monday's e-mail about the weekly horoscope.
|
||||
WORKER_TASKS: email,cleanup,invoices,notify,forum,weekly
|
||||
# The sky of the forum's daily thread.
|
||||
BACKEND_URL: http://backend:8081
|
||||
# Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets.
|
||||
@@ -237,6 +240,24 @@ services:
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
# The admin tools for Claude (docs/mcp.md): Claude connects to
|
||||
# https://${DOMAIN}/mcp (Caddy), an admin approves it on the site, and every
|
||||
# tool calls the site's API through the frontend with that admin's token.
|
||||
mcp:
|
||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-mcp:${TAG_MCP:-${TAG:-latest}}
|
||||
environment:
|
||||
API_URL: http://frontend:3000/api/v1
|
||||
PUBLIC_BASE_URL: https://${DOMAIN}
|
||||
MCP_PUBLIC_URL: https://${DOMAIN}/mcp
|
||||
LOG_DIR: /logs
|
||||
depends_on:
|
||||
- frontend
|
||||
read_only: true
|
||||
volumes:
|
||||
- logs:/logs
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
# Beszel agent: CPU, memory, disk, network and per-container stats for the
|
||||
# Beszel hub on the home NAS. Off unless COMPOSE_PROFILES=monitoring and
|
||||
# BESZEL_KEY (the hub's public key) are in .env. It listens only on the
|
||||
@@ -256,7 +277,7 @@ services:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
# Backend, worker and forum logs (backend.YYYY-MM-DD.log, worker…, worker-ai…, forum…).
|
||||
# Backend, worker, forum and MCP logs (backend.YYYY-MM-DD.log, worker…, worker-ai…, forum…, mcp…).
|
||||
logs:
|
||||
caddy-data:
|
||||
caddy-config:
|
||||
|
||||
@@ -75,6 +75,8 @@ services:
|
||||
S3_BUCKET: ${S3_BUCKET:-}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREATE_BUCKET: ${S3_CREATE_BUCKET:-false}
|
||||
# The MCP server's address, the audience of its tokens (docs/mcp.md).
|
||||
MCP_RESOURCE_URL: ${MCP_RESOURCE_URL:-http://localhost:8084/mcp}
|
||||
# STRIPE_SECRET_KEY / STRIPE_WEBHOOK_SECRET (test keys; docs/fizetes.md).
|
||||
# With them Stripe replaces the stand-in payment.
|
||||
env_file:
|
||||
@@ -165,5 +167,23 @@ services:
|
||||
- /tmp
|
||||
restart: unless-stopped
|
||||
|
||||
# The admin tools for Claude (docs/mcp.md): connect Claude Code to
|
||||
# http://localhost:8084/mcp; the login and approval happen on the frontend.
|
||||
mcp:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: services/mcp/Dockerfile
|
||||
image: sorsfonalak/mcp:latest
|
||||
ports:
|
||||
- "8084:8084"
|
||||
environment:
|
||||
API_URL: http://frontend:3000/api/v1
|
||||
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001}
|
||||
MCP_PUBLIC_URL: ${MCP_RESOURCE_URL:-http://localhost:8084/mcp}
|
||||
depends_on:
|
||||
- frontend
|
||||
read_only: true
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Heti horoszkóp
|
||||
|
||||
Ingyenes, személyes heti szöveg a tag saját képletéből és a hét égboltjából. Hétfőtől vasárnapig tart, magyar idő szerint.
|
||||
|
||||
## Az oldal
|
||||
|
||||
- **Saját oldala van:** `/heti-horoszkop`, a menüben a „Képletem” után. A saját képlet oldalán, az összefoglaló alatt egy kis kártya visz ide.
|
||||
- **Egy hónap egyszerre:** a hetek a hétfőjük hónapjához tartoznak, legelöl a legújabb. A „Korábbi hónap” és „Újabb hónap” gomb lapoz (`?honap=2026-10`); csak olyan hónapra visz, amelyben van szöveg, és előre csak az aktuális hónapig.
|
||||
- **Készül:** az aktuális hónapban az oldal egyszer kéri a heti szöveget (`POST /v1/weekly`), utána csak olvassa (`GET /v1/analyses/{id}`), amíg a worker megírja (kb. 20 másodperc); közben a hét kártyáján a várakozó animáció látszik, a hónap többi hete alatta. Ha nem sikerült, az oldal nem próbálja újra magától (minden próba fizetős AI-hívás); újratöltéskor egyszer újra megírja.
|
||||
- **Kijelentkezve:** nyitóoldal belépés és regisztráció gombbal, és egy valódi példa heti horoszkóppal a példaelemzés kitalált képletéhez (`src/content/pelda-heti.json`, a helyi rendszerrel és ugyanazzal a modellel generálva). Előnézeti kép: `/kep/heti-horoszkop.png`.
|
||||
- **Csak a megnézett hetek:** régebbi hétnek csak akkor van szövege, ha a tag azon a héten megnyitotta az oldalt. Visszamenőleg nem készül.
|
||||
- API: `GET /v1/weekly/history?month=2026-11` → `{month, current_month, this_week, weeks: [{week_start, week_end, analysis}], older, newer, email}`. Minden saját képlet hetei számítanak, mert a születési adat közben változhatott.
|
||||
|
||||
## Hogyan készül
|
||||
|
||||
- **A hét égboltja:** a horoscope-api `POST /v1/week` végpontja (`astro_engine::week`). Tartalma:
|
||||
- a bolygók (a Naptól a Plútóig) fényszögei a születési pontokhoz, 1°-os hatásfokkal, a pontos nappal;
|
||||
- hol állnak a bolygók a hét elején (jegy, születési ház, retrográd);
|
||||
- a Hold jegyváltásai, a fő holdfázisok, a bolygók irányváltásai és jegyváltásai.
|
||||
|
||||
A Hold fényszögei nincsenek benne, mert egy hét alatt minden pontot érint. A backend képletenként, születési adatonként és hetenként egyszer kéri le, és a `weekly_skies` táblába menti.
|
||||
- **A szöveg:** egy `weekly` típusú elemzés (`analyses.week_start` a hétfő). Az összefoglaló olcsó modellje írja (az admin modellbeállításainál a „Tömör összefoglaló és heti horoszkóp”). Formája: cím, és 3 rövid bekezdés (150–220 szó): a hét fő témája, a kulcsnapok a hét napjainak nevével, és egy javaslat. Az admin promptszerkesztőben nem szerkeszthető.
|
||||
- **Csak aki megnézi:** a szöveg akkor készül el, amikor a tag a héten először megnyitja a Heti horoszkóp oldalt (`POST /v1/weekly`). Így az AI-költség csak azokra jut, akik olvassák (egy szöveg kb. 1–1,5 Ft).
|
||||
- **Értékelés:** a szöveg alatt ugyanaz a csillagos értékelés van, mint az elemzéseknél. Admin újraírathatja.
|
||||
|
||||
## Hétfői levél
|
||||
|
||||
- **Kinek:** minden tagnak, akinek van saját képlete, és nem kapcsolta ki (`users.weekly_email`, alapból bekapcsolva, a meglévő tagoknál is).
|
||||
- **Mikor:** hétfőn 7 órától, hetente egyszer (`users.weekly_email_sent_on`). A worker `weekly` feladata 10 percenként nézi. Ha a worker egész hétfőn állt, az a hét kimarad.
|
||||
- **Mi van benne:** csak annyi, hogy itt a heti horoszkóp, és egy gomb a Heti horoszkóp oldalra. A szöveget csak belépés után lehet elolvasni.
|
||||
- **Kikapcsolás:**
|
||||
- a Heti horoszkóp oldal alján lévő kapcsolóval;
|
||||
- a Profil oldal „Levelek” részében;
|
||||
- a levél alján lévő linkkel (`/ertesitesek?token=<users.email_token>`, belépés nélkül);
|
||||
- a levelező saját „Leiratkozás” gombjával (RFC 8058, `POST /v1/public/weekly/unsubscribe`), ez csak ezt a levelet kapcsolja ki.
|
||||
|
||||
Az oldalon bekapcsolva az első levél a következő hétfőn jön, mert a heti szöveget a tag már látja.
|
||||
|
||||
## Értesítések oldal
|
||||
|
||||
Az `/ertesitesek?token=…` oldalon belépés nélkül beállítható minden olyan levél, amely nem egy lépéshez tartozik:
|
||||
|
||||
- a heti horoszkóp hétfői levele;
|
||||
- fórumtagoknál a fórum levelei, ugyanazok a beállítások, mint a fórumprofilnál (válaszok, követett szálak, privát üzenetek, említések, kísérő értesítések, heti összefoglaló).
|
||||
|
||||
API: `GET` és `PUT /v1/public/notifications?token=`. A jelszóval, a vásárlással és a számlával kapcsolatos levelek mindig mennek. A „Mindenről leiratkozom” gomb mindent kikapcsol.
|
||||
|
||||
## Később
|
||||
|
||||
Ha a tagok rászoknak, előfizetéses lesz (havi és éves). Ehhez a `POST /v1/weekly` kap egy jogosultság-ellenőrzést; az oldal, a régi hetek és a hétfői levél maradhat.
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# MCP: az admin eszközök Claude-ból
|
||||
|
||||
Az `mcp` szolgáltatás egy MCP-szerver: Claude-ból (claude.ai, Claude Desktop, Claude Code) lehet vele az admin dolgokat lekérdezni és a napi teendőket elintézni. Például: „Hány új tag jött a héten, és honnan?”, „Mi van a nyitott visszajelzések között?”, „Csinálj 5 promókódot a Páros csomaghoz a novemberi kampányhoz.”
|
||||
|
||||
## Összekötés
|
||||
|
||||
- **claude.ai / Claude Desktop:** Beállítások → Összekötők → *Egyéni összekötő hozzáadása* → cím: `https://sorsfonalak.hu/mcp`. A *Csatlakozás* gomb után Claude a Sorsfonalak oldalára visz.
|
||||
- **Claude Code:** `claude mcp add --transport http sorsfonalak https://sorsfonalak.hu/mcp`, utána a `/mcp` paranccsal lehet belépni.
|
||||
- **Az oldalon:** ha nem vagy belépve, belépés (Google, Apple), utána az `/oauth/engedely` oldal mutatja, mit kér az alkalmazás. **Engedélyezem** → vissza Claude-hoz. Csak admin fiók engedélyezhet.
|
||||
- **Helyben:** `docker compose up -d backend frontend mcp`, a cím `http://localhost:8084/mcp`; a belépés és az engedélyezés a `http://localhost:3001` oldalon van.
|
||||
|
||||
## Mit tehet
|
||||
|
||||
**Olvasás:**
|
||||
- statisztika (`get_stats`);
|
||||
- tagok keresése;
|
||||
- visszajelzések és összesítésük;
|
||||
- értékelések és az értékelt szöveg;
|
||||
- hibanapló, háttérfeladatok;
|
||||
- csomagok, promókódok, meghívók, ajándékok;
|
||||
- hírességek, promptok, modellek.
|
||||
|
||||
**Napi teendők** (Claude minden ilyen lépés előtt rákérdez):
|
||||
- promókód készítése és visszavonása;
|
||||
- visszajelzés állapota, megjegyzése és válasza;
|
||||
- értékelések átnézve;
|
||||
- háttérfeladatok újraindítása, hibák törlése;
|
||||
- meghívó küldése és újraküldése (valódi e-mail megy ki);
|
||||
- elemzés és válasz újraírása (AI-költség).
|
||||
|
||||
**Fórummoderálás:**
|
||||
- bejelentések és lezárásuk;
|
||||
- csatlakozási kérések elbírálása;
|
||||
- moderálási napló, egy szál elolvasása;
|
||||
- kitiltás és feloldás.
|
||||
|
||||
**Amit nem tehet** (csak az admin oldalon):
|
||||
- szerepkör, kredit és csomag adása;
|
||||
- promptok és modellek mentése;
|
||||
- hírességek szerkesztése;
|
||||
- ajándék-visszatérítés, meghívó visszavonása.
|
||||
|
||||
A fórumban tagként írni, reagálni vagy bejelenteni nem tud.
|
||||
|
||||
## A tagok adatai
|
||||
|
||||
Az eszközök válaszaiban:
|
||||
- **E-mail-címek:** maszkolva mennek, a szabad szövegben is: `an***@gmail.com`.
|
||||
- **Nevek:** a tagok nevei `[rejtve]` alakban mennek.
|
||||
- **Ami marad:** a fórum-becenevek (álnevek), a hírességek és a csomagok neve.
|
||||
|
||||
Keresni teljes e-mail-címmel is lehet (a cím Claude-tól megy a szerverhez), és meghívót is a megadott címre küld; a válaszban ezek is maszkolva jönnek vissza. A maszkolás az MCP-szerverben van (`services/mcp/src/mask.rs`), ezért az adatvédelmi tájékoztatót nem kellett bővíteni.
|
||||
|
||||
## Hogyan működik
|
||||
|
||||
```
|
||||
Claude ─HTTPS─> Cloudflare ─> Caddy
|
||||
/mcp, /.well-known/oauth-protected-resource* ─> mcp:8084
|
||||
minden más ─> frontend:3000
|
||||
/api/v1/* (proxy) ─> backend:8081, /api/v1/forum/* ─> forum:8083
|
||||
/oauth/engedely (az engedélyezés oldala)
|
||||
/.well-known/oauth-authorization-server (─> /api/v1/oauth/metadata)
|
||||
mcp ─> http://frontend:3000/api/v1/… (a felhasználó tokenjével)
|
||||
```
|
||||
|
||||
**Az OAuth 2.1 lépései** (a backend az authorization server, az MCP-szerver a resource server):
|
||||
1. **Token nélkül:** a `/mcp` 401-et ad, és a `WWW-Authenticate` fejlécben megmondja, hol a metaadat (`/.well-known/oauth-protected-resource/mcp`, RFC 9728). Ez az oldalt nevezi meg authorization servernek.
|
||||
2. **Metaadat** (`/.well-known/oauth-authorization-server`, RFC 8414): az engedélyezés oldala, a token-, a regisztrációs és a visszavonási végpont. Csak `code` és PKCE `S256`.
|
||||
3. **Kliensregisztráció** (`POST /api/v1/oauth/register`, RFC 7591): csak engedélyezett visszatérési címmel. Alapból Claude-é (`https://claude.ai/api/mcp/auth_callback`, `https://claude.com/api/mcp/auth_callback`), illetve a Claude Code-hoz `http://localhost:*` és `http://127.0.0.1:*`. A lista: `OAUTH_REDIRECT_URIS` a backendben.
|
||||
4. **Engedélyezés:** az `/oauth/engedely` oldal a backenddel ellenőrizteti a kérést, admin belépés után az **Engedélyezem** egy 10 percig érvényes, egyszer használható kódot ad. Ezt a backend csak munkamenettel adja ki, MCP-tokennel nem.
|
||||
5. **Token** (`POST /api/v1/oauth/token`): hozzáférési token (1 óra) és frissítőtoken (30 nap).
|
||||
- A frissítőtoken minden használatkor cserélődik. Ha egy régit újra beküldenek, az egész kapcsolat visszavonódik; egy kétszer beküldött kód is ezzel jár.
|
||||
- A token az MCP-szerverhez kötött (`resource`, RFC 8707: `MCP_RESOURCE_URL`).
|
||||
6. **Hívások:**
|
||||
- Az MCP-szerver a `GET /api/v1/oauth/whoami` végponttal ellenőrzi a tokent (percenként egyszer, gyorsítótárból).
|
||||
- Az eszközök a tokennel hívják az admin API-t, ugyanúgy, mint az admin oldalak.
|
||||
- A backend minden hívásnál ellenőriz: a token csak admin végpontot hívhat, írni csak a napi teendőket (`MCP_WRITES` a `services/backend/src/auth.rs`-ben). Admin szerep nélkül a token semmit nem ér.
|
||||
- A fórum csak a moderátori végpontokon fogadja el.
|
||||
|
||||
**Táblák** (`0049_mcp_oauth.sql`), mindegyik titok SHA-256 hash-ként tárolva:
|
||||
- `oauth_clients`: a regisztrált kliensek;
|
||||
- `oauth_grants`: egy-egy engedélyezett kapcsolat;
|
||||
- `oauth_codes`: az egyszer használható kódok;
|
||||
- `oauth_tokens`: a hozzáférési és frissítőtokenek.
|
||||
|
||||
A worker `cleanup` feladata törli a lejárt kódokat és tokeneket, a 30 napja visszavont vagy token nélküli kapcsolatokat, és a 30 napja kapcsolat nélküli klienseket.
|
||||
|
||||
## Visszavonás
|
||||
|
||||
- **Admin → Claude:** a kapcsolt alkalmazások listája. A **Visszavonás** után az alkalmazás azonnal elveszíti a hozzáférést.
|
||||
- **Kijelentkezés mindenhonnan**, jelszócsere, jelszó-visszaállítás: a felhasználó minden kapcsolata megszűnik.
|
||||
- **Claude-ban:** az összekötő eltávolítása (ha a kliens hívja a visszavonási végpontot, itt is megszűnik).
|
||||
|
||||
## Beállítások
|
||||
|
||||
| Hol | Változó | Érték |
|
||||
|---|---|---|
|
||||
| backend | `MCP_RESOURCE_URL` | az MCP-szerver címe (élesben `https://sorsfonalak.hu/mcp`) |
|
||||
| backend | `OAUTH_REDIRECT_URIS` | engedélyezett visszatérési címek; a `*` a végén bármely port és útvonal (üres: az alapértelmezés) |
|
||||
| mcp | `API_URL` | az oldal API-ja (`http://frontend:3000/api/v1`) |
|
||||
| mcp | `PUBLIC_BASE_URL` | az oldal, az authorization server |
|
||||
| mcp | `MCP_PUBLIC_URL` | a saját címe, ahogy a kliens látja |
|
||||
|
||||
**Ami nem kell:** DNS-bejegyzés (a `/mcp` a fő domainen van), titok és Cloudflare-beállítás. Ha Claude kapcsolódási hibát jelez, a Cloudflare Security → Events oldalán érdemes megnézni, nem állította-e meg valami a kérést (a Bot Fight Mode maradjon kikapcsolva).
|
||||
@@ -0,0 +1,51 @@
|
||||
# Admin statisztika
|
||||
|
||||
Az `/admin/statisztika` oldal (az admin menüben az első) azt mutatja, hogyan megy az oldal: hányan regisztrálnak, hányan készítenek képletet, vásárolnak, olvassák a heti horoszkópot, és honnan jönnek a tagok. Csak az admin látja.
|
||||
|
||||
## Mit mutat
|
||||
|
||||
- **Időszak:** 7, 30 vagy 90 nap, vagy minden az első tag óta. A napok magyar idő szerint számítanak.
|
||||
- **Eddig összesen:** tagok, saját képletek, fizető vásárlók, bevétel, a hétfői levél feliratkozói és a fórumtagok.
|
||||
- **Számkártyák:**
|
||||
- új tagok, saját képletek (az első saját képlet napja), vásárlás (bevétel, fizetések, vásárlók), elemzések és kérdések, heti horoszkóp olvasói, fórum-hozzászólások, AI-költség;
|
||||
- mellettük az előző, ugyanilyen hosszú időszakhoz képesti változás.
|
||||
- **Napról napra:** egy-egy kis oszlopdiagram mérőszámonként, ugyanazokra a napokra. Egy napra mutatva (telefonon koppintva) fölötte látszanak a nap számai; alatta a napi táblázat.
|
||||
- **Regisztrációtól a fizetésig:** az időszakban regisztráltak közül hányan erősítették meg a címüket, készítették el a képletüket, kezdték el a fizetést, és fizettek. Mellette: hányan kértek elemzést vagy kérdést, és hányan olvasták a heti horoszkópot.
|
||||
- **Honnan jöttek:** az időszakban regisztráltak forrás szerint (tag, saját képlet, fizetett), eszköz és regisztrációs mód szerint, és a hivatkozó oldalak és kampányok listája.
|
||||
- **Vásárlások csomagonként**, **Heti horoszkóp hetente** (olvasók és kiküldött levelek), **Amit az AI írt** (fajtánként elkészült, sikertelen, költség).
|
||||
|
||||
**Kik számítanak:**
|
||||
- A tagok számában az adminok nem szerepelnek.
|
||||
- A bevétel az éles Stripe-fizetések összege (a tesztfizetések nélkül).
|
||||
- Az AI-költség mindenkié, az adminoké is.
|
||||
|
||||
API: `GET /v1/admin/stats?days=30` (0: minden). Néhány lekérdezés, csak amikor az admin megnyitja az oldalt.
|
||||
|
||||
## Honnan jött a tag
|
||||
|
||||
Regisztrációkor (jelszavas, Google, Apple) a `users` tábla három mezőt kap. A korábbi tagoknál ezek üresek, az oldalon „Nem ismert”.
|
||||
|
||||
| Mező | Tartalma |
|
||||
|---|---|
|
||||
| `signup_source` | `facebook`, `instagram`, `messenger`, `tiktok`, `google`, `bing`, `search` (más kereső), `email`, `app` (más alkalmazás), `other` (más oldal), `direct` |
|
||||
| `signup_detail` | a hivatkozó oldal címe az elérési útja nélkül (`m.facebook.com`), vagy a link kampánycímkéi (`utm_source=fb&utm_campaign=heti`) |
|
||||
| `signup_device` | `mobile`, `tablet` vagy `desktop` |
|
||||
|
||||
**Honnan tudjuk:**
|
||||
- **A böngészőben:** az oldal az első betöltéskor megjegyzi a hivatkozó oldal címét, az `utm_*` címkéket, az `fbclid`/`gclid`/`ttclid` meglétét és a `forras` paramétert, csak a memóriában (`src/lib/arrival.ts`), és a regisztráció elküldi (`came_from`). A böngészőben semmi nem tárolódik.
|
||||
- **A backendben:** a besorolás a `services/backend/src/signup_source.rs`-ben van. Elsőbbségi sorrend:
|
||||
1. kampánycímke;
|
||||
2. egy alkalmazás beépített böngészője (a böngésző neve alapján);
|
||||
3. a `forras` paraméter;
|
||||
4. a kattintásazonosító;
|
||||
5. a hivatkozó oldal;
|
||||
6. különben `direct`.
|
||||
- **Facebook beépített böngészője:** a belépőoldal Chrome-ba vivő linkje `?forras=facebook`-ot kap, így az ott regisztrálók is Facebookosnak számítanak.
|
||||
- **Megosztott link, meghívó:** a statisztikában ez a forrás, ha volt (`referrals`, `invitations`, illetve egy összevetés-meghívó, amely a fiók előtt készült).
|
||||
|
||||
**Kampánycímke:** a saját Facebook-bejegyzések linkjére írható, például `https://sorsfonalak.hu/heti-horoszkop?utm_source=facebook&utm_campaign=heti`. A „Hivatkozó oldalak és kampányok” listában külön sorban látszik.
|
||||
|
||||
**Adatvédelem:**
|
||||
- Akik nem regisztrálnak, azokról semmit nem tárolunk; őket a Cloudflare Web Analytics mutatja.
|
||||
- A tájékoztatóban (adatkezelési táblázat és a 8. pont) szerepel, jogos érdek alapján.
|
||||
- Az adatexportban `signup_came_from` néven van benne, és a fiókkal együtt törlődik.
|
||||
@@ -20,6 +20,7 @@ service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
deunicode.workspace = true
|
||||
argon2.workspace = true
|
||||
base64.workspace = true
|
||||
password-hash = { version = "0.5", features = ["getrandom"] }
|
||||
axum.workspace = true
|
||||
axum-extra.workspace = true
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
//! HttpOnly cookie (`sf_session`) and in the login response body (for
|
||||
//! non-browser clients, sent back as `Authorization: Bearer <token>`); the
|
||||
//! database keeps only its SHA-256 hash, so sessions can be revoked.
|
||||
//!
|
||||
//! The admin endpoints also accept the OAuth access token of an MCP client
|
||||
//! that an admin connected (docs/mcp.md): for reading, and for the few
|
||||
//! writes in [`MCP_WRITES`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -12,7 +16,8 @@ use std::time::{Duration, Instant};
|
||||
use argon2::Argon2;
|
||||
use argon2::password_hash::rand_core::OsRng;
|
||||
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::extract::{FromRequestParts, MatchedPath};
|
||||
use axum::http::Method;
|
||||
use axum::http::header::{AUTHORIZATION, USER_AGENT};
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
|
||||
@@ -36,7 +41,11 @@ pub const MAX_PASSWORD_LEN: usize = 256;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthUser {
|
||||
pub user: User,
|
||||
/// The session; with an MCP client's token, the id of its connection.
|
||||
pub session_id: Uuid,
|
||||
/// Set when an MCP client's OAuth token was sent instead of a session
|
||||
/// (only the admin guards accept one).
|
||||
pub oauth: Option<db::OauthAccess>,
|
||||
}
|
||||
|
||||
impl AuthUser {
|
||||
@@ -68,19 +77,72 @@ impl FromRequestParts<Arc<AppState>> for AuthUser {
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let token = session_token(parts).ok_or(ApiError::Unauthorized)?;
|
||||
let (session_id, user) = db::user_by_session(&state.db, &token).await?.ok_or(ApiError::Unauthorized)?;
|
||||
Ok(AuthUser { user, session_id })
|
||||
Ok(AuthUser { user, session_id, oauth: None })
|
||||
}
|
||||
}
|
||||
|
||||
/// Guard: a logged-in user with the admin role (401 / 403 otherwise).
|
||||
/// The admin writes an MCP client's token may make (method, route), besides
|
||||
/// reading: the daily tasks of docs/mcp.md. Every other write needs a session.
|
||||
pub const MCP_WRITES: [(Method, &str); 11] = [
|
||||
(Method::POST, "/v1/admin/promo-codes"),
|
||||
(Method::POST, "/v1/admin/promo-codes/{id}/revoke"),
|
||||
(Method::PATCH, "/v1/admin/feedback/{id}"),
|
||||
(Method::POST, "/v1/admin/ratings/reviewed"),
|
||||
(Method::POST, "/v1/admin/jobs/restart"),
|
||||
(Method::DELETE, "/v1/admin/errors"),
|
||||
(Method::DELETE, "/v1/admin/errors/{id}"),
|
||||
(Method::POST, "/v1/admin/invitations"),
|
||||
(Method::POST, "/v1/admin/invitations/{id}/resend"),
|
||||
(Method::POST, "/v1/admin/analyses/{id}/regenerate"),
|
||||
(Method::POST, "/v1/admin/questions/{id}/regenerate"),
|
||||
];
|
||||
|
||||
/// The user of an MCP client's OAuth access token (`Authorization: Bearer`).
|
||||
pub async fn oauth_user(parts: &Parts, state: &AppState) -> Result<Option<AuthUser>, ApiError> {
|
||||
let Some(token) = parts
|
||||
.headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let found = db::user_by_oauth_token(&state.db, token).await?;
|
||||
Ok(found.map(|(access, user)| AuthUser { user, session_id: access.grant_id, oauth: Some(access) }))
|
||||
}
|
||||
|
||||
/// A session, or else an MCP client's token.
|
||||
async fn session_or_token(parts: &mut Parts, state: &Arc<AppState>) -> Result<AuthUser, ApiError> {
|
||||
match AuthUser::from_request_parts(parts, state).await {
|
||||
Err(ApiError::Unauthorized) => oauth_user(parts, state).await?.ok_or(ApiError::Unauthorized),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// With an MCP client's token: reading, and the writes of [`MCP_WRITES`].
|
||||
fn token_may(user: &AuthUser, parts: &Parts) -> Result<(), ApiError> {
|
||||
if user.oauth.is_none() || parts.method == Method::GET || parts.method == Method::HEAD {
|
||||
return Ok(());
|
||||
}
|
||||
let route = parts.extensions.get::<MatchedPath>().map(MatchedPath::as_str);
|
||||
if MCP_WRITES.iter().any(|(method, path)| *method == parts.method && Some(*path) == route) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(ApiError::Forbidden("Ezt Claude-ból nem lehet, csak az admin oldalon.".into()))
|
||||
}
|
||||
|
||||
/// Guard: a logged-in user with the admin role (401 / 403 otherwise), or an
|
||||
/// MCP client an admin connected.
|
||||
pub struct AdminUser(pub AuthUser);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for AdminUser {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
let user = session_or_token(parts, state).await?;
|
||||
user.require(Role::Admin)?;
|
||||
token_may(&user, parts)?;
|
||||
Ok(AdminUser(user))
|
||||
}
|
||||
}
|
||||
@@ -98,11 +160,12 @@ impl FromRequestParts<Arc<AppState>> for CelebrityEditor {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = AuthUser::from_request_parts(parts, state).await?;
|
||||
if user.user.has_role(Role::Creator) {
|
||||
let user = session_or_token(parts, state).await?;
|
||||
if user.oauth.is_none() && user.user.has_role(Role::Creator) {
|
||||
return Ok(CelebrityEditor(user));
|
||||
}
|
||||
user.require(Role::Admin)?;
|
||||
token_may(&user, parts)?;
|
||||
Ok(CelebrityEditor(user))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,8 +117,23 @@ pub struct Config {
|
||||
/// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it
|
||||
/// is missing (development; in production it is made in the console).
|
||||
pub storage_create_bucket: bool,
|
||||
/// `OAUTH_REDIRECT_URIS`: comma-separated return addresses an MCP client
|
||||
/// may register (docs/mcp.md); a trailing `*` stands for any port (and
|
||||
/// path). Default: Claude's callbacks and local ones for Claude Code.
|
||||
pub oauth_redirect_uris: Vec<String>,
|
||||
/// `MCP_RESOURCE_URL`: the MCP server's address, the audience of the
|
||||
/// tokens (default `PUBLIC_BASE_URL` + `/mcp`).
|
||||
pub mcp_resource_url: String,
|
||||
}
|
||||
|
||||
/// The default `OAUTH_REDIRECT_URIS`.
|
||||
pub const DEFAULT_OAUTH_REDIRECT_URIS: [&str; 4] = [
|
||||
"https://claude.ai/api/mcp/auth_callback",
|
||||
"https://claude.com/api/mcp/auth_callback",
|
||||
"http://localhost:*",
|
||||
"http://127.0.0.1:*",
|
||||
];
|
||||
|
||||
/// `STRIPE_SECRET_KEY` (`sk_test_…` or `sk_live_…`), `STRIPE_WEBHOOK_SECRET`
|
||||
/// (`whsec_…`, from the webhook endpoint in the Stripe dashboard) and
|
||||
/// `STRIPE_API_URL` (default `https://api.stripe.com`, tests change it).
|
||||
@@ -182,7 +197,6 @@ impl Config {
|
||||
let config = Self {
|
||||
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
|
||||
horoscope_api_url: var("HOROSCOPE_API_URL").unwrap_or_else(|| "http://localhost:8080".into()),
|
||||
public_base_url,
|
||||
cors_allowed_origins,
|
||||
cookie_secure: parsed("COOKIE_SECURE", true)?,
|
||||
cookie_domain: var("COOKIE_DOMAIN"),
|
||||
@@ -250,6 +264,14 @@ impl Config {
|
||||
}),
|
||||
},
|
||||
storage_create_bucket: parsed("S3_CREATE_BUCKET", false)?,
|
||||
oauth_redirect_uris: match list("OAUTH_REDIRECT_URIS") {
|
||||
uris if uris.is_empty() => DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(),
|
||||
uris => uris,
|
||||
},
|
||||
mcp_resource_url: var("MCP_RESOURCE_URL")
|
||||
.map(|u| u.trim_end_matches('/').to_string())
|
||||
.unwrap_or_else(|| format!("{public_base_url}/mcp")),
|
||||
public_base_url,
|
||||
};
|
||||
if config.session_ttl_days < 1 {
|
||||
bail!("SESSION_TTL_DAYS must be at least 1");
|
||||
@@ -300,6 +322,8 @@ impl Config {
|
||||
secret_key: "test-secret".into(),
|
||||
}),
|
||||
storage_create_bucket: false,
|
||||
oauth_redirect_uris: DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(),
|
||||
mcp_resource_url: "https://sorsfonalak.test/mcp".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ mod packages;
|
||||
mod persons;
|
||||
mod photo;
|
||||
mod routes;
|
||||
mod signup_source;
|
||||
mod storage;
|
||||
mod stripe;
|
||||
#[cfg(test)]
|
||||
@@ -62,6 +63,8 @@ pub struct AppState {
|
||||
pub storage: Option<storage::Storage>,
|
||||
/// The sky by date, the same for everyone (see `routes::sky`).
|
||||
pub sky: routes::sky::SkyCache,
|
||||
/// MCP client registrations and token requests, per visitor address.
|
||||
pub oauth_limiter: LoginLimiter,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -79,6 +82,7 @@ impl AppState {
|
||||
stripe: stripe::Client::default(),
|
||||
storage: config.storage.clone().map(storage::Storage::new),
|
||||
sky: Default::default(),
|
||||
oauth_limiter: LoginLimiter::new(60, Duration::from_secs(60 * 60)),
|
||||
db,
|
||||
config,
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ impl Function {
|
||||
|
||||
pub fn of(kind: Kind) -> Function {
|
||||
match kind {
|
||||
Kind::Summary => Function::Summary,
|
||||
// The weekly horoscope is written by the summary's (cheaper) model.
|
||||
Kind::Summary | Kind::Weekly => Function::Summary,
|
||||
Kind::Question => Function::Question,
|
||||
Kind::Natal | Kind::Synastry | Kind::Forecast | Kind::Celebrity => Function::Analysis,
|
||||
}
|
||||
|
||||
@@ -41,6 +41,10 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
.await?;
|
||||
let replies = super::feedback::unseen_replies(&mut conn, auth.id()).await?;
|
||||
let nps_due = super::feedback::nps_due(&mut conn, auth.id()).await?;
|
||||
let weekly_email: bool = sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1")
|
||||
.bind(auth.id())
|
||||
.fetch_one(&mut *conn)
|
||||
.await?;
|
||||
Ok(Json(json!({
|
||||
"user": UserView::from(&auth.user),
|
||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
||||
@@ -59,6 +63,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
"feedback_replies_unseen": replies,
|
||||
// Ask the "would you recommend us?" question now.
|
||||
"nps_due": nps_due,
|
||||
// Monday's e-mail about the weekly horoscope is on.
|
||||
"weekly_email": weekly_email,
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -132,6 +138,7 @@ pub async fn change_password(
|
||||
.bind(auth.session_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
db::revoke_oauth_grants(&mut *tx, auth.id()).await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -169,6 +176,8 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
|
||||
"exported_at": rfc3339(OffsetDateTime::now_utc()),
|
||||
"user": UserView::from(&auth.user),
|
||||
"last_login_at": rfc3339_opt(auth.user.last_login_at),
|
||||
"signup_came_from": rows("SELECT json_build_object('source', signup_source, 'site_or_campaign', signup_detail, 'device', signup_device) FROM users WHERE id = $1").await?.into_iter().next(),
|
||||
"weekly_horoscope_email": rows("SELECT json_build_object('on', weekly_email, 'last_sent_for_week', weekly_email_sent_on) FROM users WHERE id = $1").await?.into_iter().next(),
|
||||
"login_methods": rows("SELECT json_build_object('provider', provider, 'email', email, 'created_at', created_at, 'last_used_at', last_used_at) FROM auth_identities WHERE user_id = $1").await?,
|
||||
"sessions": rows("SELECT json_build_object('created_at', created_at, 'expires_at', expires_at, 'user_agent', user_agent) FROM sessions WHERE user_id = $1").await?,
|
||||
"charts": rows("SELECT json_build_object('id', id, 'label', label, 'is_primary', is_primary, 'birth_data', birth_data, 'result', result, 'created_at', created_at) FROM charts WHERE owner_id = $1 AND kind <> 'celebrity'").await?,
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! instead, free of charge, so the same chart is never paid for twice.
|
||||
//!
|
||||
//! Every saved chart also gets a free short summary (`summary` kind, written
|
||||
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
|
||||
//! by `SUMMARY_MODEL`); the detailed analyses are paid. The own chart's free
|
||||
//! weekly horoscope (`weekly` kind, see [`super::weekly`]) uses the summary's model.
|
||||
|
||||
use analysis_prompt::Kind;
|
||||
use axum::Json;
|
||||
@@ -18,7 +19,7 @@ use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use time::{Date, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::auth::validate_locale;
|
||||
@@ -53,11 +54,14 @@ pub struct AnalysisRow {
|
||||
pub next_attempt_at: OffsetDateTime,
|
||||
/// When the current text was asked for (set again by a regeneration).
|
||||
pub requested_at: OffsetDateTime,
|
||||
/// The Monday of a weekly horoscope.
|
||||
pub week_start: Option<Date>,
|
||||
}
|
||||
|
||||
pub(super) const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
|
||||
content, error, \
|
||||
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at";
|
||||
credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at, \
|
||||
week_start";
|
||||
|
||||
impl AnalysisRow {
|
||||
pub fn view(&self) -> Value {
|
||||
@@ -78,6 +82,7 @@ impl AnalysisRow {
|
||||
"attempts": self.attempts,
|
||||
"next_attempt_at": rfc3339(self.next_attempt_at),
|
||||
"requested_at": rfc3339(self.requested_at),
|
||||
"week_start": self.week_start.map(|d| d.to_string()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -143,6 +148,12 @@ pub(super) enum Target {
|
||||
chart_id: Uuid,
|
||||
hash: String,
|
||||
},
|
||||
/// The own chart's weekly horoscope (free); `hash` covers the chart and the week.
|
||||
Weekly {
|
||||
chart_id: Uuid,
|
||||
hash: String,
|
||||
week_start: Date,
|
||||
},
|
||||
}
|
||||
|
||||
async fn request(
|
||||
@@ -197,6 +208,11 @@ pub(super) async fn queue(
|
||||
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
|
||||
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
|
||||
Target::Celebrity { chart_id, hash } => ("celebrity", hash, Some(*chart_id), None, None),
|
||||
Target::Weekly { chart_id, hash, .. } => ("weekly", hash, Some(*chart_id), None, None),
|
||||
};
|
||||
let week_start = match target {
|
||||
Target::Weekly { week_start, .. } => Some(*week_start),
|
||||
_ => None,
|
||||
};
|
||||
let (model, fallback) = &crate::models::models_for(state, Kind::parse(kind).expect("known kind")).await?;
|
||||
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
|
||||
@@ -225,8 +241,9 @@ pub(super) async fn queue(
|
||||
let insert = format!(
|
||||
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
|
||||
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at, \
|
||||
forecast_id, fallback_model) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) RETURNING {ANALYSIS_COLUMNS}"
|
||||
forecast_id, fallback_model, week_start) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
|
||||
RETURNING {ANALYSIS_COLUMNS}"
|
||||
);
|
||||
let id = Uuid::now_v7();
|
||||
|
||||
@@ -263,6 +280,7 @@ pub(super) async fn queue(
|
||||
.bind(OffsetDateTime::now_utc())
|
||||
.bind(forecast_id)
|
||||
.bind(fallback)
|
||||
.bind(week_start)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
@@ -288,6 +306,7 @@ pub(super) async fn queue(
|
||||
.bind(None::<OffsetDateTime>)
|
||||
.bind(forecast_id)
|
||||
.bind(fallback)
|
||||
.bind(week_start)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if let Some(unit) = unit {
|
||||
@@ -395,6 +414,14 @@ pub async fn request_for_forecast(
|
||||
/// The hash of what the analysis is about (chart, comparison or forecast),
|
||||
/// part of its cache key; `None` when that was deleted.
|
||||
pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result<Option<String>, sqlx::Error> {
|
||||
if row.kind == "weekly" {
|
||||
let hash: Option<String> = sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
|
||||
.bind(row.chart_id)
|
||||
.fetch_optional(db)
|
||||
.await?;
|
||||
let week = row.week_start.map(|d| d.to_string()).unwrap_or_default();
|
||||
return Ok(hash.map(|h| super::weekly::target_hash(&h, &week)));
|
||||
}
|
||||
let (query, id) = match row.kind.as_str() {
|
||||
"synastry" => ("SELECT synastry_hash FROM synastries WHERE id = $1", row.synastry_id),
|
||||
"forecast" => ("SELECT forecast_hash FROM forecasts WHERE id = $1", row.forecast_id),
|
||||
|
||||
@@ -25,6 +25,7 @@ use crate::auth::{
|
||||
validate_password, verify_password,
|
||||
};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::signup_source::{self, CameFrom};
|
||||
use crate::views::UserView;
|
||||
|
||||
const VERIFY_EMAIL_TTL: time::Duration = time::Duration::days(3);
|
||||
@@ -230,6 +231,9 @@ pub struct RegisterRequest {
|
||||
/// Cloudflare Turnstile's token (see [`crate::turnstile`]).
|
||||
#[serde(default)]
|
||||
turnstile_token: Option<String>,
|
||||
/// Where the visit began, for the statistics.
|
||||
#[serde(default)]
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Before a sign-up or reset e-mail goes out: at most a few per visitor
|
||||
@@ -242,6 +246,12 @@ async fn not_a_robot(state: &AppState, headers: &axum::http::HeaderMap, token: O
|
||||
crate::turnstile::verify(state.config.turnstile.as_ref(), token, ip.as_deref()).await
|
||||
}
|
||||
|
||||
/// Where a new member came from (see [`signup_source`]).
|
||||
fn arrival(state: &AppState, headers: &HeaderMap, came: Option<&CameFrom>) -> signup_source::Arrival {
|
||||
let ua = user_agent(headers);
|
||||
signup_source::classify(ua.as_deref(), came, &signup_source::host_of(&state.config.public_base_url))
|
||||
}
|
||||
|
||||
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
|
||||
pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
|
||||
if state.config.password_login {
|
||||
@@ -279,11 +289,18 @@ pub async fn register(
|
||||
None => {
|
||||
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
|
||||
let user_id = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
|
||||
let arrival = arrival(&state, &headers, req.came_from.as_ref());
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, email, display_name, locale, signup_source, signup_detail, signup_device) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(req.display_name))
|
||||
.bind(&locale)
|
||||
.bind(arrival.source)
|
||||
.bind(&arrival.detail)
|
||||
.bind(arrival.device)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Packages of invitations go to this account; only whoever opens
|
||||
@@ -369,6 +386,9 @@ pub struct GoogleRequest {
|
||||
invite_token: Option<String>,
|
||||
/// The slug of the shared link the visitor came from.
|
||||
referral: Option<String>,
|
||||
/// Where the visit began, for the statistics of a new account.
|
||||
#[serde(default)]
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Logs in with Google. An unknown Google account is linked to the existing
|
||||
@@ -385,6 +405,7 @@ pub async fn google(
|
||||
locale: claims.locale.clone(),
|
||||
invite_token: req.invite_token,
|
||||
referral: req.referral,
|
||||
came_from: req.came_from,
|
||||
};
|
||||
social_login(&state, headers, jar, "google", claims, signup).await
|
||||
}
|
||||
@@ -401,6 +422,8 @@ pub struct AppleRequest {
|
||||
name: Option<String>,
|
||||
invite_token: Option<String>,
|
||||
referral: Option<String>,
|
||||
#[serde(default)]
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Logs in with Apple, like [`google`]. The address may be an Apple relay
|
||||
@@ -412,7 +435,13 @@ pub async fn apple(
|
||||
WithRejection(Json(req), _): Body<AppleRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
let claims = state.apple.verify(&req.id_token).await?;
|
||||
let signup = Signup { name: req.name, locale: None, invite_token: req.invite_token, referral: req.referral };
|
||||
let signup = Signup {
|
||||
name: req.name,
|
||||
locale: None,
|
||||
invite_token: req.invite_token,
|
||||
referral: req.referral,
|
||||
came_from: req.came_from,
|
||||
};
|
||||
social_login(&state, headers, jar, "apple", claims, signup).await
|
||||
}
|
||||
|
||||
@@ -422,6 +451,7 @@ struct Signup {
|
||||
locale: Option<String>,
|
||||
invite_token: Option<String>,
|
||||
referral: Option<String>,
|
||||
came_from: Option<CameFrom>,
|
||||
}
|
||||
|
||||
/// Logs in with a verified provider identity: the linked user, else the user
|
||||
@@ -479,6 +509,7 @@ async fn social_login(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(id).execute(&mut *tx).await?;
|
||||
db::revoke_oauth_grants(&mut *tx, id).await?;
|
||||
tracing::warn!(user = %id, provider, "unconfirmed password account taken over by its address's owner");
|
||||
}
|
||||
// The provider has verified the address, so it counts as verified here too.
|
||||
@@ -500,13 +531,19 @@ async fn social_login(
|
||||
.filter(|l| state.config.supported_locales.iter().any(|s| s == l))
|
||||
.unwrap_or(&state.config.supported_locales[0])
|
||||
.to_string();
|
||||
let arrival = arrival(state, &headers, signup.came_from.as_ref());
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, email, email_verified_at, display_name, locale) VALUES ($1, $2, now(), $3, $4)",
|
||||
"INSERT INTO users (id, email, email_verified_at, display_name, locale, \
|
||||
signup_source, signup_detail, signup_device) \
|
||||
VALUES ($1, $2, now(), $3, $4, $5, $6, $7)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(&email)
|
||||
.bind(clean_name(signup.name))
|
||||
.bind(locale)
|
||||
.bind(arrival.source)
|
||||
.bind(&arrival.detail)
|
||||
.bind(arrival.device)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
super::invitations::mark_accepted(
|
||||
@@ -559,6 +596,8 @@ pub async fn logout(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResu
|
||||
/// Ends every session of the user (all devices).
|
||||
pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(auth.id()).execute(&state.db).await?;
|
||||
// The MCP clients connected by the user too (docs/mcp.md).
|
||||
db::revoke_oauth_grants(&state.db, auth.id()).await?;
|
||||
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
|
||||
}
|
||||
|
||||
@@ -623,6 +662,7 @@ pub async fn set_password_with_link(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
|
||||
db::revoke_oauth_grants(&mut *tx, user_id).await?;
|
||||
let mut user = load_user(&mut tx, user_id).await?;
|
||||
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -349,7 +349,8 @@ async fn corrected_birth(
|
||||
// The user's own comparisons with the person are deleted on correction (they
|
||||
// no longer match), unless a paid analysis was written for one of them.
|
||||
let (analysed, foreign_synastry): (bool, bool) = sqlx::query_as(
|
||||
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind <> 'summary' AND status <> 'failed') \
|
||||
"SELECT EXISTS (SELECT 1 FROM analyses WHERE chart_id = $1 AND kind NOT IN ('summary', 'weekly') \
|
||||
AND status <> 'failed') \
|
||||
OR EXISTS (SELECT 1 FROM analyses a JOIN synastries s ON s.id = a.synastry_id \
|
||||
WHERE (s.chart1_id = $1 OR s.chart2_id = $1) AND a.status <> 'failed') \
|
||||
OR EXISTS (SELECT 1 FROM analyses a JOIN forecasts f ON f.id = a.forecast_id \
|
||||
|
||||
@@ -43,7 +43,7 @@ pub const TAGS: [&str; 10] = [
|
||||
"useful",
|
||||
];
|
||||
/// What can be rated (analysis kinds, and answers to questions).
|
||||
const RATED_KINDS: [&str; 5] = ["summary", "natal", "synastry", "forecast", "tarot"];
|
||||
const RATED_KINDS: [&str; 6] = ["summary", "natal", "synastry", "forecast", "tarot", "weekly"];
|
||||
const MAX_COMMENT: usize = 1000;
|
||||
const MAX_MESSAGE: usize = 2000;
|
||||
const MAX_REPLY: usize = 4000;
|
||||
|
||||
@@ -20,6 +20,8 @@ mod invitations;
|
||||
mod invoices_user;
|
||||
mod jobs;
|
||||
mod models;
|
||||
mod notifications;
|
||||
mod oauth;
|
||||
pub(crate) mod payments;
|
||||
mod promo;
|
||||
mod prompts;
|
||||
@@ -27,8 +29,10 @@ mod questions;
|
||||
mod recalculate;
|
||||
mod shares;
|
||||
pub mod sky;
|
||||
mod stats;
|
||||
mod synastries;
|
||||
mod tarot;
|
||||
mod weekly;
|
||||
|
||||
pub use recalculate::run as recalculate;
|
||||
|
||||
@@ -36,7 +40,7 @@ use std::sync::Arc;
|
||||
|
||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||
use axum::http::{HeaderValue, Method, header};
|
||||
use axum::routing::{delete, get, patch, post};
|
||||
use axum::routing::{delete, get, patch, post, put};
|
||||
use axum::{Json, Router};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde_json::{Value, json};
|
||||
@@ -85,6 +89,15 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/auth/logout-all", post(auth::logout_all))
|
||||
.route("/v1/auth/password-reset", post(auth::request_password_reset))
|
||||
.route("/v1/auth/set-password", post(auth::set_password_with_link))
|
||||
// MCP clients (docs/mcp.md): OAuth for the admin tools.
|
||||
.route("/v1/oauth/metadata", get(oauth::metadata))
|
||||
.route("/v1/oauth/register", post(oauth::register))
|
||||
.route("/v1/oauth/authorize", get(oauth::authorize_check).post(oauth::authorize))
|
||||
.route("/v1/oauth/token", post(oauth::token))
|
||||
.route("/v1/oauth/revoke", post(oauth::revoke))
|
||||
.route("/v1/oauth/whoami", get(oauth::whoami))
|
||||
.route("/v1/admin/oauth/grants", get(oauth::admin_grants))
|
||||
.route("/v1/admin/oauth/grants/{id}", delete(oauth::admin_revoke_grant))
|
||||
// own account (GDPR export and deletion included)
|
||||
.route("/v1/me", get(account::me).patch(account::update_me).delete(account::delete_me))
|
||||
.route("/v1/me/password", post(account::change_password))
|
||||
@@ -101,6 +114,9 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
|
||||
.route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
|
||||
.route("/v1/charts/{id}/summary", post(analyses::summary_for_chart))
|
||||
.route("/v1/weekly", post(weekly::current))
|
||||
.route("/v1/weekly/email", put(weekly::set_email))
|
||||
.route("/v1/weekly/history", get(weekly::history))
|
||||
.route("/v1/charts/{id}/forecasts", get(forecasts::list_for_chart).post(forecasts::create))
|
||||
.route("/v1/forecasts/{id}", get(forecasts::get_one))
|
||||
.route("/v1/forecasts/{id}/analyses", get(analyses::list_for_forecast).post(analyses::request_for_forecast))
|
||||
@@ -145,6 +161,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
|
||||
.route("/v1/public/invites/{token}", get(synastries::public_invite))
|
||||
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
||||
.route("/v1/public/weekly/unsubscribe", post(weekly::unsubscribe))
|
||||
.route("/v1/public/notifications", get(notifications::get_settings).put(notifications::put_settings))
|
||||
.route("/v1/public/invitations/{token}", get(invitations::public_view))
|
||||
.route("/v1/public/waitlist", post(invitations::join_waitlist))
|
||||
.route("/v1/public/chart", post(calculator::chart))
|
||||
@@ -156,6 +174,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/public/celebrities/{slug}", get(celebrities::public_view))
|
||||
.route("/v1/public/photos/{*key}", get(celebrities::photo))
|
||||
// administration
|
||||
.route("/v1/admin/stats", get(stats::admin_stats))
|
||||
.route("/v1/admin/users", get(admin::list_users))
|
||||
.route("/v1/admin/users/{id}", patch(admin::update_user))
|
||||
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! The page of every e-mail setting, opened from an e-mail's footer with the
|
||||
//! user's `email_token` (no login needed): Monday's weekly horoscope e-mail
|
||||
//! and, for forum members, the forum's e-mails (the same settings as on the
|
||||
//! forum profile). The e-mails that belong to something the user does
|
||||
//! (password, purchase, invoice) always go, so they are not listed.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St};
|
||||
use crate::AppState;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenQuery {
|
||||
token: String,
|
||||
}
|
||||
|
||||
async fn user_of(state: &AppState, token: &str) -> Result<Uuid, ApiError> {
|
||||
let token = Uuid::parse_str(token.trim()).map_err(|_| ApiError::NotFound("token"))?;
|
||||
let user: Option<Uuid> =
|
||||
sqlx::query_scalar("SELECT id FROM users WHERE email_token = $1").bind(token).fetch_optional(&state.db).await?;
|
||||
user.ok_or(ApiError::NotFound("token"))
|
||||
}
|
||||
|
||||
type ForumRow = (String, String, String, String, String, bool, bool);
|
||||
|
||||
async fn settings(state: &AppState, user: Uuid) -> Result<Value, ApiError> {
|
||||
let weekly: bool =
|
||||
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await?;
|
||||
let forum: Option<ForumRow> = sqlx::query_as(
|
||||
"SELECT email_replies, email_followed, email_messages, email_mentions, email_listener, email_weekly, listener \
|
||||
FROM forum.members WHERE user_id = $1",
|
||||
)
|
||||
.bind(user)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
Ok(json!({
|
||||
"weekly_horoscope": weekly,
|
||||
"forum": forum.map(|(replies, followed, messages, mentions, listener_mail, weekly, listener)| json!({
|
||||
"replies": replies,
|
||||
"followed": followed,
|
||||
"messages": messages,
|
||||
"mentions": mentions,
|
||||
// Only volunteer listeners get these.
|
||||
"listener": listener.then_some(listener_mail),
|
||||
"weekly": weekly,
|
||||
})),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn get_settings(
|
||||
State(state): St,
|
||||
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let user = user_of(&state, &q.token).await?;
|
||||
Ok(Json(settings(&state, user).await?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
weekly_horoscope: bool,
|
||||
#[serde(default)]
|
||||
forum: Option<ForumSettings>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ForumSettings {
|
||||
replies: String,
|
||||
followed: String,
|
||||
messages: String,
|
||||
mentions: String,
|
||||
#[serde(default)]
|
||||
listener: Option<String>,
|
||||
weekly: bool,
|
||||
}
|
||||
|
||||
fn one_of(value: &str, allowed: &[&str], what: &str) -> Result<(), ApiError> {
|
||||
if allowed.contains(&value) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ApiError::BadRequest(format!("{what} must be one of {}", allowed.join(", "))))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn put_settings(
|
||||
State(state): St,
|
||||
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||
WithRejection(Json(req), _): Body<Settings>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let user = user_of(&state, &q.token).await?;
|
||||
if let Some(f) = &req.forum {
|
||||
one_of(&f.replies, &["off", "daily", "instant"], "replies")?;
|
||||
one_of(&f.followed, &["off", "daily"], "followed")?;
|
||||
one_of(&f.messages, &["off", "instant"], "messages")?;
|
||||
one_of(&f.mentions, &["off", "instant"], "mentions")?;
|
||||
if let Some(l) = &f.listener {
|
||||
one_of(l, &["off", "instant"], "listener")?;
|
||||
}
|
||||
}
|
||||
let mut tx = state.db.begin().await?;
|
||||
// As the switch on the site: turned on again, the first one comes next Monday.
|
||||
sqlx::query(&super::weekly::switch_sql()).bind(user).bind(req.weekly_horoscope).execute(&mut *tx).await?;
|
||||
if let Some(f) = &req.forum {
|
||||
sqlx::query(
|
||||
"UPDATE forum.members SET email_replies = $2, email_followed = $3, email_messages = $4, \
|
||||
email_mentions = $5, email_listener = coalesce($6, email_listener), email_weekly = $7 \
|
||||
WHERE user_id = $1",
|
||||
)
|
||||
.bind(user)
|
||||
.bind(&f.replies)
|
||||
.bind(&f.followed)
|
||||
.bind(&f.messages)
|
||||
.bind(&f.mentions)
|
||||
.bind(&f.listener)
|
||||
.bind(f.weekly)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(settings(&state, user).await?))
|
||||
}
|
||||
@@ -0,0 +1,748 @@
|
||||
//! OAuth 2.1 for the MCP server (docs/mcp.md). Claude registers itself as a
|
||||
//! client (only with an allowed return address), an admin approves the
|
||||
//! connection on the site (`/oauth/engedely`, which calls `authorize`), and
|
||||
//! Claude trades the code for an access token (an hour) and a refresh token
|
||||
//! (30 days, a new one at every refresh). The admin guards accept the access
|
||||
//! token (see `auth::MCP_WRITES`); the MCP server checks it with `whoami`.
|
||||
//!
|
||||
//! The endpoints Claude calls (`register`, `token`, `revoke`) answer OAuth's
|
||||
//! own error format; the ones the site calls answer the API's.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::rejection::{FormRejection, JsonRejection};
|
||||
use axum::extract::{FromRequestParts, Path, Query, State};
|
||||
use axum::http::header::{AUTHORIZATION, CACHE_CONTROL, PRAGMA};
|
||||
use axum::http::request::Parts;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{Form, Json};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
|
||||
use db::Role;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Body, St, client_ip};
|
||||
use crate::AppState;
|
||||
use crate::auth::{AuthUser, oauth_user};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
/// What a connection may do: the admin tools (the guards narrow it further).
|
||||
pub const SCOPE: &str = "admin";
|
||||
const ACCESS_TTL: Duration = Duration::hours(1);
|
||||
const REFRESH_TTL: Duration = Duration::days(30);
|
||||
const CODE_TTL: Duration = Duration::minutes(10);
|
||||
const MAX_REDIRECT_URIS: usize = 5;
|
||||
const AUTH_METHODS: [&str; 3] = ["none", "client_secret_post", "client_secret_basic"];
|
||||
|
||||
// --- errors in OAuth's format -----------------------------------------------------
|
||||
|
||||
/// `{"error", "error_description"}` (RFC 6749 5.2, RFC 7591 3.2.2).
|
||||
#[derive(Debug)]
|
||||
pub struct OauthError {
|
||||
status: StatusCode,
|
||||
error: &'static str,
|
||||
description: String,
|
||||
}
|
||||
|
||||
impl OauthError {
|
||||
fn new(error: &'static str, description: impl Into<String>) -> Self {
|
||||
let status = if error == "invalid_client" { StatusCode::UNAUTHORIZED } else { StatusCode::BAD_REQUEST };
|
||||
Self { status, error, description: description.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for OauthError {
|
||||
fn into_response(self) -> Response {
|
||||
if self.status.is_server_error() {
|
||||
tracing::error!(error = %self.description, "oauth request failed");
|
||||
}
|
||||
let body = Json(json!({ "error": self.error, "error_description": self.description }));
|
||||
(self.status, [(CACHE_CONTROL, "no-store")], body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for OauthError {
|
||||
fn from(e: sqlx::Error) -> Self {
|
||||
Self { status: StatusCode::INTERNAL_SERVER_ERROR, error: "server_error", description: format!("database: {e}") }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ApiError> for OauthError {
|
||||
fn from(e: ApiError) -> Self {
|
||||
match e {
|
||||
ApiError::TooManyRequests => {
|
||||
Self { status: StatusCode::TOO_MANY_REQUESTS, error: "too_many_requests", description: e.to_string() }
|
||||
}
|
||||
other => Self {
|
||||
status: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error: "server_error",
|
||||
description: other.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonRejection> for OauthError {
|
||||
fn from(rejection: JsonRejection) -> Self {
|
||||
Self::new("invalid_client_metadata", rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FormRejection> for OauthError {
|
||||
fn from(rejection: FormRejection) -> Self {
|
||||
Self::new("invalid_request", rejection.body_text())
|
||||
}
|
||||
}
|
||||
|
||||
// --- metadata (RFC 8414) ------------------------------------------------------------
|
||||
|
||||
/// The authorization server's metadata, served by the frontend at
|
||||
/// `/.well-known/oauth-authorization-server`.
|
||||
pub async fn metadata(State(state): St) -> Json<Value> {
|
||||
let base = &state.config.public_base_url;
|
||||
Json(json!({
|
||||
"issuer": base,
|
||||
"authorization_endpoint": format!("{base}/oauth/engedely"),
|
||||
"token_endpoint": format!("{base}/api/v1/oauth/token"),
|
||||
"registration_endpoint": format!("{base}/api/v1/oauth/register"),
|
||||
"revocation_endpoint": format!("{base}/api/v1/oauth/revoke"),
|
||||
"response_types_supported": ["code"],
|
||||
"response_modes_supported": ["query"],
|
||||
"grant_types_supported": ["authorization_code", "refresh_token"],
|
||||
"code_challenge_methods_supported": ["S256"],
|
||||
"token_endpoint_auth_methods_supported": AUTH_METHODS,
|
||||
"revocation_endpoint_auth_methods_supported": AUTH_METHODS,
|
||||
"scopes_supported": [SCOPE],
|
||||
"authorization_response_iss_parameter_supported": true,
|
||||
}))
|
||||
}
|
||||
|
||||
// --- client registration (RFC 7591) ---------------------------------------------------
|
||||
|
||||
/// Whether a client may register `uri` as its return address: one of the
|
||||
/// configured ones, where a trailing `*` stands for a port and any path.
|
||||
pub fn redirect_allowed(uri: &str, patterns: &[String]) -> bool {
|
||||
if uri.len() > 500 || uri.contains('#') || uri.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return false;
|
||||
}
|
||||
patterns.iter().any(|pattern| match pattern.strip_suffix('*') {
|
||||
None => uri == pattern,
|
||||
Some(prefix) => uri.strip_prefix(prefix).is_some_and(|rest| {
|
||||
let port = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
|
||||
!port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit())
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Registration {
|
||||
#[serde(default)]
|
||||
redirect_uris: Vec<String>,
|
||||
client_name: Option<String>,
|
||||
token_endpoint_auth_method: Option<String>,
|
||||
grant_types: Option<Vec<String>>,
|
||||
response_types: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Json(req), _): WithRejection<Json<Registration>, OauthError>,
|
||||
) -> Result<Response, OauthError> {
|
||||
state.oauth_limiter.hit(&format!("register:{}", client_ip(&headers).unwrap_or_default()))?;
|
||||
if req.redirect_uris.is_empty() || req.redirect_uris.len() > MAX_REDIRECT_URIS {
|
||||
return Err(OauthError::new("invalid_redirect_uri", "Give one to five redirect_uris."));
|
||||
}
|
||||
if let Some(bad) = req.redirect_uris.iter().find(|u| !redirect_allowed(u, &state.config.oauth_redirect_uris)) {
|
||||
return Err(OauthError::new("invalid_redirect_uri", format!("This redirect_uri is not allowed: {bad}")));
|
||||
}
|
||||
let grant_types = req.grant_types.unwrap_or_else(|| vec!["authorization_code".into()]);
|
||||
if grant_types.iter().any(|g| g != "authorization_code" && g != "refresh_token") {
|
||||
return Err(OauthError::new("invalid_client_metadata", "Only authorization_code and refresh_token."));
|
||||
}
|
||||
let response_types = req.response_types.unwrap_or_else(|| vec!["code".into()]);
|
||||
if response_types.iter().any(|r| r != "code") {
|
||||
return Err(OauthError::new("invalid_client_metadata", "Only the code response type."));
|
||||
}
|
||||
// RFC 7591's default is client_secret_basic.
|
||||
let method = req.token_endpoint_auth_method.unwrap_or_else(|| "client_secret_basic".into());
|
||||
if !AUTH_METHODS.contains(&method.as_str()) {
|
||||
return Err(OauthError::new("invalid_client_metadata", "Unsupported token_endpoint_auth_method."));
|
||||
}
|
||||
let name: String = req
|
||||
.client_name
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(100)
|
||||
.collect::<String>()
|
||||
.trim()
|
||||
.to_string();
|
||||
let name = if name.is_empty() { "MCP-kliens".to_string() } else { name };
|
||||
|
||||
let client_id = db::random_token(16);
|
||||
let secret = (method != "none").then(db::new_token);
|
||||
sqlx::query("INSERT INTO oauth_clients (id, name, redirect_uris, secret_hash) VALUES ($1, $2, $3, $4)")
|
||||
.bind(&client_id)
|
||||
.bind(&name)
|
||||
.bind(&req.redirect_uris)
|
||||
.bind(secret.as_deref().map(db::token_hash))
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(client = %client_id, name = %name, "oauth client registered");
|
||||
let mut body = json!({
|
||||
"client_id": client_id,
|
||||
"client_id_issued_at": OffsetDateTime::now_utc().unix_timestamp(),
|
||||
"client_name": name,
|
||||
"redirect_uris": req.redirect_uris,
|
||||
"grant_types": grant_types,
|
||||
"response_types": response_types,
|
||||
"token_endpoint_auth_method": method,
|
||||
});
|
||||
if let Some(secret) = secret {
|
||||
body["client_secret"] = json!(secret);
|
||||
body["client_secret_expires_at"] = json!(0);
|
||||
}
|
||||
Ok((StatusCode::CREATED, [(CACHE_CONTROL, "no-store")], Json(body)).into_response())
|
||||
}
|
||||
|
||||
// --- approval (the site's /oauth/engedely page) -----------------------------------------
|
||||
|
||||
/// The authorization request's parameters, as the client put them on the
|
||||
/// approval page's address (and the page sends them on).
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AuthorizeParams {
|
||||
response_type: Option<String>,
|
||||
client_id: Option<String>,
|
||||
redirect_uri: Option<String>,
|
||||
code_challenge: Option<String>,
|
||||
code_challenge_method: Option<String>,
|
||||
scope: Option<String>,
|
||||
state: Option<String>,
|
||||
resource: Option<String>,
|
||||
/// POST only: the admin said no.
|
||||
#[serde(default)]
|
||||
deny: bool,
|
||||
}
|
||||
|
||||
/// A checked authorization request.
|
||||
struct Checked {
|
||||
client_id: String,
|
||||
client_name: String,
|
||||
redirect_uri: String,
|
||||
code_challenge: String,
|
||||
state: Option<String>,
|
||||
}
|
||||
|
||||
fn bad(message: &str) -> ApiError {
|
||||
ApiError::BadRequest(message.to_string())
|
||||
}
|
||||
|
||||
/// The same address with or without a trailing slash.
|
||||
fn same_resource(a: &str, b: &str) -> bool {
|
||||
a.trim_end_matches('/') == b.trim_end_matches('/')
|
||||
}
|
||||
|
||||
async fn check(state: &AppState, p: &AuthorizeParams) -> ApiResult<Checked> {
|
||||
let client_id = p.client_id.as_deref().ok_or_else(|| bad("Hiányzik az alkalmazás azonosítója."))?;
|
||||
let client: Option<(String, Vec<String>)> =
|
||||
sqlx::query_as("SELECT name, redirect_uris FROM oauth_clients WHERE id = $1")
|
||||
.bind(client_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let (client_name, redirect_uris) = client.ok_or_else(|| bad("Ismeretlen alkalmazás. Kapcsold össze újra."))?;
|
||||
let redirect_uri = match &p.redirect_uri {
|
||||
Some(uri) if redirect_uris.contains(uri) => uri.clone(),
|
||||
None if redirect_uris.len() == 1 => redirect_uris[0].clone(),
|
||||
_ => return Err(bad("Ez a visszatérési cím nincs az alkalmazásnál bejegyezve.")),
|
||||
};
|
||||
if p.response_type.as_deref() != Some("code") {
|
||||
return Err(bad("Csak a „code” válaszforma támogatott."));
|
||||
}
|
||||
if p.code_challenge_method.as_deref() != Some("S256") {
|
||||
return Err(bad("PKCE (S256) kell."));
|
||||
}
|
||||
let code_challenge = p.code_challenge.clone().unwrap_or_default();
|
||||
if !(43..=128).contains(&code_challenge.len()) {
|
||||
return Err(bad("Hibás PKCE-kód."));
|
||||
}
|
||||
if let Some(resource) = &p.resource
|
||||
&& !same_resource(resource, &state.config.mcp_resource_url)
|
||||
{
|
||||
return Err(bad("Ismeretlen erőforrás."));
|
||||
}
|
||||
if p.state.as_deref().is_some_and(|s| s.len() > 1000) {
|
||||
return Err(bad("Túl hosszú state."));
|
||||
}
|
||||
Ok(Checked { client_id: client_id.to_string(), client_name, redirect_uri, code_challenge, state: p.state.clone() })
|
||||
}
|
||||
|
||||
/// The approval page asks what it is approving (no login needed for this).
|
||||
pub async fn authorize_check(
|
||||
State(state): St,
|
||||
WithRejection(Query(p), _): WithRejection<Query<AuthorizeParams>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let c = check(&state, &p).await?;
|
||||
let host = reqwest::Url::parse(&c.redirect_uri).ok().and_then(|u| u.host_str().map(str::to_string));
|
||||
Ok(Json(json!({
|
||||
"client_name": c.client_name,
|
||||
"redirect_uri": c.redirect_uri,
|
||||
"redirect_host": host,
|
||||
"scope": SCOPE,
|
||||
"resource": state.config.mcp_resource_url,
|
||||
// `requested` is what the client asked for; the connection gets `scope`.
|
||||
"requested_scope": p.scope,
|
||||
})))
|
||||
}
|
||||
|
||||
/// The client's return address with the answer's parameters.
|
||||
fn answer(redirect_uri: &str, pairs: &[(&str, &str)]) -> ApiResult<String> {
|
||||
let mut url = reqwest::Url::parse(redirect_uri).map_err(|_| bad("Hibás visszatérési cím."))?;
|
||||
{
|
||||
let mut query = url.query_pairs_mut();
|
||||
for (key, value) in pairs {
|
||||
query.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
Ok(url.to_string())
|
||||
}
|
||||
|
||||
/// The admin approved (or refused) the connection: the address to send the
|
||||
/// browser back to the client with a code (or an error). A session only:
|
||||
/// an MCP client's token cannot make new tokens.
|
||||
pub async fn authorize(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(p), _): Body<AuthorizeParams>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
if !auth.user.has_role(Role::Admin) {
|
||||
return Err(ApiError::Forbidden("Ehhez admin fiók kell.".into()));
|
||||
}
|
||||
let c = check(&state, &p).await?;
|
||||
let iss = state.config.public_base_url.as_str();
|
||||
let mut pairs: Vec<(&str, &str)> = Vec::new();
|
||||
let code = db::new_token();
|
||||
if p.deny {
|
||||
pairs.push(("error", "access_denied"));
|
||||
} else {
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(db::token_hash(&code))
|
||||
.bind(&c.client_id)
|
||||
.bind(auth.id())
|
||||
.bind(&c.redirect_uri)
|
||||
.bind(&c.code_challenge)
|
||||
.bind(SCOPE)
|
||||
.bind(&state.config.mcp_resource_url)
|
||||
.bind(OffsetDateTime::now_utc() + CODE_TTL)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(client = %c.client_id, user = %auth.id(), "oauth connection approved");
|
||||
pairs.push(("code", &code));
|
||||
}
|
||||
if let Some(s) = &c.state {
|
||||
pairs.push(("state", s));
|
||||
}
|
||||
pairs.push(("iss", iss));
|
||||
Ok(Json(json!({ "redirect_to": answer(&c.redirect_uri, &pairs)? })))
|
||||
}
|
||||
|
||||
// --- tokens ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenRequest {
|
||||
grant_type: Option<String>,
|
||||
code: Option<String>,
|
||||
redirect_uri: Option<String>,
|
||||
code_verifier: Option<String>,
|
||||
refresh_token: Option<String>,
|
||||
client_id: Option<String>,
|
||||
client_secret: Option<String>,
|
||||
resource: Option<String>,
|
||||
}
|
||||
|
||||
/// The client of a token or revocation request: HTTP Basic, the form's
|
||||
/// `client_id` and `client_secret`, or a public client's `client_id` alone.
|
||||
async fn client_of(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
client_id: Option<&str>,
|
||||
client_secret: Option<&str>,
|
||||
) -> Result<String, OauthError> {
|
||||
let basic = headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Basic "))
|
||||
.and_then(|b| STANDARD.decode(b.trim()).ok())
|
||||
.and_then(|b| String::from_utf8(b).ok())
|
||||
.and_then(|s| s.split_once(':').map(|(id, secret)| (id.to_string(), secret.to_string())));
|
||||
let (id, secret) = match basic {
|
||||
Some((id, secret)) => (id, Some(secret)),
|
||||
None => (
|
||||
client_id.ok_or_else(|| OauthError::new("invalid_client", "Unknown client."))?.to_string(),
|
||||
client_secret.map(str::to_string),
|
||||
),
|
||||
};
|
||||
let row: Option<(Option<Vec<u8>>,)> = sqlx::query_as("SELECT secret_hash FROM oauth_clients WHERE id = $1")
|
||||
.bind(&id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
match row {
|
||||
None => return Err(OauthError::new("invalid_client", "Unknown client.")),
|
||||
Some((Some(hash),)) if secret.as_deref().map(db::token_hash).as_ref() != Some(&hash) => {
|
||||
return Err(OauthError::new("invalid_client", "Wrong client secret."));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
sqlx::query("UPDATE oauth_clients SET last_used_at = now() WHERE id = $1").bind(&id).execute(&state.db).await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// PKCE: the verifier's SHA-256, base64url, is the challenge (RFC 7636).
|
||||
fn pkce_ok(verifier: &str, challenge: &str) -> bool {
|
||||
(43..=128).contains(&verifier.len())
|
||||
&& verifier.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
|
||||
&& URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) == challenge
|
||||
}
|
||||
|
||||
/// A new access and refresh token for a connection.
|
||||
async fn issue(tx: &mut sqlx::PgConnection, grant_id: Uuid) -> Result<Response, OauthError> {
|
||||
let (access, refresh) = (db::new_token(), db::new_token());
|
||||
let now = OffsetDateTime::now_utc();
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(grant_id)
|
||||
.bind(db::token_hash(&access))
|
||||
.bind(now + ACCESS_TTL)
|
||||
.bind(db::token_hash(&refresh))
|
||||
.bind(now + REFRESH_TTL)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let body = json!({
|
||||
"access_token": access,
|
||||
"token_type": "Bearer",
|
||||
"expires_in": ACCESS_TTL.whole_seconds(),
|
||||
"refresh_token": refresh,
|
||||
"scope": SCOPE,
|
||||
});
|
||||
Ok((StatusCode::OK, [(CACHE_CONTROL, "no-store"), (PRAGMA, "no-cache")], Json(body)).into_response())
|
||||
}
|
||||
|
||||
async fn revoke_grant(tx: &mut sqlx::PgConnection, grant_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL")
|
||||
.bind(grant_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn still_admin(tx: &mut sqlx::PgConnection, user_id: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT 'admin' = ANY(roles) FROM users WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map(|r| r.unwrap_or(false))
|
||||
}
|
||||
|
||||
fn invalid_grant(description: &str) -> OauthError {
|
||||
OauthError::new("invalid_grant", description)
|
||||
}
|
||||
|
||||
pub async fn token(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Form(req), _): WithRejection<Form<TokenRequest>, OauthError>,
|
||||
) -> Result<Response, OauthError> {
|
||||
state.oauth_limiter.hit(&format!("token:{}", client_ip(&headers).unwrap_or_default()))?;
|
||||
let client = client_of(&state, &headers, req.client_id.as_deref(), req.client_secret.as_deref()).await?;
|
||||
match req.grant_type.as_deref() {
|
||||
Some("authorization_code") => code_grant(&state, &client, &req).await,
|
||||
Some("refresh_token") => refresh_grant(&state, &client, &req).await,
|
||||
_ => Err(OauthError::new("unsupported_grant_type", "Use authorization_code or refresh_token.")),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct CodeRow {
|
||||
client_id: String,
|
||||
user_id: Uuid,
|
||||
redirect_uri: String,
|
||||
code_challenge: String,
|
||||
scope: String,
|
||||
resource: Option<String>,
|
||||
expires_at: OffsetDateTime,
|
||||
used_at: Option<OffsetDateTime>,
|
||||
grant_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
async fn code_grant(state: &AppState, client: &str, req: &TokenRequest) -> Result<Response, OauthError> {
|
||||
let code = req.code.as_deref().ok_or_else(|| OauthError::new("invalid_request", "The code is missing."))?;
|
||||
let verifier = req
|
||||
.code_verifier
|
||||
.as_deref()
|
||||
.ok_or_else(|| OauthError::new("invalid_request", "The code_verifier is missing."))?;
|
||||
let code_hash = db::token_hash(code);
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: Option<CodeRow> = sqlx::query_as(
|
||||
"SELECT client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at, used_at, grant_id \
|
||||
FROM oauth_codes WHERE code_hash = $1 FOR UPDATE",
|
||||
)
|
||||
.bind(&code_hash)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(row) = row.filter(|r| r.client_id == client) else { return Err(invalid_grant("Unknown code.")) };
|
||||
if row.used_at.is_some() {
|
||||
// A code sent twice may have been stolen: the connection made with it ends.
|
||||
if let Some(grant_id) = row.grant_id {
|
||||
revoke_grant(&mut tx, grant_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::warn!(client, grant = %grant_id, "oauth code used twice: connection revoked");
|
||||
}
|
||||
return Err(invalid_grant("The code was already used."));
|
||||
}
|
||||
if row.expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(invalid_grant("The code has expired."));
|
||||
}
|
||||
if req.redirect_uri.as_deref() != Some(row.redirect_uri.as_str()) {
|
||||
return Err(invalid_grant("The redirect_uri does not match."));
|
||||
}
|
||||
if !pkce_ok(verifier, &row.code_challenge) {
|
||||
return Err(invalid_grant("Wrong code_verifier."));
|
||||
}
|
||||
if let (Some(asked), Some(granted)) = (&req.resource, &row.resource)
|
||||
&& !same_resource(asked, granted)
|
||||
{
|
||||
return Err(OauthError::new("invalid_target", "Unknown resource."));
|
||||
}
|
||||
if !still_admin(&mut tx, row.user_id).await? {
|
||||
return Err(invalid_grant("The approver is no longer an admin."));
|
||||
}
|
||||
let grant_id = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope, resource) VALUES ($1, $2, $3, $4, $5)")
|
||||
.bind(grant_id)
|
||||
.bind(client)
|
||||
.bind(row.user_id)
|
||||
.bind(&row.scope)
|
||||
.bind(&row.resource)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("UPDATE oauth_codes SET used_at = now(), grant_id = $2 WHERE code_hash = $1")
|
||||
.bind(&code_hash)
|
||||
.bind(grant_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let response = issue(&mut tx, grant_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::info!(client, grant = %grant_id, user = %row.user_id, "oauth connection made");
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct RefreshRow {
|
||||
id: Uuid,
|
||||
grant_id: Uuid,
|
||||
client_id: String,
|
||||
user_id: Uuid,
|
||||
refresh_expires_at: OffsetDateTime,
|
||||
refreshed_at: Option<OffsetDateTime>,
|
||||
revoked_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
async fn refresh_grant(state: &AppState, client: &str, req: &TokenRequest) -> Result<Response, OauthError> {
|
||||
let refresh = req
|
||||
.refresh_token
|
||||
.as_deref()
|
||||
.ok_or_else(|| OauthError::new("invalid_request", "The refresh_token is missing."))?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: Option<RefreshRow> = sqlx::query_as(
|
||||
"SELECT t.id, t.grant_id, g.client_id, g.user_id, t.refresh_expires_at, t.refreshed_at, g.revoked_at \
|
||||
FROM oauth_tokens t JOIN oauth_grants g ON g.id = t.grant_id \
|
||||
WHERE t.refresh_hash = $1 FOR UPDATE OF t, g",
|
||||
)
|
||||
.bind(db::token_hash(refresh))
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(row) = row.filter(|r| r.client_id == client) else { return Err(invalid_grant("Unknown refresh token.")) };
|
||||
if row.revoked_at.is_some() {
|
||||
return Err(invalid_grant("The connection was revoked."));
|
||||
}
|
||||
if row.refreshed_at.is_some() {
|
||||
// An old refresh token again: it may have been stolen, so the connection ends.
|
||||
revoke_grant(&mut tx, row.grant_id).await?;
|
||||
tx.commit().await?;
|
||||
tracing::warn!(client, grant = %row.grant_id, "oauth refresh token reused: connection revoked");
|
||||
return Err(invalid_grant("The refresh token was already used."));
|
||||
}
|
||||
if row.refresh_expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(invalid_grant("The refresh token has expired."));
|
||||
}
|
||||
if !still_admin(&mut tx, row.user_id).await? {
|
||||
return Err(invalid_grant("The approver is no longer an admin."));
|
||||
}
|
||||
sqlx::query("UPDATE oauth_tokens SET refreshed_at = now() WHERE id = $1").bind(row.id).execute(&mut *tx).await?;
|
||||
let response = issue(&mut tx, row.grant_id).await?;
|
||||
tx.commit().await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RevokeRequest {
|
||||
token: Option<String>,
|
||||
client_id: Option<String>,
|
||||
client_secret: Option<String>,
|
||||
}
|
||||
|
||||
/// RFC 7009: either token of a connection ends the whole connection.
|
||||
pub async fn revoke(
|
||||
State(state): St,
|
||||
headers: HeaderMap,
|
||||
WithRejection(Form(req), _): WithRejection<Form<RevokeRequest>, OauthError>,
|
||||
) -> Result<StatusCode, OauthError> {
|
||||
let client = client_of(&state, &headers, req.client_id.as_deref(), req.client_secret.as_deref()).await?;
|
||||
if let Some(token) = req.token {
|
||||
let hash = db::token_hash(&token);
|
||||
sqlx::query(
|
||||
"UPDATE oauth_grants g SET revoked_at = now() FROM oauth_tokens t \
|
||||
WHERE t.grant_id = g.id AND g.client_id = $2 AND g.revoked_at IS NULL \
|
||||
AND (t.access_hash = $1 OR t.refresh_hash = $1)",
|
||||
)
|
||||
.bind(hash)
|
||||
.bind(&client)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
}
|
||||
Ok(StatusCode::OK)
|
||||
}
|
||||
|
||||
// --- the MCP server's check -------------------------------------------------------------
|
||||
|
||||
/// Guard: an MCP client's access token of an admin (not a session).
|
||||
pub struct McpClient(AuthUser);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for McpClient {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let user = oauth_user(parts, state).await?.ok_or(ApiError::Unauthorized)?;
|
||||
user.require(Role::Admin)?;
|
||||
Ok(McpClient(user))
|
||||
}
|
||||
}
|
||||
|
||||
/// Who the token belongs to and what it is for (the MCP server checks the
|
||||
/// resource; no personal data).
|
||||
pub async fn whoami(McpClient(user): McpClient) -> Json<Value> {
|
||||
let access = user.oauth.as_ref();
|
||||
Json(json!({
|
||||
"user_id": user.id(),
|
||||
"roles": user.user.roles,
|
||||
"grant_id": access.map(|a| a.grant_id),
|
||||
"scope": access.map(|a| a.scope.as_str()),
|
||||
"resource": access.and_then(|a| a.resource.as_deref()),
|
||||
}))
|
||||
}
|
||||
|
||||
// --- the admin's list of connections -------------------------------------------------------
|
||||
|
||||
/// A connection: id, client name, its return addresses, the admin's e-mail, made, last used.
|
||||
type GrantRow = (Uuid, String, Vec<String>, String, OffsetDateTime, Option<OffsetDateTime>);
|
||||
|
||||
/// The connections in use (a session only: a client cannot see or end them).
|
||||
pub async fn admin_grants(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
auth.require(Role::Admin)?;
|
||||
let rows: Vec<GrantRow> = sqlx::query_as(
|
||||
"SELECT g.id, c.name, c.redirect_uris, u.email, g.created_at, g.last_used_at \
|
||||
FROM oauth_grants g JOIN oauth_clients c ON c.id = g.client_id JOIN users u ON u.id = g.user_id \
|
||||
WHERE g.revoked_at IS NULL \
|
||||
AND EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.grant_id = g.id AND t.refresh_expires_at > now()) \
|
||||
ORDER BY g.created_at DESC",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let grants: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, client, uris, email, created, used)| {
|
||||
let host =
|
||||
uris.first().and_then(|u| reqwest::Url::parse(u).ok()).and_then(|u| u.host_str().map(String::from));
|
||||
json!({
|
||||
"id": id,
|
||||
"client_name": client,
|
||||
"redirect_host": host,
|
||||
"user_email": email,
|
||||
"created_at": rfc3339(created),
|
||||
"last_used_at": rfc3339_opt(used),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({ "grants": grants })))
|
||||
}
|
||||
|
||||
pub async fn admin_revoke_grant(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): super::IdPath,
|
||||
) -> ApiResult<StatusCode> {
|
||||
auth.require(Role::Admin)?;
|
||||
let done = sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL")
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if done.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("connection"));
|
||||
}
|
||||
tracing::info!(grant = %id, by = %auth.id(), "oauth connection revoked by an admin");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn redirect_addresses() {
|
||||
let allowed: Vec<String> = crate::config::DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec();
|
||||
for ok in [
|
||||
"https://claude.ai/api/mcp/auth_callback",
|
||||
"https://claude.com/api/mcp/auth_callback",
|
||||
"http://localhost:53682/callback",
|
||||
"http://127.0.0.1:8080",
|
||||
"http://localhost:3000/cb?x=1",
|
||||
] {
|
||||
assert!(redirect_allowed(ok, &allowed), "{ok}");
|
||||
}
|
||||
for no in [
|
||||
"https://claude.ai/api/mcp/auth_callback/x",
|
||||
"https://evil.example/api/mcp/auth_callback",
|
||||
"http://localhost:80@evil.example/",
|
||||
"http://localhost.evil.example:80/",
|
||||
"http://localhost:/cb",
|
||||
"http://localhost:123456/",
|
||||
"https://claude.ai/api/mcp/auth_callback#frag",
|
||||
"javascript:alert(1)",
|
||||
] {
|
||||
assert!(!redirect_allowed(no, &allowed), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkce() {
|
||||
// A verifier and its challenge (base64url of the SHA-256).
|
||||
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWZOEjXk";
|
||||
assert!(pkce_ok(verifier, "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII"));
|
||||
assert!(!pkce_ok(verifier, "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reIX"));
|
||||
assert!(!pkce_ok("short", "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Admin → Statisztika: `GET /v1/admin/stats?days=30`. Sign-ups, own charts,
|
||||
//! analyses, purchases and the weekly horoscope's readers, day by day in
|
||||
//! Hungarian time, the way from sign-up to purchase, and where the members
|
||||
//! came from. Members are counted without the admins; money is every live
|
||||
//! Stripe payment. A few queries over the database, only when an admin opens
|
||||
//! the page.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::{Date, OffsetDateTime};
|
||||
|
||||
use super::St;
|
||||
use crate::auth::AdminUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::packages;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct StatsQuery {
|
||||
/// The last this many days with today; 0: since the first member.
|
||||
days: Option<i64>,
|
||||
}
|
||||
|
||||
/// Not an admin (`u`: the users row).
|
||||
const MEMBER: &str = "NOT ('admin' = ANY(u.roles))";
|
||||
/// The analyses a member orders (summaries and weekly texts come by themselves).
|
||||
const ORDERED: &str = "('natal', 'synastry', 'forecast', 'tarot')";
|
||||
|
||||
/// The headline numbers between `$1` and `$2`.
|
||||
fn kpi_sql() -> String {
|
||||
format!(
|
||||
"SELECT json_build_object(\
|
||||
'signups', (SELECT count(*) FROM users u WHERE {MEMBER} AND u.created_at >= $1 AND u.created_at < $2), \
|
||||
'own_charts', (SELECT count(*) FROM (SELECT min(c.created_at) AS first FROM charts c \
|
||||
JOIN users u ON u.id = c.owner_id WHERE c.kind = 'own' AND {MEMBER} GROUP BY c.owner_id) f \
|
||||
WHERE first >= $1 AND first < $2), \
|
||||
'analyses', (SELECT count(*) FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind IN {ORDERED} AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2), \
|
||||
'questions', (SELECT count(*) FROM questions q JOIN users u ON u.id = q.asked_by \
|
||||
WHERE {MEMBER} AND q.created_at >= $1 AND q.created_at < $2), \
|
||||
'orders', (SELECT count(*) FROM stripe_checkouts WHERE live AND completed_at >= $1 AND completed_at < $2), \
|
||||
'buyers', (SELECT count(DISTINCT user_id) FROM stripe_checkouts \
|
||||
WHERE live AND completed_at >= $1 AND completed_at < $2), \
|
||||
'revenue_huf', (SELECT COALESCE(sum(price_huf), 0) FROM stripe_checkouts \
|
||||
WHERE live AND completed_at >= $1 AND completed_at < $2), \
|
||||
'refunded_huf', (SELECT COALESCE(sum(c.price_huf), 0) FROM gifts g JOIN stripe_checkouts c ON c.gift_id = g.id \
|
||||
WHERE c.live AND g.refunded_at >= $1 AND g.refunded_at < $2), \
|
||||
'weekly_readers', (SELECT count(DISTINCT a.requested_by) FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind = 'weekly' AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2), \
|
||||
'forum_posts', (SELECT count(*) FROM forum.posts p JOIN users u ON u.id = p.author_id \
|
||||
WHERE {MEMBER} AND p.deleted_at IS NULL AND p.created_at >= $1 AND p.created_at < $2), \
|
||||
'ai_cost_usd', (SELECT COALESCE(sum(cost_usd), 0) FROM ( \
|
||||
SELECT cost_usd FROM analyses WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT cost_usd FROM questions WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT cost_usd FROM prompt_previews WHERE created_at >= $1 AND created_at < $2) x))"
|
||||
)
|
||||
}
|
||||
|
||||
/// One row a day from `$3` to `$4` (dates in Hungarian time).
|
||||
fn daily_sql() -> String {
|
||||
let day = |col: &str| format!("({col} AT TIME ZONE 'Europe/Budapest')::date");
|
||||
format!(
|
||||
"WITH days AS (SELECT d::date AS day FROM generate_series($3::date, $4::date, interval '1 day') d), \
|
||||
signups AS (SELECT {u} AS day, count(*) AS n FROM users u \
|
||||
WHERE {MEMBER} AND u.created_at >= $1 AND u.created_at < $2 GROUP BY 1), \
|
||||
own AS (SELECT {first} AS day, count(*) AS n FROM (SELECT min(c.created_at) AS first FROM charts c \
|
||||
JOIN users u ON u.id = c.owner_id WHERE c.kind = 'own' AND {MEMBER} GROUP BY c.owner_id) f \
|
||||
WHERE first >= $1 AND first < $2 GROUP BY 1), \
|
||||
ordered AS (SELECT {a} AS day, count(*) AS n FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind IN {ORDERED} AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2 GROUP BY 1), \
|
||||
asked AS (SELECT {q} AS day, count(*) AS n FROM questions q JOIN users u ON u.id = q.asked_by \
|
||||
WHERE {MEMBER} AND q.created_at >= $1 AND q.created_at < $2 GROUP BY 1), \
|
||||
paid AS (SELECT {c} AS day, count(*) AS n, sum(price_huf) AS huf FROM stripe_checkouts \
|
||||
WHERE live AND completed_at >= $1 AND completed_at < $2 GROUP BY 1), \
|
||||
weekly AS (SELECT {a} AS day, count(DISTINCT a.requested_by) AS n FROM analyses a \
|
||||
JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind = 'weekly' AND {MEMBER} AND a.created_at >= $1 AND a.created_at < $2 GROUP BY 1), \
|
||||
posts AS (SELECT {p} AS day, count(*) AS n FROM forum.posts p JOIN users u ON u.id = p.author_id \
|
||||
WHERE {MEMBER} AND p.deleted_at IS NULL AND p.created_at >= $1 AND p.created_at < $2 GROUP BY 1) \
|
||||
SELECT COALESCE(json_agg(json_build_object(\
|
||||
'date', d.day, 'signups', COALESCE(s.n, 0), 'own_charts', COALESCE(o.n, 0), \
|
||||
'analyses', COALESCE(an.n, 0), 'questions', COALESCE(q.n, 0), 'orders', COALESCE(pd.n, 0), \
|
||||
'revenue_huf', COALESCE(pd.huf, 0), 'weekly_readers', COALESCE(w.n, 0), 'forum_posts', COALESCE(fp.n, 0)\
|
||||
) ORDER BY d.day), '[]') \
|
||||
FROM days d LEFT JOIN signups s USING (day) LEFT JOIN own o USING (day) LEFT JOIN ordered an USING (day) \
|
||||
LEFT JOIN asked q USING (day) LEFT JOIN paid pd USING (day) LEFT JOIN weekly w USING (day) \
|
||||
LEFT JOIN posts fp USING (day)",
|
||||
u = day("u.created_at"),
|
||||
first = day("first"),
|
||||
a = day("a.created_at"),
|
||||
q = day("q.created_at"),
|
||||
c = day("completed_at"),
|
||||
p = day("p.created_at"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The members who signed up between `$1` and `$2`: how far each got, and
|
||||
/// where they came from. A shared link or an invitation is the source when
|
||||
/// there was one (it was posted somewhere too, but that is what brought them).
|
||||
fn cohort_sql() -> String {
|
||||
format!(
|
||||
"WITH cohort AS (SELECT \
|
||||
u.email_verified_at IS NOT NULL AS verified, \
|
||||
EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.kind = 'own') AS own_chart, \
|
||||
EXISTS (SELECT 1 FROM analyses a WHERE a.requested_by = u.id AND a.kind IN {ORDERED}) \
|
||||
OR EXISTS (SELECT 1 FROM questions q WHERE q.asked_by = u.id) AS ordered, \
|
||||
EXISTS (SELECT 1 FROM stripe_checkouts s WHERE s.user_id = u.id AND s.live) AS checkout, \
|
||||
EXISTS (SELECT 1 FROM stripe_checkouts s WHERE s.user_id = u.id AND s.live \
|
||||
AND s.completed_at IS NOT NULL) AS bought, \
|
||||
EXISTS (SELECT 1 FROM analyses a WHERE a.requested_by = u.id AND a.kind = 'weekly') AS weekly, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM referrals r WHERE r.user_id = u.id) THEN 'shared' \
|
||||
WHEN EXISTS (SELECT 1 FROM invitations i WHERE i.accepted_by = u.id) \
|
||||
OR EXISTS (SELECT 1 FROM synastry_invites s WHERE s.accepted_by = u.id \
|
||||
AND s.created_at < u.created_at) THEN 'invite' \
|
||||
ELSE COALESCE(u.signup_source, 'unknown') END AS source, \
|
||||
u.signup_detail AS detail, \
|
||||
COALESCE(u.signup_device, 'unknown') AS device, \
|
||||
COALESCE((SELECT i.provider FROM auth_identities i WHERE i.user_id = u.id \
|
||||
ORDER BY i.created_at LIMIT 1), 'unknown') AS method \
|
||||
FROM users u WHERE {MEMBER} AND u.created_at >= $1 AND u.created_at < $2) \
|
||||
SELECT json_build_object(\
|
||||
'funnel', (SELECT json_build_object('signups', count(*), 'verified', count(*) FILTER (WHERE verified), \
|
||||
'own_chart', count(*) FILTER (WHERE own_chart), 'ordered', count(*) FILTER (WHERE ordered), \
|
||||
'checkout', count(*) FILTER (WHERE checkout), 'bought', count(*) FILTER (WHERE bought), \
|
||||
'weekly', count(*) FILTER (WHERE weekly)) FROM cohort), \
|
||||
'sources', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC, x.source), '[]') FROM ( \
|
||||
SELECT source, count(*) AS signups, count(*) FILTER (WHERE own_chart) AS own_chart, \
|
||||
count(*) FILTER (WHERE bought) AS bought FROM cohort GROUP BY source) x), \
|
||||
'details', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC, x.detail), '[]') FROM ( \
|
||||
SELECT detail, count(*) AS signups FROM cohort WHERE detail IS NOT NULL \
|
||||
GROUP BY detail ORDER BY count(*) DESC, detail LIMIT 10) x), \
|
||||
'devices', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC), '[]') FROM ( \
|
||||
SELECT device, count(*) AS signups FROM cohort GROUP BY device) x), \
|
||||
'methods', (SELECT COALESCE(json_agg(x ORDER BY x.signups DESC), '[]') FROM ( \
|
||||
SELECT method, count(*) AS signups FROM cohort GROUP BY method) x))"
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn admin_stats(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Query(query), _): WithRejection<Query<StatsQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let days = query.days.unwrap_or(30);
|
||||
if !(0..=366).contains(&days) {
|
||||
return Err(ApiError::BadRequest("days must be between 0 and 366".into()));
|
||||
}
|
||||
// The period in Hungarian days: its first and last day, and the moments
|
||||
// they start and end; the previous period of the same length before it.
|
||||
let (first_day, today, from, to, previous): (Date, Date, OffsetDateTime, OffsetDateTime, Option<OffsetDateTime>) =
|
||||
sqlx::query_as(
|
||||
"WITH t AS (SELECT (now() AT TIME ZONE 'Europe/Budapest')::date AS today), \
|
||||
p AS (SELECT today, CASE WHEN $1 = 0 \
|
||||
THEN LEAST(today, COALESCE((SELECT min((created_at AT TIME ZONE 'Europe/Budapest')::date) FROM users), today)) \
|
||||
ELSE today - ($1::int - 1) END AS first FROM t) \
|
||||
SELECT first, today, first::timestamp AT TIME ZONE 'Europe/Budapest', \
|
||||
(today + 1)::timestamp AT TIME ZONE 'Europe/Budapest', \
|
||||
CASE WHEN $1 = 0 THEN NULL ELSE (first - $1::int)::timestamp AT TIME ZONE 'Europe/Budapest' END \
|
||||
FROM p",
|
||||
)
|
||||
.bind(days)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
let kpi = kpi_sql();
|
||||
let period: Value = sqlx::query_scalar(&kpi).bind(from).bind(to).fetch_one(&state.db).await?;
|
||||
let before: Option<Value> = match previous {
|
||||
Some(start) => Some(sqlx::query_scalar(&kpi).bind(start).bind(from).fetch_one(&state.db).await?),
|
||||
None => None,
|
||||
};
|
||||
let daily: Value =
|
||||
sqlx::query_scalar(&daily_sql()).bind(from).bind(to).bind(first_day).bind(today).fetch_one(&state.db).await?;
|
||||
let cohort: Value = sqlx::query_scalar(&cohort_sql()).bind(from).bind(to).fetch_one(&state.db).await?;
|
||||
|
||||
// Everything so far.
|
||||
let totals: Value = sqlx::query_scalar(&format!(
|
||||
"SELECT json_build_object(\
|
||||
'members', (SELECT count(*) FROM users u WHERE {MEMBER}), \
|
||||
'own_charts', (SELECT count(*) FROM users u WHERE {MEMBER} \
|
||||
AND EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.is_primary)), \
|
||||
'buyers', (SELECT count(DISTINCT user_id) FROM stripe_checkouts WHERE live AND completed_at IS NOT NULL), \
|
||||
'revenue_huf', (SELECT COALESCE(sum(price_huf), 0) FROM stripe_checkouts WHERE live AND completed_at IS NOT NULL), \
|
||||
'weekly_subscribers', (SELECT count(*) FROM users u WHERE {MEMBER} AND u.weekly_email \
|
||||
AND EXISTS (SELECT 1 FROM charts c WHERE c.owner_id = u.id AND c.is_primary)), \
|
||||
'forum_members', (SELECT count(*) FROM forum.members m JOIN users u ON u.id = m.user_id WHERE {MEMBER}))"
|
||||
))
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
// Purchases in the period by package (gifts apart).
|
||||
let mut packages_sold: Value = sqlx::query_scalar(
|
||||
"SELECT COALESCE(json_agg(x ORDER BY x.revenue_huf DESC, x.package), '[]') FROM ( \
|
||||
SELECT package, gift_id IS NOT NULL AS gift, count(*) AS orders, sum(price_huf) AS revenue_huf \
|
||||
FROM stripe_checkouts WHERE live AND completed_at >= $1 AND completed_at < $2 GROUP BY 1, 2) x",
|
||||
)
|
||||
.bind(from)
|
||||
.bind(to)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if let Some(rows) = packages_sold.as_array_mut() {
|
||||
for row in rows {
|
||||
let name = row["package"].as_str().and_then(packages::find).map(|p| p.name);
|
||||
row["name"] = json!(name);
|
||||
}
|
||||
}
|
||||
|
||||
// What the AI wrote in the period, and what it cost (everyone's, admins' too).
|
||||
let content: Value = sqlx::query_scalar(
|
||||
"SELECT COALESCE(json_agg(x ORDER BY x.done DESC, x.kind), '[]') FROM ( \
|
||||
SELECT kind, count(*) FILTER (WHERE status = 'done') AS done, \
|
||||
count(*) FILTER (WHERE status = 'failed') AS failed, COALESCE(sum(cost_usd), 0) AS cost_usd \
|
||||
FROM ( \
|
||||
SELECT kind, status, cost_usd FROM analyses WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT 'question', status, cost_usd FROM questions WHERE created_at >= $1 AND created_at < $2 \
|
||||
UNION ALL SELECT 'preview', status, cost_usd FROM prompt_previews WHERE created_at >= $1 AND created_at < $2 \
|
||||
) a GROUP BY kind) x",
|
||||
)
|
||||
.bind(from)
|
||||
.bind(to)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
// The weekly horoscope week by week since its first week (the last 12):
|
||||
// members who read it, and the Monday e-mails sent.
|
||||
let weekly: Value = sqlx::query_scalar(&format!(
|
||||
"WITH weeks AS (SELECT w::date AS week_start FROM generate_series( \
|
||||
GREATEST((SELECT min(week_start) FROM analyses WHERE kind = 'weekly'), \
|
||||
date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date - 77), \
|
||||
date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date, interval '7 days') w \
|
||||
WHERE EXISTS (SELECT 1 FROM analyses WHERE kind = 'weekly')) \
|
||||
SELECT COALESCE(json_agg(json_build_object('week_start', w.week_start, \
|
||||
'readers', (SELECT count(DISTINCT a.requested_by) FROM analyses a JOIN users u ON u.id = a.requested_by \
|
||||
WHERE a.kind = 'weekly' AND a.week_start = w.week_start AND {MEMBER}), \
|
||||
'emails', (SELECT count(*) FROM email_outbox e WHERE e.template = 'weekly_horoscope' \
|
||||
AND e.sent_at IS NOT NULL AND e.payload->>'week_start' = w.week_start::text)) \
|
||||
ORDER BY w.week_start DESC), '[]') FROM weeks w"
|
||||
))
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"days": days,
|
||||
"from": first_day.to_string(),
|
||||
"to": today.to_string(),
|
||||
"totals": totals,
|
||||
"period": period,
|
||||
"previous": before,
|
||||
"daily": daily,
|
||||
"cohort": cohort,
|
||||
"packages": packages_sold,
|
||||
"content": content,
|
||||
"weekly": weekly,
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! The free weekly horoscope of the member's own chart: the week's sky (from
|
||||
//! the horoscope service, stored per chart and week in `weekly_skies`) and its
|
||||
//! text (an analysis of kind `weekly`, written by the summary's model). It is
|
||||
//! asked for when the weekly horoscope page opens, so it is only written for
|
||||
//! those who look; Monday's e-mail (worker; on unless turned off) says no
|
||||
//! more than that it is there. The page shows one month at a time, the
|
||||
//! newest week first ([`history`]).
|
||||
//!
|
||||
//! Weeks run from Monday to Sunday, Hungarian time.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Query, State};
|
||||
use axum_extra::extract::WithRejection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::Date;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::analyses::{ANALYSIS_COLUMNS, AnalysisRow, Target, queue};
|
||||
use super::charts::{ChartRow, owned_chart};
|
||||
use super::{Body, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
/// The Monday of the current week in Hungary.
|
||||
pub(super) const THIS_MONDAY: &str = "SELECT date_trunc('week', now() AT TIME ZONE 'Europe/Budapest')::date";
|
||||
|
||||
/// What a weekly text is about, for its cache key: the chart and the week.
|
||||
pub fn target_hash(chart_hash: &str, week_start: &str) -> String {
|
||||
format!("{chart_hash}|week|{week_start}")
|
||||
}
|
||||
|
||||
/// The week's sky on the chart, calculated once per chart, birth data and week.
|
||||
async fn ensure_sky(state: &AppState, chart: &ChartRow, week: Date) -> Result<(), ApiError> {
|
||||
let (exists,): (bool,) = sqlx::query_as(
|
||||
"SELECT EXISTS (SELECT 1 FROM weekly_skies WHERE chart_id = $1 AND chart_hash = $2 AND week_start = $3)",
|
||||
)
|
||||
.bind(chart.id)
|
||||
.bind(&chart.chart_hash)
|
||||
.bind(week)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if exists {
|
||||
return Ok(());
|
||||
}
|
||||
let mut result = state.horoscope.week(&json!({ "birth": chart.birth_data, "start": week.to_string() })).await?;
|
||||
if let Some(obj) = result.as_object_mut() {
|
||||
obj.remove("meta");
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO weekly_skies (chart_id, chart_hash, week_start, result) VALUES ($1, $2, $3, $4) \
|
||||
ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(chart.id)
|
||||
.bind(&chart.chart_hash)
|
||||
.bind(week)
|
||||
.bind(&result)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn weekly_email(state: &AppState, user: Uuid) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query_scalar("SELECT weekly_email FROM users WHERE id = $1").bind(user).fetch_one(&state.db).await
|
||||
}
|
||||
|
||||
/// This week's horoscope of the own chart: queued if it does not exist yet
|
||||
/// (or the last attempt failed); the page polls this until it is written.
|
||||
pub async fn current(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||||
let chart_id: Option<Uuid> = sqlx::query_scalar("SELECT id FROM charts WHERE owner_id = $1 AND is_primary")
|
||||
.bind(auth.id())
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
let chart = owned_chart(&state.db, chart_id.ok_or(ApiError::NotFound("chart"))?, auth.id()).await?;
|
||||
let week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?;
|
||||
ensure_sky(&state, &chart, week).await?;
|
||||
let target = Target::Weekly {
|
||||
chart_id: chart.id,
|
||||
hash: target_hash(&chart.chart_hash, &week.to_string()),
|
||||
week_start: week,
|
||||
};
|
||||
let (_, row) = queue(&state, auth.id(), &target, &auth.user.locale, None).await?;
|
||||
let end = week.saturating_add(time::Duration::days(6));
|
||||
Ok(Json(json!({
|
||||
"week_start": week.to_string(),
|
||||
"week_end": end.to_string(),
|
||||
"analysis": row.view(),
|
||||
"email": weekly_email(&state, auth.id()).await?,
|
||||
})))
|
||||
}
|
||||
|
||||
/// "2026-11".
|
||||
fn month_key(date: Date) -> String {
|
||||
format!("{:04}-{:02}", date.year(), u8::from(date.month()))
|
||||
}
|
||||
|
||||
/// The first day of a "2026-11" month.
|
||||
fn month_start(key: &str) -> Option<Date> {
|
||||
let (y, m) = key.split_once('-')?;
|
||||
let month = time::Month::try_from(m.parse::<u8>().ok()?).ok()?;
|
||||
Date::from_calendar_date(y.parse().ok()?, month, 1).ok()
|
||||
}
|
||||
|
||||
fn next_month(first: Date) -> Date {
|
||||
let (y, m) = (first.year(), first.month());
|
||||
let y = if m == time::Month::December { y + 1 } else { y };
|
||||
Date::from_calendar_date(y, m.next(), 1).expect("the first of a month")
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MonthQuery {
|
||||
/// "2026-11"; this month by default.
|
||||
month: Option<String>,
|
||||
}
|
||||
|
||||
/// One month of the member's weekly horoscopes (weeks counted by their
|
||||
/// Monday), the newest first, and the months before and after that have any.
|
||||
/// Only weeks the member opened have a text.
|
||||
pub async fn history(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Query(q), _): WithRejection<Query<MonthQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let this_week: Date = sqlx::query_scalar(THIS_MONDAY).fetch_one(&state.db).await?;
|
||||
let current = month_start(&month_key(this_week)).expect("a valid month");
|
||||
let first = match q.month.as_deref() {
|
||||
Some(m) => month_start(m).ok_or_else(|| ApiError::BadRequest("month must look like 2026-11".into()))?,
|
||||
None => current,
|
||||
}
|
||||
.min(current);
|
||||
let next = next_month(first);
|
||||
// Every own chart counts: the birth data may have changed meanwhile.
|
||||
const MINE: &str = "kind = 'weekly' AND chart_id IN (SELECT id FROM charts WHERE owner_id = $1 AND kind = 'own')";
|
||||
let rows: Vec<AnalysisRow> = sqlx::query_as(&format!(
|
||||
"SELECT DISTINCT ON (week_start) {ANALYSIS_COLUMNS} FROM analyses \
|
||||
WHERE {MINE} AND week_start >= $2 AND week_start < $3 \
|
||||
ORDER BY week_start DESC, (status = 'done') DESC, created_at DESC"
|
||||
))
|
||||
.bind(auth.id())
|
||||
.bind(first)
|
||||
.bind(next)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
let (older, newer): (Option<Date>, Option<Date>) = sqlx::query_as(&format!(
|
||||
"SELECT (SELECT max(week_start) FROM analyses WHERE {MINE} AND week_start < $2), \
|
||||
(SELECT min(week_start) FROM analyses WHERE {MINE} AND week_start >= $3)"
|
||||
))
|
||||
.bind(auth.id())
|
||||
.bind(first)
|
||||
.bind(next)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
// This month always has a page (its week is written when it opens).
|
||||
let newer = newer.map(month_key).or_else(|| (first < current).then(|| month_key(current)));
|
||||
let weeks: Vec<Value> = rows
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
let start = r.week_start?;
|
||||
Some(json!({
|
||||
"week_start": start.to_string(),
|
||||
"week_end": start.saturating_add(time::Duration::days(6)).to_string(),
|
||||
"analysis": r.view(),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(json!({
|
||||
"month": month_key(first),
|
||||
"current_month": month_key(current),
|
||||
"this_week": this_week.to_string(),
|
||||
"weeks": weeks,
|
||||
"older": older.map(month_key),
|
||||
"newer": newer,
|
||||
"email": weekly_email(&state, auth.id()).await?,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct EmailSwitch {
|
||||
on: bool,
|
||||
}
|
||||
|
||||
/// Turns Monday's e-mail on or off. Turned on, the first one comes next
|
||||
/// Monday (this week's horoscope is already in front of the member).
|
||||
pub(super) fn switch_sql() -> String {
|
||||
// Only a change from off to on moves the date: saving "on" again must not
|
||||
// hold back this Monday's e-mail.
|
||||
format!(
|
||||
"UPDATE users SET \
|
||||
weekly_email_sent_on = CASE WHEN $2 AND NOT weekly_email \
|
||||
THEN greatest(weekly_email_sent_on, ({THIS_MONDAY})) \
|
||||
ELSE weekly_email_sent_on END, \
|
||||
weekly_email = $2, updated_at = now() \
|
||||
WHERE id = $1"
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn set_email(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Json(req), _): Body<EmailSwitch>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
sqlx::query(&switch_sql()).bind(auth.id()).bind(req.on).execute(&state.db).await?;
|
||||
Ok(Json(json!({ "email": req.on })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenQuery {
|
||||
token: String,
|
||||
}
|
||||
|
||||
/// "No more weekly horoscope e-mails", straight from the mail client's
|
||||
/// unsubscribe button (RFC 8058 one-click POST); the footer link opens the
|
||||
/// page of every e-mail setting ([`super::notifications`]). No login needed.
|
||||
pub async fn unsubscribe(
|
||||
State(state): St,
|
||||
WithRejection(Query(q), _): WithRejection<Query<TokenQuery>, ApiError>,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let token = Uuid::parse_str(q.token.trim()).map_err(|_| ApiError::NotFound("token"))?;
|
||||
let done = sqlx::query("UPDATE users SET weekly_email = false, updated_at = now() WHERE email_token = $1")
|
||||
.bind(token)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
if done.rows_affected() == 0 {
|
||||
return Err(ApiError::NotFound("token"));
|
||||
}
|
||||
Ok(Json(json!({ "unsubscribed": true })))
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! Where a new member came from (`users.signup_source`, `signup_detail`,
|
||||
//! `signup_device`), for the admin statistics. The page sends what it saw
|
||||
//! when the visit began ([`CameFrom`]: the referring site's address and the
|
||||
//! link's campaign tags, kept in the page's memory only); the browser's name
|
||||
//! tells the apps' built-in browsers and the device type. Nothing is kept
|
||||
//! about visitors who do not sign up.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// What the page saw when the visit began, sent with a sign-up.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CameFrom {
|
||||
/// The referring page's address without its path (`l.facebook.com`), or
|
||||
/// an Android app's name (`com.facebook.katana`).
|
||||
#[serde(default)]
|
||||
pub referrer: Option<String>,
|
||||
#[serde(default)]
|
||||
pub utm_source: Option<String>,
|
||||
#[serde(default)]
|
||||
pub utm_medium: Option<String>,
|
||||
#[serde(default)]
|
||||
pub utm_campaign: Option<String>,
|
||||
/// The name of the click id that was on the link: `fbclid`, `gclid` or `ttclid`.
|
||||
#[serde(default)]
|
||||
pub click: Option<String>,
|
||||
/// The app whose built-in browser the visitor left for the phone's own
|
||||
/// browser through the login page's way out (`facebook`, `instagram`…).
|
||||
#[serde(default)]
|
||||
pub app: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Arrival {
|
||||
pub source: &'static str,
|
||||
pub detail: Option<String>,
|
||||
pub device: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Printable text, at most `max` characters, or nothing.
|
||||
fn clean(value: Option<&str>, max: usize) -> Option<String> {
|
||||
let v: String = value?.trim().chars().filter(|c| !c.is_control()).take(max).collect();
|
||||
(!v.is_empty()).then_some(v)
|
||||
}
|
||||
|
||||
/// `host` is `domain` or one of its subdomains.
|
||||
fn is(host: &str, domain: &str) -> bool {
|
||||
host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.'))
|
||||
}
|
||||
|
||||
/// The app of a built-in browser, from the browser's name (as on the login page).
|
||||
fn in_app(ua: &str) -> Option<&'static str> {
|
||||
let lower = ua.to_ascii_lowercase();
|
||||
if lower.contains("instagram") {
|
||||
Some("instagram")
|
||||
} else if lower.contains("messengerforios") || lower.contains("orca-android") || lower.contains("fb_iab/messenger")
|
||||
{
|
||||
Some("messenger")
|
||||
} else if ["FBAN", "FBAV", "FB_IAB", "FBIOS", "FB4A"].iter().any(|m| ua.contains(m)) {
|
||||
Some("facebook")
|
||||
} else if lower.contains("tiktok") || lower.contains("musical_ly") || lower.contains("bytedance") {
|
||||
Some("tiktok")
|
||||
} else if ua.contains("Android") && ua.contains("; wv)") {
|
||||
Some("app")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn device(ua: &str) -> &'static str {
|
||||
if ua.contains("iPad") || ua.contains("Tablet") || (ua.contains("Android") && !ua.contains("Mobile")) {
|
||||
"tablet"
|
||||
} else if ua.contains("Mobi") || ua.contains("iPhone") || ua.contains("Android") {
|
||||
"mobile"
|
||||
} else {
|
||||
"desktop"
|
||||
}
|
||||
}
|
||||
|
||||
/// A campaign tag's source, as the site's own links may write it.
|
||||
fn tagged(source: &str) -> &'static str {
|
||||
let s = source.to_lowercase();
|
||||
if s.contains("facebook") || s == "fb" || s.starts_with("fb_") || s.starts_with("fb-") {
|
||||
"facebook"
|
||||
} else if s.contains("instagram") || s == "ig" {
|
||||
"instagram"
|
||||
} else if s.contains("messenger") {
|
||||
"messenger"
|
||||
} else if s.contains("tiktok") {
|
||||
"tiktok"
|
||||
} else if s.contains("google") {
|
||||
"google"
|
||||
} else if s.contains("bing") {
|
||||
"bing"
|
||||
} else if s.contains("mail") || s.contains("newsletter") || s.contains("hirlevel") || s.contains("hírlevél") {
|
||||
"email"
|
||||
} else {
|
||||
"other"
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of the referring site (`None`: the site itself).
|
||||
fn site(host: &str, own_host: &str) -> Option<&'static str> {
|
||||
let own = own_host.trim_start_matches("www.");
|
||||
if host == "localhost" || (!own.is_empty() && is(host, own)) {
|
||||
return None;
|
||||
}
|
||||
let kind = if is(host, "messenger.com") || host.starts_with("com.facebook.orca") {
|
||||
"messenger"
|
||||
} else if is(host, "facebook.com") || is(host, "fb.com") || host == "fb.me" || host.starts_with("com.facebook.") {
|
||||
"facebook"
|
||||
} else if is(host, "instagram.com") || host.starts_with("com.instagram.") {
|
||||
"instagram"
|
||||
} else if is(host, "tiktok.com") || host.starts_with("com.zhiliaoapp.") || host.starts_with("com.ss.android.") {
|
||||
"tiktok"
|
||||
} else if host.starts_with("mail.")
|
||||
|| host.starts_with("posta.")
|
||||
|| is(host, "outlook.live.com")
|
||||
|| is(host, "outlook.office.com")
|
||||
|| is(host, "freemail.hu")
|
||||
|| is(host, "citromail.hu")
|
||||
|| host == "com.google.android.gm"
|
||||
{
|
||||
"email"
|
||||
} else if host.split('.').any(|label| label == "google")
|
||||
|| host.starts_with("com.google.android.googlequicksearchbox")
|
||||
{
|
||||
"google"
|
||||
} else if is(host, "bing.com") {
|
||||
"bing"
|
||||
} else if ["duckduckgo.com", "yahoo.com", "ecosia.org", "search.brave.com", "startpage.com", "qwant.com"]
|
||||
.iter()
|
||||
.any(|d| is(host, d))
|
||||
|| host.split('.').any(|label| label == "yandex")
|
||||
{
|
||||
"search"
|
||||
} else {
|
||||
"other"
|
||||
};
|
||||
Some(kind)
|
||||
}
|
||||
|
||||
/// The source of a sign-up. In order: the link's campaign tags (the site's
|
||||
/// own links), an app's built-in browser, the app the visitor came out of,
|
||||
/// a click id, the referring site; else typed in or opened from a bookmark
|
||||
/// or an app that hides where it came from (`direct`).
|
||||
pub fn classify(user_agent: Option<&str>, came: Option<&CameFrom>, own_host: &str) -> Arrival {
|
||||
let empty = CameFrom::default();
|
||||
let came = came.unwrap_or(&empty);
|
||||
let referrer = clean(came.referrer.as_deref(), 120).map(|h| h.to_ascii_lowercase());
|
||||
let referrer = referrer.map(|h| h.split(':').next().unwrap_or_default().to_string()).filter(|h| !h.is_empty());
|
||||
let utm: Vec<String> =
|
||||
[("utm_source", &came.utm_source), ("utm_medium", &came.utm_medium), ("utm_campaign", &came.utm_campaign)]
|
||||
.into_iter()
|
||||
.filter_map(|(key, value)| clean(value.as_deref(), 60).map(|v| format!("{key}={v}")))
|
||||
.collect();
|
||||
let referring_site = referrer.as_deref().and_then(|h| site(h, own_host));
|
||||
let ua = user_agent.unwrap_or_default();
|
||||
let app = clean(came.app.as_deref(), 20).and_then(|a| {
|
||||
["facebook", "instagram", "messenger", "tiktok", "app"].into_iter().find(|known| *known == a.to_lowercase())
|
||||
});
|
||||
let click = match came.click.as_deref() {
|
||||
Some("fbclid") => Some("facebook"),
|
||||
Some("gclid") => Some("google"),
|
||||
Some("ttclid") => Some("tiktok"),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let source = clean(came.utm_source.as_deref(), 60)
|
||||
.map(|s| tagged(&s))
|
||||
.or_else(|| in_app(ua))
|
||||
.or(app)
|
||||
.or(click)
|
||||
.or(referring_site)
|
||||
.unwrap_or("direct");
|
||||
let detail = if utm.is_empty() { referring_site.and(referrer) } else { Some(utm.join("&")) };
|
||||
Arrival {
|
||||
source,
|
||||
detail: detail.map(|d| d.chars().take(200).collect()),
|
||||
device: user_agent.filter(|u| !u.is_empty()).map(device),
|
||||
}
|
||||
}
|
||||
|
||||
/// The site's own address without the scheme, port and path.
|
||||
pub fn host_of(base_url: &str) -> String {
|
||||
let rest = base_url.split("://").nth(1).unwrap_or(base_url);
|
||||
rest.split(['/', ':']).next().unwrap_or_default().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FB_ANDROID: &str = "Mozilla/5.0 (Linux; Android 14; SM-A546B Build/UP1A; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/490.0.0.50.82;]";
|
||||
const CHROME_ANDROID: &str = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Mobile Safari/537.36";
|
||||
const MAC: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36";
|
||||
const IPAD: &str = "Mozilla/5.0 (iPad; CPU OS 26_6_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/157.0 Mobile/15E148 Safari/604.1";
|
||||
|
||||
fn came(referrer: Option<&str>) -> CameFrom {
|
||||
CameFrom { referrer: referrer.map(str::to_string), ..CameFrom::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources() {
|
||||
let own = "sorsfonalak.hu";
|
||||
// Facebook's own browser, whatever the referrer says.
|
||||
let a = classify(Some(FB_ANDROID), Some(&came(Some("m.facebook.com"))), own);
|
||||
assert_eq!((a.source, a.detail.as_deref(), a.device), ("facebook", Some("m.facebook.com"), Some("mobile")));
|
||||
// Out of the app through the login page's way out: Chrome, no referrer.
|
||||
let out = CameFrom { app: Some("facebook".into()), ..CameFrom::default() };
|
||||
assert_eq!(classify(Some(CHROME_ANDROID), Some(&out), own).source, "facebook");
|
||||
// Search engines, mail, other sites, the site itself.
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("www.google.com"))), own).source, "google");
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("www.google.co.hu"))), own).source, "google");
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("mail.google.com"))), own).source, "email");
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("duckduckgo.com"))), own).source, "search");
|
||||
let other = classify(Some(MAC), Some(&came(Some("astro-blog.hu"))), own);
|
||||
assert_eq!((other.source, other.detail.as_deref()), ("other", Some("astro-blog.hu")));
|
||||
let internal = classify(Some(MAC), Some(&came(Some("www.sorsfonalak.hu"))), own);
|
||||
assert_eq!((internal.source, internal.detail, internal.device), ("direct", None, Some("desktop")));
|
||||
assert_eq!(classify(Some(MAC), Some(&came(Some("notfacebook.com"))), own).source, "other");
|
||||
// Campaign tags win, and are the detail.
|
||||
let tags = CameFrom {
|
||||
utm_source: Some("fb".into()),
|
||||
utm_campaign: Some("heti".into()),
|
||||
referrer: Some("l.facebook.com".into()),
|
||||
..CameFrom::default()
|
||||
};
|
||||
let a = classify(Some(IPAD), Some(&tags), own);
|
||||
assert_eq!(
|
||||
(a.source, a.detail.as_deref(), a.device),
|
||||
("facebook", Some("utm_source=fb&utm_campaign=heti"), Some("tablet"))
|
||||
);
|
||||
// A click id alone; nothing at all.
|
||||
let click = CameFrom { click: Some("fbclid".into()), ..CameFrom::default() };
|
||||
assert_eq!(classify(Some(CHROME_ANDROID), Some(&click), own).source, "facebook");
|
||||
assert_eq!(classify(None, None, own), Arrival { source: "direct", detail: None, device: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn site_address() {
|
||||
assert_eq!(host_of("https://sorsfonalak.hu"), "sorsfonalak.hu");
|
||||
assert_eq!(host_of("http://localhost:3001/"), "localhost");
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,23 @@ async fn fake_forecast(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
||||
)
|
||||
}
|
||||
|
||||
/// Calls of the fake week endpoint (only `weekly_horoscope_of_the_own_chart` uses it).
|
||||
static WEEK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
async fn fake_week(Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
|
||||
WEEK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let start = body["start"].as_str().unwrap_or("2026-11-30").to_string();
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"timezone": "Europe/Budapest",
|
||||
"week": {"start": start, "end": "?", "contacts": [], "positions": [], "moon_sign": "leo",
|
||||
"moon_ingresses": [], "ingresses": [], "lunations": [], "stations": []},
|
||||
"meta": {}
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// Calls of the fake sky endpoints (only `the_sky_is_shared_and_kept` uses them).
|
||||
static SKY_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
@@ -254,6 +271,7 @@ async fn fake_services_with(s3: FakeS3) -> String {
|
||||
)
|
||||
.route("/v1/synastry", post(fake_synastry))
|
||||
.route("/v1/forecast", post(fake_forecast))
|
||||
.route("/v1/week", post(fake_week))
|
||||
.route(
|
||||
"/v1/sky",
|
||||
get(|| async {
|
||||
@@ -345,6 +363,19 @@ impl TestApp {
|
||||
(status, headers, resp.into_body().collect().await.unwrap().to_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// A form POST (OAuth's token and revocation endpoints), with extra headers.
|
||||
async fn form(&self, uri: &str, body: &str, headers: &[(&str, &str)]) -> Response {
|
||||
let mut req =
|
||||
Request::builder().method("POST").uri(uri).header("content-type", "application/x-www-form-urlencoded");
|
||||
for (name, value) in headers {
|
||||
req = req.header(*name, *value);
|
||||
}
|
||||
let resp = self.router.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
|
||||
let (status, headers) = (resp.status(), resp.headers().clone());
|
||||
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||
Response { status, body: serde_json::from_slice(&bytes).unwrap_or(Value::Null), headers }
|
||||
}
|
||||
|
||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
||||
self.call_with(method, uri, token, body, &[]).await
|
||||
}
|
||||
@@ -1107,7 +1138,7 @@ async fn export_and_delete_account(pool: PgPool) {
|
||||
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||
/// logged-in user, so other apps cannot use them.
|
||||
const PUBLIC_ROUTES: [&str; 24] = [
|
||||
const PUBLIC_ROUTES: [&str; 31] = [
|
||||
"/healthz",
|
||||
// Stripe calls it; the signature proves it.
|
||||
"/v1/payments/stripe/webhook",
|
||||
@@ -1123,6 +1154,9 @@ const PUBLIC_ROUTES: [&str; 24] = [
|
||||
"/v1/public/shares/{slug}/visit",
|
||||
"/v1/public/invites/{token}",
|
||||
"/v1/public/invitations/unsubscribe",
|
||||
// The e-mail settings behind an e-mail's footer link: the token stands for the login.
|
||||
"/v1/public/weekly/unsubscribe",
|
||||
"/v1/public/notifications",
|
||||
"/v1/public/invitations/{token}",
|
||||
"/v1/public/waitlist",
|
||||
// The public birth chart (limited per visitor address).
|
||||
@@ -1136,6 +1170,13 @@ const PUBLIC_ROUTES: [&str; 24] = [
|
||||
// The sky by date, the same for everyone (the moon and retrograde calendars).
|
||||
"/v1/public/sky",
|
||||
"/v1/public/sky/events",
|
||||
// OAuth for the MCP clients (docs/mcp.md): Claude calls these before it has
|
||||
// a token; approving (POST authorize) needs an admin's session.
|
||||
"/v1/oauth/metadata",
|
||||
"/v1/oauth/register",
|
||||
"/v1/oauth/authorize",
|
||||
"/v1/oauth/token",
|
||||
"/v1/oauth/revoke",
|
||||
];
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -1957,6 +1998,155 @@ async fn invitation_only_signup(pool: PgPool) {
|
||||
assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn weekly_horoscope_of_the_own_chart(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let bob = app.register("bob@example.com", "Bob").await;
|
||||
// No own chart yet: nothing to write it from.
|
||||
assert_eq!(app.call("POST", "/v1/weekly", Some(&bob), None).await.status, StatusCode::NOT_FOUND);
|
||||
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||
|
||||
let calls = WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let r = app.call("POST", "/v1/weekly", Some(&anna), None).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let parts: Vec<i32> = r.body["week_start"].as_str().unwrap().split('-').map(|p| p.parse().unwrap()).collect();
|
||||
let month = time::Month::try_from(parts[1] as u8).unwrap();
|
||||
let start = time::Date::from_calendar_date(parts[0], month, parts[2] as u8).unwrap();
|
||||
assert_eq!(start.weekday(), time::Weekday::Monday);
|
||||
assert_eq!(r.body["week_end"], start.saturating_add(time::Duration::days(6)).to_string());
|
||||
let a = &r.body["analysis"];
|
||||
assert_eq!((a["kind"].as_str(), a["status"].as_str()), (Some("weekly"), Some("pending")));
|
||||
assert_eq!((a["chart_id"].as_str(), a["credits_charged"].as_i64()), (chart["id"].as_str(), Some(0)));
|
||||
assert_eq!(a["week_start"], r.body["week_start"]);
|
||||
// On by default.
|
||||
assert_eq!(r.body["email"], true);
|
||||
// Asked again: the same text, the sky calculated once.
|
||||
let again = app.call("POST", "/v1/weekly", Some(&anna), None).await.body;
|
||||
assert_eq!(again["analysis"]["id"], a["id"]);
|
||||
assert_eq!(WEEK_CALLS.load(std::sync::atomic::Ordering::Relaxed), calls + 1);
|
||||
// Written by the summary's model; not among the chart's analyses on its page, but listed.
|
||||
let (weekly_model, summary_model): (String, String) = sqlx::query_as(
|
||||
"SELECT w.model, s.model FROM analyses w JOIN analyses s ON s.chart_id = w.chart_id AND s.kind = 'summary' \
|
||||
WHERE w.kind = 'weekly'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(weekly_model, summary_model);
|
||||
|
||||
// The page: one month at a time, the newest week first; older months page back.
|
||||
let month = app.get("/v1/weekly/history", Some(&anna)).await.body;
|
||||
assert_eq!(month["month"], month["current_month"]);
|
||||
assert_eq!(month["this_week"], r.body["week_start"]);
|
||||
assert_eq!(month["weeks"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(month["weeks"][0]["analysis"]["id"], a["id"]);
|
||||
assert_eq!((month["older"].is_null(), month["newer"].is_null()), (true, true));
|
||||
let old_week = start.saturating_sub(time::Duration::days(35));
|
||||
sqlx::query(
|
||||
"INSERT INTO analyses (id, kind, chart_id, requested_by, language, model, prompt_version, cache_key, status, \
|
||||
content, credits_charged, week_start) \
|
||||
SELECT $1, 'weekly', c.id, c.owner_id, 'hu', 'm', 'v3', 'old', 'done', '{\"title\": \"Régi hét\"}', 0, $2 \
|
||||
FROM charts c WHERE c.id = $3",
|
||||
)
|
||||
.bind(uuid::Uuid::now_v7())
|
||||
.bind(old_week)
|
||||
.bind(uuid::Uuid::parse_str(chart["id"].as_str().unwrap()).unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let older_key = format!("{:04}-{:02}", old_week.year(), u8::from(old_week.month()));
|
||||
let month = app.get("/v1/weekly/history", Some(&anna)).await.body;
|
||||
assert_eq!(month["older"], older_key);
|
||||
let back = app.get(&format!("/v1/weekly/history?month={older_key}"), Some(&anna)).await.body;
|
||||
assert_eq!(back["weeks"][0]["analysis"]["content"]["title"], "Régi hét");
|
||||
assert_eq!(back["weeks"][0]["week_start"], old_week.to_string());
|
||||
assert_eq!(back["newer"], month["current_month"]);
|
||||
// Not into the future; a bad month is refused; others see nothing of it.
|
||||
assert_eq!(app.get("/v1/weekly/history?month=2999-01", Some(&anna)).await.body["month"], month["current_month"]);
|
||||
assert_eq!(app.get("/v1/weekly/history?month=nope", Some(&anna)).await.status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(app.get("/v1/weekly/history", Some(&bob)).await.body["weeks"], json!([]));
|
||||
|
||||
// Monday's e-mail: off and on again from the site.
|
||||
let r = app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": false}))).await;
|
||||
assert_eq!((r.status, &r.body["email"]), (StatusCode::OK, &json!(false)));
|
||||
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["weekly_email"], false);
|
||||
app.call("PUT", "/v1/weekly/email", Some(&anna), Some(json!({"on": true}))).await;
|
||||
let (on, sent_on): (bool, Option<time::Date>) =
|
||||
sqlx::query_as("SELECT weekly_email, weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
// Turned on again, the first one comes next Monday.
|
||||
assert_eq!((on, sent_on), (true, Some(start)));
|
||||
|
||||
// The page of every e-mail setting, from the footer link (no login).
|
||||
let (token,): (uuid::Uuid,) = sqlx::query_as("SELECT email_token FROM users WHERE email = 'anna@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let page = format!("/v1/public/notifications?token={token}");
|
||||
let r = app.get(&page, None).await;
|
||||
assert_eq!((r.status, &r.body), (StatusCode::OK, &json!({"weekly_horoscope": true, "forum": null})));
|
||||
assert_eq!(app.get("/v1/public/notifications?token=nope", None).await.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(
|
||||
app.get(&format!("/v1/public/notifications?token={}", uuid::Uuid::now_v7()), None).await.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
// A forum member sees the forum's e-mails too.
|
||||
sqlx::query(
|
||||
"INSERT INTO forum.members (user_id, nickname, nickname_key, avatar) \
|
||||
SELECT id, 'Csillag', 'csillag', 'moon-gold' FROM users WHERE email = 'anna@example.com'",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r = app.get(&page, None).await.body;
|
||||
assert_eq!(
|
||||
r["forum"],
|
||||
json!({"replies": "daily", "followed": "off", "messages": "instant", "mentions": "instant", "listener": null, "weekly": false})
|
||||
);
|
||||
let mut forum = r["forum"].clone();
|
||||
forum["replies"] = json!("loud");
|
||||
let bad = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true, "forum": forum}))).await;
|
||||
assert_eq!(bad.status, StatusCode::BAD_REQUEST);
|
||||
let off = json!({"replies": "off", "followed": "off", "messages": "off", "mentions": "off", "listener": null, "weekly": false});
|
||||
let r = app.call("PUT", &page, None, Some(json!({"weekly_horoscope": false, "forum": off}))).await;
|
||||
assert_eq!((r.status, &r.body["weekly_horoscope"], &r.body["forum"]), (StatusCode::OK, &json!(false), &off));
|
||||
// Turned on again from this page: as on the site, the first one comes next Monday.
|
||||
sqlx::query("UPDATE users SET weekly_email_sent_on = NULL WHERE email = 'anna@example.com'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
|
||||
let sent_on: Option<time::Date> =
|
||||
sqlx::query_scalar("SELECT weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sent_on, Some(start));
|
||||
// Saved again while on: this Monday's e-mail is not held back.
|
||||
sqlx::query("UPDATE users SET weekly_email_sent_on = NULL WHERE email = 'anna@example.com'")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.call("PUT", &page, None, Some(json!({"weekly_horoscope": true}))).await;
|
||||
let sent_on: Option<time::Date> =
|
||||
sqlx::query_scalar("SELECT weekly_email_sent_on FROM users WHERE email = 'anna@example.com'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sent_on, None);
|
||||
// The mail client's one-click unsubscribe turns off the weekly e-mail only.
|
||||
let r = app.call("POST", &format!("/v1/public/weekly/unsubscribe?token={token}"), None, None).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
assert_eq!(app.get(&page, None).await.body["weekly_horoscope"], false);
|
||||
assert_eq!(
|
||||
app.call("POST", "/v1/public/weekly/unsubscribe?token=nope", None, None).await.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
@@ -4142,3 +4332,354 @@ async fn email_sign_up_checks_turnstile_and_limits_each_address(pool: PgPool) {
|
||||
let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &elsewhere).await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn admin_statistics_and_where_members_came_from(pool: PgPool) {
|
||||
let app = TestApp::new(pool.clone()).await;
|
||||
let admin = app.register("admin@example.com", "Admin").await; // BOOTSTRAP_ADMIN_EMAILS
|
||||
const FB_APP: &str = "Mozilla/5.0 (Linux; Android 14; SM-A546B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/490.0.0.50.82;]";
|
||||
const MAC: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0 Safari/537.36";
|
||||
|
||||
// From Facebook's own browser, and from a Google search on a computer.
|
||||
let mut tokens = Vec::new();
|
||||
for (email, ua, came) in [
|
||||
("anna@example.com", FB_APP, json!({"referrer": "m.facebook.com"})),
|
||||
("bela@example.com", MAC, json!({"referrer": "www.google.com"})),
|
||||
] {
|
||||
let r = app
|
||||
.call_with(
|
||||
"POST",
|
||||
"/v1/auth/register",
|
||||
None,
|
||||
Some(json!({"email": email, "display_name": "X", "came_from": came})),
|
||||
&[("user-agent", ua)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||
let url = app.outbox_url(email, "verify_email").await;
|
||||
let r = app
|
||||
.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "titkos-jelszo-123"}))
|
||||
.await;
|
||||
tokens.push(r.body["session"]["token"].as_str().unwrap().to_string());
|
||||
}
|
||||
// With Google, from a tagged link of the site's own Facebook post.
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/auth/google",
|
||||
None,
|
||||
json!({"id_token": google_token("g-9", "cili@gmail.com", GOOGLE_CLIENT),
|
||||
"came_from": {"utm_source": "fb", "utm_campaign": "heti", "referrer": "l.facebook.com"}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
let row: (Option<String>, Option<String>, Option<String>) = sqlx::query_as(
|
||||
"SELECT signup_source, signup_detail, signup_device FROM users WHERE email = 'anna@example.com'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(row, (Some("facebook".into()), Some("m.facebook.com".into()), Some("mobile".into())));
|
||||
let export = app.get("/v1/me/export", Some(&tokens[0])).await;
|
||||
assert_eq!(export.body["signup_came_from"]["source"], "facebook", "{}", export.body);
|
||||
|
||||
// Anna makes her chart and pays (live); Béla pays in test mode only.
|
||||
app.chart(&tokens[0], "Én", true, "1990-05-15").await;
|
||||
let ids: Vec<uuid::Uuid> = sqlx::query_scalar(
|
||||
"SELECT id FROM users WHERE email IN ('anna@example.com', 'bela@example.com') ORDER BY email",
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for (n, (user, live)) in [(ids[0], true), (ids[1], false)].into_iter().enumerate() {
|
||||
sqlx::query(
|
||||
"INSERT INTO stripe_checkouts (id, user_id, package, price_huf, live, completed_at) \
|
||||
VALUES ($1, $2, 'single', 2000, $3, now())",
|
||||
)
|
||||
.bind(format!("cs_stats_{n}"))
|
||||
.bind(user)
|
||||
.bind(live)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&tokens[0])).await.status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.get("/v1/admin/stats?days=999", Some(&admin)).await.status, StatusCode::BAD_REQUEST);
|
||||
let r = app.get("/v1/admin/stats?days=7", Some(&admin)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let s = &r.body;
|
||||
// The admin is not counted as a member.
|
||||
assert_eq!((&s["totals"]["members"], &s["totals"]["own_charts"]), (&json!(3), &json!(1)));
|
||||
assert_eq!((&s["totals"]["buyers"], &s["totals"]["revenue_huf"]), (&json!(1), &json!(2000)));
|
||||
let p = &s["period"];
|
||||
assert_eq!(
|
||||
(&p["signups"], &p["own_charts"], &p["orders"], &p["revenue_huf"]),
|
||||
(&json!(3), &json!(1), &json!(1), &json!(2000))
|
||||
);
|
||||
assert_eq!(s["previous"]["signups"], 0);
|
||||
let daily = s["daily"].as_array().unwrap();
|
||||
assert_eq!(daily.len(), 7);
|
||||
assert_eq!((&daily[6]["date"], &daily[6]["signups"]), (&s["to"], &json!(3)));
|
||||
let c = &s["cohort"];
|
||||
assert_eq!(
|
||||
c["funnel"],
|
||||
json!({"signups": 3, "verified": 3, "own_chart": 1, "ordered": 0, "checkout": 1, "bought": 1, "weekly": 0})
|
||||
);
|
||||
assert_eq!(
|
||||
c["sources"],
|
||||
json!([{"source": "facebook", "signups": 2, "own_chart": 1, "bought": 1}, {"source": "google", "signups": 1, "own_chart": 0, "bought": 0}])
|
||||
);
|
||||
let details = c["details"].as_array().unwrap();
|
||||
assert!(details.contains(&json!({"detail": "utm_source=fb&utm_campaign=heti", "signups": 1})), "{details:?}");
|
||||
assert!(details.contains(&json!({"detail": "www.google.com", "signups": 1})), "{details:?}");
|
||||
assert_eq!(c["methods"], json!([{"method": "password", "signups": 2}, {"method": "google", "signups": 1}]));
|
||||
assert_eq!(
|
||||
s["packages"],
|
||||
json!([{"package": "single", "gift": false, "orders": 1, "revenue_huf": 2000, "name": "Egy elemzés"}])
|
||||
);
|
||||
// Since the first member: no previous period.
|
||||
let all = app.get("/v1/admin/stats?days=0", Some(&admin)).await.body;
|
||||
assert!(all["previous"].is_null());
|
||||
assert_eq!(all["period"]["signups"], 3);
|
||||
}
|
||||
|
||||
// --- MCP clients through OAuth (docs/mcp.md) ---------------------------------------------
|
||||
|
||||
const MCP_CALLBACK: &str = "https://claude.ai/api/mcp/auth_callback";
|
||||
const MCP_CALLBACK_ENC: &str = "https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback";
|
||||
// A PKCE verifier and its challenge.
|
||||
const PKCE_VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWZOEjXk";
|
||||
const PKCE_CHALLENGE: &str = "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII";
|
||||
|
||||
fn mcp_approval(client: &str) -> Value {
|
||||
json!({
|
||||
"response_type": "code", "client_id": client, "redirect_uri": MCP_CALLBACK,
|
||||
"code_challenge": PKCE_CHALLENGE, "code_challenge_method": "S256",
|
||||
"state": "xyz", "resource": "https://sorsfonalak.test/mcp", "scope": "admin",
|
||||
})
|
||||
}
|
||||
|
||||
/// The admin approves; returns the code from the address Claude gets back.
|
||||
async fn mcp_code(app: &TestApp, session: &str, client: &str) -> String {
|
||||
let r = app.post("/v1/oauth/authorize", Some(session), mcp_approval(client)).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let to = r.body["redirect_to"].as_str().unwrap();
|
||||
assert!(to.starts_with(&format!("{MCP_CALLBACK}?code=")), "{to}");
|
||||
assert!(to.ends_with("&state=xyz&iss=https%3A%2F%2Fsorsfonalak.test"), "{to}");
|
||||
to.split("code=").nth(1).unwrap().split('&').next().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn mcp_exchange(client: &str, code: &str, verifier: &str) -> String {
|
||||
format!(
|
||||
"grant_type=authorization_code&code={code}&redirect_uri={MCP_CALLBACK_ENC}&client_id={client}\
|
||||
&code_verifier={verifier}&resource=https%3A%2F%2Fsorsfonalak.test%2Fmcp"
|
||||
)
|
||||
}
|
||||
|
||||
/// A new connection: (access token, refresh token).
|
||||
async fn mcp_connect(app: &TestApp, session: &str, client: &str) -> (String, String) {
|
||||
let code = mcp_code(app, session, client).await;
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(client, &code, PKCE_VERIFIER), &[]).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
(r.body["access_token"].as_str().unwrap().into(), r.body["refresh_token"].as_str().unwrap().into())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn mcp_clients_connect_through_oauth(pool: PgPool) {
|
||||
let app = TestApp::new(pool).await;
|
||||
let anna = app.register("anna@example.com", "Anna").await;
|
||||
let admin = app.register("admin@example.com", "Admin").await;
|
||||
let anna_id = app.get("/v1/me", Some(&anna)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||
|
||||
let meta = app.get("/v1/oauth/metadata", None).await.body;
|
||||
assert_eq!(
|
||||
(&meta["issuer"], &meta["token_endpoint"], &meta["authorization_endpoint"]),
|
||||
(
|
||||
&json!("https://sorsfonalak.test"),
|
||||
&json!("https://sorsfonalak.test/api/v1/oauth/token"),
|
||||
&json!("https://sorsfonalak.test/oauth/engedely")
|
||||
)
|
||||
);
|
||||
|
||||
// Registration: only Claude's (or a local) return address.
|
||||
let r = app.post("/v1/oauth/register", None, json!({"redirect_uris": ["https://evil.example/cb"]})).await;
|
||||
assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::BAD_REQUEST, Some("invalid_redirect_uri")));
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/oauth/register",
|
||||
None,
|
||||
json!({"client_name": "Claude", "redirect_uris": [MCP_CALLBACK], "token_endpoint_auth_method": "none",
|
||||
"grant_types": ["authorization_code", "refresh_token"], "logo_uri": "https://claude.ai/x.png"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert!(r.body.get("client_secret").is_none());
|
||||
let client = r.body["client_id"].as_str().unwrap().to_string();
|
||||
|
||||
// The approval page's question; a return address the client did not register.
|
||||
let query = format!(
|
||||
"response_type=code&client_id={client}&redirect_uri={MCP_CALLBACK_ENC}&code_challenge={PKCE_CHALLENGE}\
|
||||
&code_challenge_method=S256&state=xyz"
|
||||
);
|
||||
let r = app.get(&format!("/v1/oauth/authorize?{query}"), None).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["client_name"], &r.body["redirect_host"]),
|
||||
(StatusCode::OK, &json!("Claude"), &json!("claude.ai"))
|
||||
);
|
||||
let other = query.replace("claude.ai", "claude.com");
|
||||
assert_eq!(app.get(&format!("/v1/oauth/authorize?{other}"), None).await.status, StatusCode::BAD_REQUEST);
|
||||
let plain = query.replace("S256", "plain");
|
||||
assert_eq!(app.get(&format!("/v1/oauth/authorize?{plain}"), None).await.status, StatusCode::BAD_REQUEST);
|
||||
|
||||
// Approving needs a login and the admin role; a refusal goes back too.
|
||||
assert_eq!(app.post("/v1/oauth/authorize", None, mcp_approval(&client)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.post("/v1/oauth/authorize", Some(&anna), mcp_approval(&client)).await.status, StatusCode::FORBIDDEN);
|
||||
let mut deny = mcp_approval(&client);
|
||||
deny["deny"] = json!(true);
|
||||
let r = app.post("/v1/oauth/authorize", Some(&admin), deny).await;
|
||||
assert_eq!(
|
||||
r.body["redirect_to"],
|
||||
json!(format!("{MCP_CALLBACK}?error=access_denied&state=xyz&iss=https%3A%2F%2Fsorsfonalak.test"))
|
||||
);
|
||||
|
||||
// The code: a wrong verifier or return address does not use it up.
|
||||
let code = mcp_code(&app, &admin, &client).await;
|
||||
let wrong = mcp_exchange(&client, &code, &"a".repeat(43));
|
||||
let r = app.form("/v1/oauth/token", &wrong, &[]).await;
|
||||
assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::BAD_REQUEST, Some("invalid_grant")));
|
||||
let elsewhere = mcp_exchange(&client, &code, PKCE_VERIFIER).replace("claude.ai", "claude.com");
|
||||
assert_eq!(app.form("/v1/oauth/token", &elsewhere, &[]).await.body["error"], "invalid_grant");
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["token_type"], &r.body["expires_in"]),
|
||||
(StatusCode::OK, &json!("Bearer"), &json!(3600)),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
assert_eq!(r.headers["cache-control"], "no-store");
|
||||
let (access, refresh) =
|
||||
(r.body["access_token"].as_str().unwrap().to_string(), r.body["refresh_token"].as_str().unwrap().to_string());
|
||||
|
||||
// What the token is for, and what it may do.
|
||||
let r = app.get("/v1/oauth/whoami", Some(&access)).await;
|
||||
assert_eq!(
|
||||
(r.status, &r.body["resource"], &r.body["scope"]),
|
||||
(StatusCode::OK, &json!("https://sorsfonalak.test/mcp"), &json!("admin"))
|
||||
);
|
||||
assert!(r.body.get("email").is_none());
|
||||
assert_eq!(app.get("/v1/oauth/whoami", Some(&admin)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/admin/stats?days=7", Some(&access)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/admin/users?q=anna", Some(&access)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/admin/celebrities", Some(&access)).await.status, StatusCode::OK);
|
||||
let r = app.post("/v1/admin/promo-codes", Some(&access), json!({"package": "single", "count": 1})).await;
|
||||
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
|
||||
assert_eq!(app.post("/v1/admin/jobs/restart", Some(&access), json!({})).await.status, StatusCode::OK);
|
||||
// Not a daily task: only on the admin page.
|
||||
let roles = json!({"roles": ["user", "admin"]});
|
||||
let r = app.call("PATCH", &format!("/v1/admin/users/{anna_id}"), Some(&access), Some(roles)).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let units = json!({"unit": "natal", "delta": 5});
|
||||
let r = app.post(&format!("/v1/admin/users/{anna_id}/credits"), Some(&access), units).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
// Not an admin page: no session, no new tokens, no list of connections.
|
||||
assert_eq!(app.get("/v1/me", Some(&access)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(
|
||||
app.post("/v1/oauth/authorize", Some(&access), mcp_approval(&client)).await.status,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
assert_eq!(app.get("/v1/admin/oauth/grants", Some(&access)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let grants = app.get("/v1/admin/oauth/grants", Some(&admin)).await.body["grants"].clone();
|
||||
assert_eq!((grants.as_array().unwrap().len(), &grants[0]["client_name"]), (1, &json!("Claude")));
|
||||
|
||||
// A refresh makes a new pair; the old refresh token again ends the connection.
|
||||
let again = format!("grant_type=refresh_token&refresh_token={refresh}&client_id={client}");
|
||||
let r = app.form("/v1/oauth/token", &again, &[]).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
let access2 = r.body["access_token"].as_str().unwrap().to_string();
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access2)).await.status, StatusCode::OK);
|
||||
assert_eq!(app.form("/v1/oauth/token", &again, &[]).await.body["error"], "invalid_grant");
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access2)).await.status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access)).await.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// A code used twice ends the connection made with it.
|
||||
let code = mcp_code(&app, &admin, &client).await;
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await;
|
||||
let access3 = r.body["access_token"].as_str().unwrap().to_string();
|
||||
let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await;
|
||||
assert_eq!(r.body["error"], "invalid_grant");
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access3)).await.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// An expired code.
|
||||
let code = mcp_code(&app, &admin, &client).await;
|
||||
sqlx::query("UPDATE oauth_codes SET expires_at = now() - interval '1 second' WHERE used_at IS NULL")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await.body["error"],
|
||||
"invalid_grant"
|
||||
);
|
||||
|
||||
// Ended by the admin on the site, by the client, by logging out everywhere.
|
||||
let (access4, _) = mcp_connect(&app, &admin, &client).await;
|
||||
let grants = app.get("/v1/admin/oauth/grants", Some(&admin)).await.body["grants"].clone();
|
||||
assert_eq!(grants.as_array().unwrap().len(), 1);
|
||||
let id = grants[0]["id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
app.call("DELETE", &format!("/v1/admin/oauth/grants/{id}"), Some(&admin), None).await.status,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access4)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let (access5, refresh5) = mcp_connect(&app, &admin, &client).await;
|
||||
let r = app.form("/v1/oauth/revoke", &format!("token={refresh5}&client_id={client}"), &[]).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access5)).await.status, StatusCode::UNAUTHORIZED);
|
||||
let (access6, _) = mcp_connect(&app, &admin, &client).await;
|
||||
assert_eq!(app.post("/v1/auth/logout-all", Some(&admin), json!({})).await.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&access6)).await.status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// An admin no more: the token is refused.
|
||||
sqlx::query("UPDATE users SET roles = array_append(roles, 'admin') WHERE email = 'anna@example.com'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let (anna_access, anna_refresh) = mcp_connect(&app, &anna, &client).await;
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&anna_access)).await.status, StatusCode::OK);
|
||||
sqlx::query("UPDATE users SET roles = array_remove(roles, 'admin') WHERE email = 'anna@example.com'")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(app.get("/v1/admin/stats", Some(&anna_access)).await.status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.get("/v1/oauth/whoami", Some(&anna_access)).await.status, StatusCode::FORBIDDEN);
|
||||
let again = format!("grant_type=refresh_token&refresh_token={anna_refresh}&client_id={client}");
|
||||
assert_eq!(app.form("/v1/oauth/token", &again, &[]).await.body["error"], "invalid_grant");
|
||||
|
||||
// A client with a secret must send it (in the form or with HTTP Basic).
|
||||
let r = app
|
||||
.post(
|
||||
"/v1/oauth/register",
|
||||
None,
|
||||
json!({"client_name": "Claude Code", "redirect_uris": ["http://localhost:53682/callback"]}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!((r.status, &r.body["token_endpoint_auth_method"]), (StatusCode::CREATED, &json!("client_secret_basic")));
|
||||
let (local, secret) =
|
||||
(r.body["client_id"].as_str().unwrap().to_string(), r.body["client_secret"].as_str().unwrap().to_string());
|
||||
let login = json!({"email": "admin@example.com", "password": "titkos-jelszo-123"});
|
||||
let admin = app.post("/v1/auth/login", None, login).await.body["session"]["token"].as_str().unwrap().to_string();
|
||||
let mut approval = mcp_approval(&local);
|
||||
approval["redirect_uri"] = json!("http://localhost:53682/callback");
|
||||
let r = app.post("/v1/oauth/authorize", Some(&admin), approval).await;
|
||||
let to = r.body["redirect_to"].as_str().unwrap();
|
||||
let code = to.split("code=").nth(1).unwrap().split('&').next().unwrap();
|
||||
let exchange = format!(
|
||||
"grant_type=authorization_code&code={code}&redirect_uri=http%3A%2F%2Flocalhost%3A53682%2Fcallback\
|
||||
&code_verifier={PKCE_VERIFIER}"
|
||||
);
|
||||
let r = app.form("/v1/oauth/token", &format!("{exchange}&client_id={local}"), &[]).await;
|
||||
assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::UNAUTHORIZED, Some("invalid_client")));
|
||||
use base64::Engine;
|
||||
let basic = format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(format!("{local}:{secret}")));
|
||||
let r = app.form("/v1/oauth/token", &exchange, &[("authorization", &basic)]).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Who is asking: the backend's session (cookie or Bearer token) and the
|
||||
//! member behind it. Reading needs no login; writing needs a nickname.
|
||||
//! Every request of a member also keeps the online dot fresh.
|
||||
//!
|
||||
//! An admin's MCP client (docs/mcp.md) may send its OAuth token instead: it
|
||||
//! reads as that admin and may moderate, but never writes as a member.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -68,6 +71,8 @@ pub struct Viewer {
|
||||
pub topics: Vec<i16>,
|
||||
/// The members they muted.
|
||||
pub mutes: Vec<Uuid>,
|
||||
/// An admin's MCP client (an OAuth token, not a session): moderation only.
|
||||
pub via_token: bool,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
@@ -89,6 +94,9 @@ impl Viewer {
|
||||
}
|
||||
|
||||
pub fn require_user(&self) -> Result<&User, ApiError> {
|
||||
if self.via_token {
|
||||
return Err(ApiError::Forbidden("Claude-ból a fórumban csak moderálni lehet.".into()));
|
||||
}
|
||||
self.user.as_ref().ok_or(ApiError::Unauthorized)
|
||||
}
|
||||
|
||||
@@ -108,7 +116,7 @@ impl Viewer {
|
||||
}
|
||||
|
||||
pub fn require_moderator(&self) -> Result<&User, ApiError> {
|
||||
let user = self.require_user()?;
|
||||
let user = self.user.as_ref().ok_or(ApiError::Unauthorized)?;
|
||||
if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) }
|
||||
}
|
||||
}
|
||||
@@ -127,7 +135,15 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &Arc<AppState>) -> Result<Self, Self::Rejection> {
|
||||
let Some(token) = session_token(parts) else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) };
|
||||
let Some((_, user)) = db::user_by_session(&state.db, &token).await? else {
|
||||
// An admin's MCP client: the admin, without the member's side.
|
||||
return Ok(match db::user_by_oauth_token(&state.db, &token).await? {
|
||||
Some((_, user)) if user.has_role(Role::Admin) => {
|
||||
Viewer { user: Some(user), via_token: true, ..Viewer::default() }
|
||||
}
|
||||
_ => Viewer::default(),
|
||||
});
|
||||
};
|
||||
let member = load_member(&state.db, user.id).await?;
|
||||
if member.is_some() {
|
||||
// At most once a minute per member: the online dot.
|
||||
@@ -154,7 +170,7 @@ impl FromRequestParts<Arc<AppState>> for Viewer {
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
Ok(Viewer { user: Some(user), member, topics, mutes })
|
||||
Ok(Viewer { user: Some(user), member, topics, mutes, via_token: false })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -204,6 +204,10 @@ struct Incoming {
|
||||
|
||||
/// At most one typing notice per target in this time.
|
||||
const TYPING_EVERY: Duration = Duration::from_secs(2);
|
||||
/// At most one typing notice this often per connection, whatever the place.
|
||||
const TYPING_ANY_EVERY: Duration = Duration::from_secs(1);
|
||||
/// A typing notice is a few dozen bytes; anything longer is not one.
|
||||
const TYPING_MAX_BYTES: usize = 200;
|
||||
|
||||
/// "I am typing", from the page: passed on to those who may see that place.
|
||||
async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
||||
@@ -248,6 +252,9 @@ async fn typing(db: &PgPool, me: &Me, text: &str) -> Option<Event> {
|
||||
async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, db: PgPool, me: Me) {
|
||||
let (user, moderator) = (me.user, me.moderator);
|
||||
let mut last_typing: Option<(String, std::time::Instant)> = None;
|
||||
// Whatever the place: at most one notice a second per connection, so
|
||||
// alternating places cannot flood the database and the other members.
|
||||
let mut last_any: Option<std::time::Instant> = None;
|
||||
let mut ping = tokio::time::interval(PING);
|
||||
ping.tick().await;
|
||||
loop {
|
||||
@@ -280,12 +287,16 @@ async fn serve(mut socket: WebSocket, mut rx: broadcast::Receiver<Arc<Event>>, d
|
||||
}
|
||||
incoming = socket.recv() => match incoming {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
// Typing notices, a few seconds apart per place.
|
||||
let fresh = last_typing
|
||||
// Typing notices, a few seconds apart per place, one a second in all.
|
||||
let fresh = text.len() <= TYPING_MAX_BYTES
|
||||
&& last_any.is_none_or(|at| at.elapsed() >= TYPING_ANY_EVERY)
|
||||
&& last_typing
|
||||
.as_ref()
|
||||
.is_none_or(|(place, at)| *place != text.as_str() || at.elapsed() >= TYPING_EVERY);
|
||||
if fresh {
|
||||
last_typing = Some((text.to_string(), std::time::Instant::now()));
|
||||
let now = std::time::Instant::now();
|
||||
last_any = Some(now);
|
||||
last_typing = Some((text.to_string(), now));
|
||||
if let Some(event) = typing(&db, &me, &text).await {
|
||||
emit(&db, event).await;
|
||||
}
|
||||
|
||||
@@ -302,6 +302,10 @@ pub async fn serve(
|
||||
let thread = super::threads::readable_thread(&state.db, &viewer, thread)
|
||||
.await
|
||||
.map_err(|_| ApiError::NotFound("photo"))?;
|
||||
// A removed thread takes its photos down too (moderators still see them).
|
||||
if thread.deleted_at.is_some() && !viewer.is_moderator() {
|
||||
return Err(ApiError::NotFound("photo"));
|
||||
}
|
||||
thread.deleted_at.is_none() && thread.visibility == "public" && !deleted
|
||||
}
|
||||
};
|
||||
@@ -312,18 +316,22 @@ pub async fn serve(
|
||||
.map_err(|e| ApiError::Internal(format!("reading a photo: {e}")))?
|
||||
.ok_or(ApiError::NotFound("photo"))?;
|
||||
let content_type = if file.ends_with(".webp") { "image/webp" } else { "image/jpeg" };
|
||||
let cache = if public { "public, max-age=31536000, immutable" } else { "private, max-age=3600" };
|
||||
// Not for long even when public: a moderator may remove the post, and the
|
||||
// CDN and the browsers must let go of the photo within the hour.
|
||||
let cache = if public { "public, max-age=3600" } else { "private, max-age=3600" };
|
||||
Ok(([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, cache)], object.bytes).into_response())
|
||||
}
|
||||
|
||||
/// Every hour: unattached photos older than a day, and the photos of posts
|
||||
/// removed more than a year ago, leave the storage and the table.
|
||||
/// (or whole threads) removed more than a year ago, leave the storage and the table.
|
||||
pub async fn cleanup(state: &AppState) -> anyhow::Result<u64> {
|
||||
let Some(storage) = &state.storage else { return Ok(0) };
|
||||
let gone: Vec<(Uuid, String, String)> = sqlx::query_as(
|
||||
"SELECT ph.id, ph.file, ph.thumb FROM forum.photos ph LEFT JOIN forum.posts p ON p.id = ph.post_id \
|
||||
LEFT JOIN forum.threads t ON t.id = p.thread_id \
|
||||
WHERE (ph.post_id IS NULL AND ph.created_at < now() - interval '1 day') \
|
||||
OR (p.deleted_at IS NOT NULL AND p.deleted_at < now() - interval '1 year') \
|
||||
OR (t.deleted_at IS NOT NULL AND t.deleted_at < now() - interval '1 year') \
|
||||
LIMIT 500",
|
||||
)
|
||||
.fetch_all(&state.db)
|
||||
|
||||
@@ -316,9 +316,15 @@ async fn set_helped(
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
/// The sharer's link goes (as when revoked on the main site).
|
||||
/// The sharer's link goes (as when revoked on the main site), unless another
|
||||
/// live question of theirs still shows it: asking twice about the same chart
|
||||
/// reuses one link (call it after this post let go of it).
|
||||
async fn revoke_share(db: impl sqlx::PgExecutor<'_>, share: uuid::Uuid, owner: uuid::Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL")
|
||||
sqlx::query(
|
||||
"UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL \
|
||||
AND NOT EXISTS (SELECT 1 FROM forum.posts p JOIN forum.threads t ON t.id = p.thread_id \
|
||||
WHERE p.share_id = $1 AND p.deleted_at IS NULL AND t.deleted_at IS NULL)",
|
||||
)
|
||||
.bind(share)
|
||||
.bind(owner)
|
||||
.execute(db)
|
||||
|
||||
+117
-10
@@ -1327,18 +1327,41 @@ async fn a_question_about_ones_chart(pool: PgPool) {
|
||||
assert_eq!(shown["posts"][0]["share"]["revoked"], true);
|
||||
assert!(shown["posts"][0]["share"].get("points").is_none());
|
||||
|
||||
// The author takes it off (only she may): the card goes, the link stops working.
|
||||
// A second question about the same chart uses the same link.
|
||||
sqlx::query("UPDATE shares SET revoked_at = NULL WHERE slug = 'annaforum000001'").execute(&app.pool).await.unwrap();
|
||||
let (status, second) = app
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/forum/threads",
|
||||
Some(&anna),
|
||||
json!({ "topic": "egbolt-es-kepletek", "title": "És a Vénusz?", "body": "Még egy kérdés.", "share": "annaforum000001" }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{second}");
|
||||
let second = second["id"].as_i64().unwrap();
|
||||
let revoked = || async {
|
||||
sqlx::query_scalar::<_, bool>("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
// The author takes it off the first (only she may): that card goes, the
|
||||
// other question keeps it, so the link stays.
|
||||
let opening = shown["posts"][0]["id"].as_i64().unwrap();
|
||||
let uri = format!("/v1/forum/posts/{opening}/share");
|
||||
assert_eq!(app.call("DELETE", &uri, Some(&bea), Value::Null).await.0, StatusCode::FORBIDDEN);
|
||||
assert_eq!(app.call("DELETE", &uri, Some(&anna), Value::Null).await.0, StatusCode::NO_CONTENT);
|
||||
assert!(app.get(&format!("/v1/forum/threads/{id}"), Some(&bea)).await["posts"][0]["share"].is_null());
|
||||
let revoked: bool = sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM shares WHERE slug = 'annaforum000001'")
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(revoked);
|
||||
assert!(!revoked().await);
|
||||
let other = app.get(&format!("/v1/forum/threads/{second}"), Some(&bea)).await;
|
||||
assert_eq!(other["posts"][0]["share"]["points"][1]["sign"], "pisces");
|
||||
|
||||
// Deleting the last question that shows it: now the link stops working.
|
||||
let last = other["posts"][0]["id"].as_i64().unwrap();
|
||||
let (status, _) = app.call("DELETE", &format!("/v1/forum/posts/{last}"), Some(&anna), json!({})).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert!(revoked().await);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
@@ -1604,7 +1627,8 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
assert_eq!(thread["posts"][0]["photos"].as_array().unwrap().len(), 2);
|
||||
let (status, headers, _) = app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(headers["cache-control"].to_str().unwrap().contains("immutable"));
|
||||
// Public, but only for an hour: a removed post's photo must not linger in caches.
|
||||
assert_eq!(headers["cache-control"].to_str().unwrap(), "public, max-age=3600");
|
||||
|
||||
// In a members-only topic: members only, not cached publicly; Bea cannot use Anna's photo.
|
||||
let (_, third) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
|
||||
@@ -1647,11 +1671,26 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
let (status, body) = upload(&anna, "image/jpeg", jpeg_with_exif()).await;
|
||||
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
|
||||
|
||||
// Unattached for over a day: gone from the table and the storage.
|
||||
// A removed thread takes its photos down (the posts themselves stay unmarked).
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now() WHERE id = $1")
|
||||
.bind(created["id"].as_i64().unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(app.raw("GET", &path(&jpeg["url"]), None, "", Vec::new()).await.0, StatusCode::NOT_FOUND);
|
||||
assert_eq!(app.raw("GET", &path(&jpeg["url"]), Some(&bea), "", Vec::new()).await.0, StatusCode::NOT_FOUND);
|
||||
|
||||
// Unattached for over a day, and in a thread removed over a year ago: gone
|
||||
// from the table and the storage.
|
||||
sqlx::query("UPDATE forum.photos SET created_at = now() - interval '2 days' WHERE post_id IS NULL")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE forum.threads SET deleted_at = now() - interval '2 years' WHERE id = $1")
|
||||
.bind(created["id"].as_i64().unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let state = AppState {
|
||||
db: pool.clone(),
|
||||
flood_secs: 0,
|
||||
@@ -1660,7 +1699,75 @@ async fn photos_in_posts(pool: PgPool) {
|
||||
storage: Some(object_storage::Storage::new(storage)),
|
||||
links: crate::links::LinkConfig::new("http://127.0.0.1:9/oembed", "http://127.0.0.1:9"),
|
||||
};
|
||||
assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 2);
|
||||
assert_eq!(crate::routes::photo_cleanup(&state).await.unwrap(), 4);
|
||||
let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap();
|
||||
assert_eq!(left, 3);
|
||||
assert_eq!(left, 1);
|
||||
}
|
||||
|
||||
/// An admin's MCP client (docs/mcp.md): it moderates with its OAuth token,
|
||||
/// and never writes as a member.
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn an_admins_mcp_client_moderates_only(pool: PgPool) {
|
||||
let app = TestApp::new(pool);
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||
let admin = app.member("admin@example.com", "Gondnok", &["user", "admin"]).await;
|
||||
let thread = app.thread(&anna, "belso-utak", "Energiák").await;
|
||||
let post = app.reply(&bea, thread, "Energetikai gyógyítás, írj!", None).await["id"].as_i64().unwrap();
|
||||
app.call("POST", &format!("/v1/forum/posts/{post}/report"), Some(&anna), json!({"kind": "ad"})).await;
|
||||
|
||||
// The token the backend gave Claude after the admin's approval.
|
||||
let token = db::new_token();
|
||||
let grant = Uuid::now_v7();
|
||||
sqlx::query("INSERT INTO oauth_clients (id, name, redirect_uris) VALUES ('claude', 'Claude', '{}')")
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope) VALUES ($1, 'claude', $2, 'admin')")
|
||||
.bind(grant)
|
||||
.bind(admin.id)
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \
|
||||
VALUES ($1, $2, $3, now() + interval '1 hour', $4, now() + interval '30 days')",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(grant)
|
||||
.bind(db::token_hash(&token))
|
||||
.bind(db::token_hash(&db::new_token()))
|
||||
.execute(&app.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let claude = User { id: admin.id, token };
|
||||
|
||||
// Moderation: the reports, closing one, a ban, the log (under the admin's name).
|
||||
let list = app.get("/v1/forum/mod/reports", Some(&claude)).await;
|
||||
let id = list["reports"][0]["id"].as_i64().unwrap();
|
||||
let (status, _) =
|
||||
app.call("POST", &format!("/v1/forum/mod/reports/{id}"), Some(&claude), json!({"action": "dismiss"})).await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
let (status, _) = app
|
||||
.call("POST", "/v1/forum/members/holdfeny/ban", Some(&claude), json!({"hours": 24, "reason": "hirdetés"}))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let log = app.get("/v1/forum/mod/log", Some(&claude)).await;
|
||||
assert_eq!((&log["entries"][0]["action"], &log["entries"][0]["actor"]), (&json!("ban"), &json!("Gondnok")));
|
||||
assert_eq!(app.get(&format!("/v1/forum/threads/{thread}"), Some(&claude)).await["thread"]["id"], thread);
|
||||
|
||||
// Never as a member: no reply, reaction, report or new thread.
|
||||
let reply = json!({"body": "Claude írta."});
|
||||
let (status, _) = app.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&claude), reply).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) =
|
||||
app.call("PUT", &format!("/v1/forum/posts/{post}/reaction"), Some(&claude), json!({"kind": "heart"})).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
let (status, _) =
|
||||
app.call("POST", &format!("/v1/forum/posts/{post}/report"), Some(&claude), json!({"kind": "ad"})).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
|
||||
// A revoked connection is nobody.
|
||||
sqlx::query("UPDATE oauth_grants SET revoked_at = now()").execute(&app.pool).await.unwrap();
|
||||
assert_eq!(app.call("GET", "/v1/forum/mod/reports", Some(&claude), Value::Null).await.0, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,11 @@ const config: NextConfig = {
|
||||
"/kep/fooldal.png": ["./src/assets/og/*.ttf"],
|
||||
"/hires-emberek/[slug]/kep/[file]": ["./src/assets/og/*.ttf"],
|
||||
},
|
||||
// OAuth for the MCP server's clients (docs/mcp.md): the authorization
|
||||
// server's metadata, from the backend, at its standard address.
|
||||
async rewrites() {
|
||||
return [{ source: "/.well-known/oauth-authorization-server", destination: "/api/v1/oauth/metadata" }];
|
||||
},
|
||||
images: {
|
||||
// Only the famous people's photos (served by the backend through the
|
||||
// /api/v1 proxy, one stored version each) go through the optimizer.
|
||||
|
||||
@@ -61,17 +61,17 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
||||
<section className="lp-hero">
|
||||
<div className="lp-wrap lp-hero-grid">
|
||||
<div className="lp-hero-text">
|
||||
<span className="eyebrow lp-rise lp-r1">Születési képlet · Éves előrejelzés · Kapcsolat</span>
|
||||
<h1 className="lp-title lp-rise lp-r2">
|
||||
<span className="eyebrow">Születési képlet · Éves előrejelzés · Kapcsolat</span>
|
||||
<h1 className="lp-title">
|
||||
Ahol a csillagok
|
||||
<br />
|
||||
összekötnek.
|
||||
</h1>
|
||||
<p className="lp-lead lp-rise lp-r3">
|
||||
<p className="lp-lead">
|
||||
Add meg, mikor és hol születtél: percre pontosan kiszámoljuk a képletedet, és személyre szóló elemzést írunk
|
||||
belőle. Megmutatjuk, mit hoz az éved, és mennyire illetek össze azzal, akit szeretsz.
|
||||
</p>
|
||||
<div className="lp-personal lp-rise lp-r3">
|
||||
<div className="lp-personal">
|
||||
<svg aria-hidden="true" viewBox="0 0 24 24" className="lp-personal-icon">
|
||||
<path d="M12 3.5a7.5 7.5 0 0 1 7.5 7.5c0 3-.6 5.7-1.6 7.8" />
|
||||
<path d="M4.5 11a7.5 7.5 0 0 1 3-6" />
|
||||
@@ -88,7 +88,7 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="lp-actions lp-rise lp-r4">
|
||||
<div className="lp-actions">
|
||||
<Link href={start} className="btn btn-primary lp-btn">
|
||||
{signIn}
|
||||
</Link>
|
||||
@@ -97,13 +97,13 @@ export function Landing({ inviteOnly, loggedIn = false }: { inviteOnly: boolean;
|
||||
</Link>
|
||||
</div>
|
||||
{!loggedIn && (
|
||||
<p className="lp-free-line lp-rise lp-r4">
|
||||
<p className="lp-free-line">
|
||||
<span className="lp-free-label">Ingyenes</span>
|
||||
<Link href="/szuletesi-horoszkop">Nézd meg a születési horoszkópodat belépés nélkül →</Link>
|
||||
</p>
|
||||
)}
|
||||
{!loggedIn && (
|
||||
<p className="hint lp-rise lp-r4">
|
||||
<p className="hint">
|
||||
{inviteOnly
|
||||
? "Az oldal egyelőre meghívásos: meghívóval, Google-fiókkal lépsz be."
|
||||
: "A képlet és a rövid összefoglaló ingyenes. Google-fiókkal lépsz be."}
|
||||
|
||||
@@ -207,6 +207,34 @@ export default async function PrivacyPage() {
|
||||
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Heti horoszkóp: a hét égboltja a saját képleteden, a belőle írt szöveg, és hogy kéred-e a hétfői
|
||||
értesítő levelet
|
||||
</td>
|
||||
<td>
|
||||
Az ingyenes heti horoszkóp; hétfőnként egy rövid levél, hogy itt az új (alapból küldjük, a levél
|
||||
alján, a Heti horoszkóp oldalon vagy a Profil oldalon bármikor kikapcsolhatod)
|
||||
</td>
|
||||
<td>Szerződés teljesítése; a levélnél jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Regisztrációkor: honnan érkeztél az oldalra (például Facebook vagy Google-keresés, egy másik oldal
|
||||
címe az elérési útja nélkül, vagy a link kampánycímkéje), és hogy telefonról, tabletről vagy
|
||||
számítógépről
|
||||
</td>
|
||||
<td>Statisztika: hogy lássuk, honnan jönnek a tagok, és melyik bejegyzésünk vagy hirdetésünk működik</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
Melyik oldalt nyitottad meg, honnan érkeztél, a böngésződ és az eszközöd típusa, az országod és az oldal
|
||||
betöltési ideje (látogatottságmérés)
|
||||
</td>
|
||||
<td>Hogy lássuk, mennyien nézik az egyes oldalakat, és elég gyors-e az oldal</td>
|
||||
<td>Jogos érdek (6. cikk (1) f)</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -263,7 +291,8 @@ export default async function PrivacyPage() {
|
||||
<p>
|
||||
<strong>Mire használjuk:</strong> a fiókod létrehozására és arra, hogy belépéskor felismerjünk; az
|
||||
e-mail-címedet a rendszerlevelekhez (például ha elkészült egy elemzésed, elfogadták a meghívódat, vagy
|
||||
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted); a
|
||||
válasz érkezett vagy megemlítettek a fórumon, illetve a fórum heti összefoglalója, ha ezeket kérted) és a
|
||||
heti horoszkóp hétfői értesítőjéhez (ha nem kapcsoltad ki); a
|
||||
nevedet a megjelenítéshez; a nyelvet az oldal és az elemzések nyelvéhez.
|
||||
</p>
|
||||
<p>
|
||||
@@ -304,10 +333,11 @@ export default async function PrivacyPage() {
|
||||
<section>
|
||||
<h2>4. Az elemzések és a mesterséges intelligencia</h2>
|
||||
<p>
|
||||
A rövid összefoglalót, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott válaszokat nagy nyelvi
|
||||
modell (mesterséges intelligencia) írja. A modellhez a <strong>képlet csillagászati adatai</strong> jutnak
|
||||
el (a bolygók jegye, foka, háza és fényszögei), kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel,
|
||||
a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a
|
||||
A rövid összefoglalót, a heti horoszkópot, a részletes elemzéseket, a kártyajóslást és a kérdésekre adott
|
||||
válaszokat nagy nyelvi modell (mesterséges intelligencia) írja. A modellhez a{" "}
|
||||
<strong>képlet csillagászati adatai</strong> jutnak el (a bolygók jegye, foka, háza és fényszögei), a heti
|
||||
horoszkópnál a hét égboltja is (hol járnak a bolygók, és milyen fényszöget alkotnak a képleteddel),
|
||||
kártyajóslásnál a kihúzott lapok, és ha kérdést teszel fel, a kérdésed szövege. Nevet, e-mail-címet, születési dátumot, időpontot vagy helyet nem küldünk el. Kérjük, a
|
||||
kérdéseidbe se írj neveket vagy érzékeny adatot (például egészségügyi adatot). Az elemzés szórakoztató és
|
||||
önismereti célú szöveg, nem minősül egészségügyi, pénzügyi, jogi vagy más szakmai tanácsnak.
|
||||
</p>
|
||||
@@ -337,7 +367,8 @@ export default async function PrivacyPage() {
|
||||
<strong>Cloudflare, Inc.</strong> – a forgalom továbbítása és a támadások elleni védelem; az oldal
|
||||
letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a
|
||||
Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is
|
||||
vizsgálja).
|
||||
vizsgálja). A Web Analytics szolgáltatásával méri a látogatottságot és az oldal sebességét, süti és a
|
||||
böngészőben tárolt azonosító nélkül; az egyes látogatókat nem követi.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
|
||||
@@ -406,7 +437,18 @@ export default async function PrivacyPage() {
|
||||
<p>
|
||||
A működéshez feltétlenül szükséges sütit használunk (<code>sf_session</code>), amely belépve tart. Ha a
|
||||
fórumon világos vagy sötét témát választasz, a választásodat egy második süti (<code>sf_forum_theme</code>)
|
||||
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket, illetve látogatottságmérőt nem használunk.
|
||||
őrzi egy évig; mást nem tárol. Reklám- vagy követő sütiket nem használunk.
|
||||
</p>
|
||||
<p>
|
||||
A látogatottságot a Cloudflare Web Analytics méri, süti és a böngészőben tárolt azonosító nélkül. Az oldal
|
||||
betöltésekor egy kis szkript elküldi, melyik oldalt nyitottad meg, honnan érkeztél, milyen böngészőt és
|
||||
eszközt használsz, és mennyi idő alatt töltődött be az oldal. Mi ebből csak összesített számokat látunk, az
|
||||
egyes látogatókat nem tudjuk követni.
|
||||
</p>
|
||||
<p>
|
||||
Ha regisztrálsz, a fiókodhoz elmentjük, honnan érkeztél az oldalra és milyen eszközről. Ehhez sem sütit,
|
||||
sem a böngészőben tárolt adatot nem használunk: az oldal csak az adott látogatás alatt, a saját memóriájában
|
||||
jegyzi meg, és a regisztrációval együtt küldi el. Akik nem regisztrálnak, azokról ilyet nem tárolunk.
|
||||
</p>
|
||||
<p>
|
||||
A belépés nélküli <Link href="/szuletesi-horoszkop">születési horoszkópnál</Link> a megadott születési adatokat
|
||||
|
||||
@@ -12,6 +12,7 @@ const PAGE = 50;
|
||||
const SOURCES: Record<string, string> = { analysis: "Elemzés", question: "Kérdés-válasz", preview: "Prompt-próba" };
|
||||
const KINDS: Record<string, string> = {
|
||||
summary: "összefoglaló",
|
||||
weekly: "heti horoszkóp",
|
||||
natal: "képletelemzés",
|
||||
synastry: "kapcsolati",
|
||||
forecast: "előrejelzés",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { confirmDialog } from "@/components/Dialogs";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import type { OauthGrant } from "@/lib/types";
|
||||
|
||||
/** The MCP clients connected to the admin tools, and revoking them. */
|
||||
export function Connections() {
|
||||
const [grants, setGrants] = useState<OauthGrant[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setGrants((await api<{ grants: OauthGrant[] }>("/admin/oauth/grants")).grants);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
async function revoke(grant: OauthGrant) {
|
||||
const ok = await confirmDialog({
|
||||
title: `Visszavonod: ${grant.client_name}?`,
|
||||
text: "Az alkalmazás azonnal elveszíti a hozzáférést. Újra összekötni Claude-ban lehet.",
|
||||
confirm: "Visszavonás",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api(`/admin/oauth/grants/${grant.id}`, { method: "DELETE" });
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
}
|
||||
}
|
||||
|
||||
if (error) return <p className="msg msg-error">{error}</p>;
|
||||
if (!grants) return <p className="muted">Betöltés…</p>;
|
||||
if (grants.length === 0) return <p className="muted">Nincs kapcsolt alkalmazás.</p>;
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Alkalmazás</th>
|
||||
<th>Admin</th>
|
||||
<th>Összekötve</th>
|
||||
<th>Utoljára használta</th>
|
||||
<th aria-label="Műveletek" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{grants.map((g) => (
|
||||
<tr key={g.id}>
|
||||
<td>
|
||||
{g.client_name}
|
||||
{g.redirect_host && <span className="hint"> · {g.redirect_host}</span>}
|
||||
</td>
|
||||
<td>{g.user_email}</td>
|
||||
<td>{formatDate(g.created_at, true)}</td>
|
||||
<td>{formatDate(g.last_used_at, true)}</td>
|
||||
<td>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={() => revoke(g)}>
|
||||
Visszavonás
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AdminNav } from "@/components/AdminNav";
|
||||
import { requireMe } from "@/lib/server";
|
||||
|
||||
import { Connections } from "./Connections";
|
||||
|
||||
export const metadata: Metadata = { title: "Claude" };
|
||||
|
||||
export default async function AdminConnectionsPage() {
|
||||
const me = await requireMe("/admin/kapcsolatok");
|
||||
if (!me.user.roles.includes("admin")) notFound();
|
||||
return (
|
||||
<main className="page">
|
||||
<AdminNav current="/admin/kapcsolatok" />
|
||||
<div className="page-head">
|
||||
<h1>Claude</h1>
|
||||
<p className="muted">
|
||||
Az admin eszközökhöz kapcsolt alkalmazások. Claude-ban az összekötő címe:{" "}
|
||||
<code>https://sorsfonalak.hu/mcp</code>. Az összekötéskor admin fiókkal kell belépni és engedélyezni.
|
||||
</p>
|
||||
</div>
|
||||
<Connections />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,11 @@ import type { CatalogModel, ModelFunction } from "@/lib/types";
|
||||
import { RunningJobs } from "./RunningJobs";
|
||||
|
||||
const LABELS: Record<ModelFunction["kind"], { title: string; about: string }> = {
|
||||
summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." },
|
||||
summary: {
|
||||
title: "Tömör összefoglaló és heti horoszkóp",
|
||||
about:
|
||||
"Ingyenes: az összefoglaló minden új képlethez magától elkészül, a heti horoszkóp akkor, amikor a tag a héten megnyitja a képletét. Olcsó, gyors modell elég.",
|
||||
},
|
||||
analysis: {
|
||||
title: "Elemzések és éves előrejelzés",
|
||||
about: "Fizetős szövegek: részletes képletelemzés, kapcsolati elemzés és éves előrejelzés.",
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { AdminJob } from "@/lib/types";
|
||||
|
||||
const KINDS: Record<AdminJob["kind"], string> = {
|
||||
summary: "Összefoglaló",
|
||||
weekly: "Heti horoszkóp",
|
||||
natal: "Képletelemzés",
|
||||
synastry: "Kapcsolati elemzés",
|
||||
forecast: "Éves előrejelzés",
|
||||
|
||||
@@ -0,0 +1,616 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { KIND_LABELS } from "@/lib/feedback";
|
||||
import type { AdminStats as Stats, StatsDay, StatsPeriod } from "@/lib/types";
|
||||
import { MONTHS, weekRange } from "@/lib/weekly";
|
||||
|
||||
const PERIODS: [number, string][] = [
|
||||
[7, "7 nap"],
|
||||
[30, "30 nap"],
|
||||
[90, "90 nap"],
|
||||
[0, "Mind"],
|
||||
];
|
||||
|
||||
const SOURCE_LABELS: Record<string, string> = {
|
||||
facebook: "Facebook",
|
||||
instagram: "Instagram",
|
||||
messenger: "Messenger",
|
||||
tiktok: "TikTok",
|
||||
google: "Google kereső",
|
||||
bing: "Bing",
|
||||
search: "Más kereső",
|
||||
email: "E-mail",
|
||||
app: "Más alkalmazás",
|
||||
other: "Más oldal",
|
||||
direct: "Közvetlenül",
|
||||
shared: "Megosztott link",
|
||||
invite: "Meghívó",
|
||||
unknown: "Nem ismert",
|
||||
};
|
||||
|
||||
const DEVICE_LABELS: Record<string, string> = {
|
||||
mobile: "Telefon",
|
||||
tablet: "Tablet",
|
||||
desktop: "Számítógép",
|
||||
unknown: "Nem ismert",
|
||||
};
|
||||
|
||||
const METHOD_LABELS: Record<string, string> = {
|
||||
google: "Google",
|
||||
apple: "Apple",
|
||||
facebook: "Facebook",
|
||||
password: "E-mail és jelszó",
|
||||
unknown: "Nem ismert",
|
||||
};
|
||||
|
||||
const CONTENT_LABELS: Record<string, string> = {
|
||||
...KIND_LABELS,
|
||||
celebrity: "Híres ember elemzése",
|
||||
preview: "Prompt-próba (admin)",
|
||||
};
|
||||
|
||||
const WEEKDAYS = ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"];
|
||||
|
||||
const num = (n: number) => n.toLocaleString("hu-HU");
|
||||
const huf = (n: number) => `${num(n)} Ft`;
|
||||
const usd = (n: number) =>
|
||||
n.toLocaleString("hu-HU", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
const pct = (part: number, whole: number) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "–");
|
||||
|
||||
/** "nov. 24." */
|
||||
function shortDay(iso: string): string {
|
||||
const [, m, d] = iso.split("-").map(Number);
|
||||
return `${MONTHS[m - 1].slice(0, 3)}. ${d}.`;
|
||||
}
|
||||
|
||||
/** "november 24., hétfő" */
|
||||
function longDay(iso: string): string {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
const weekday = WEEKDAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()];
|
||||
return `${MONTHS[m - 1]} ${d}., ${weekday}`;
|
||||
}
|
||||
|
||||
function addDays(iso: string, days: number): string {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Admin → Statisztika: how the site is doing, for the chosen period. */
|
||||
export function AdminStats() {
|
||||
const [days, setDays] = useState(30);
|
||||
const [data, setData] = useState<Stats | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
api<Stats>(`/admin/stats?days=${days}`)
|
||||
.then((d) => live && setData(d))
|
||||
.catch((e) => live && setError(errorText(e)))
|
||||
.finally(() => live && setLoading(false));
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [days]);
|
||||
|
||||
return (
|
||||
<div className="field stats" style={{ gap: 18 }}>
|
||||
<div className="stats-filter" role="group" aria-label="Időszak">
|
||||
{PERIODS.map(([d, label]) => (
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
className={d === days ? "btn btn-sm btn-primary" : "btn btn-sm"}
|
||||
aria-pressed={d === days}
|
||||
onClick={() => setDays(d)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
{data && (
|
||||
<span className="hint">
|
||||
{longDay(data.from).replace(/, .*/, "")} – {longDay(data.to).replace(/, .*/, "")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!data && !error && <p className="muted">Betöltés…</p>}
|
||||
{data && (
|
||||
<div className="field" style={{ gap: 18, opacity: loading ? 0.55 : 1 }} aria-busy={loading}>
|
||||
<Totals data={data} />
|
||||
<Tiles
|
||||
period={data.period}
|
||||
previous={data.previous}
|
||||
days={data.days}
|
||||
subscribers={data.totals.weekly_subscribers}
|
||||
/>
|
||||
<Daily daily={data.daily} />
|
||||
<div className="stats-grid">
|
||||
<Funnel data={data} />
|
||||
<Sources data={data} />
|
||||
</div>
|
||||
<div className="stats-grid">
|
||||
<Packages data={data} />
|
||||
<Weekly data={data} />
|
||||
</div>
|
||||
<Content data={data} />
|
||||
<p className="hint">
|
||||
A tagok számában az adminok nem szerepelnek. A bevétel az éles Stripe-fizetések összege, a tesztfizetések
|
||||
nélkül. A napokat magyar idő szerint számoljuk. Azokról, akik nem regisztrálnak, nem tárolunk semmit; őket a
|
||||
Cloudflare Web Analytics mutatja.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Totals({ data }: { data: Stats }) {
|
||||
const t = data.totals;
|
||||
return (
|
||||
<p className="muted stats-totals">
|
||||
Eddig összesen: <strong>{num(t.members)}</strong> tag · <strong>{num(t.own_charts)}</strong> saját képlet ·{" "}
|
||||
<strong>{num(t.buyers)}</strong> fizető vásárló · <strong>{huf(t.revenue_huf)}</strong> bevétel ·{" "}
|
||||
<strong>{num(t.weekly_subscribers)}</strong> kéri a heti levelet · <strong>{num(t.forum_members)}</strong>{" "}
|
||||
fórumtag
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
/** "+2 az előző 30 naphoz képest" */
|
||||
function Delta({ now, before, days }: { now: number; before: number | undefined; days: number }) {
|
||||
if (before === undefined) return null;
|
||||
const diff = now - before;
|
||||
const text =
|
||||
diff === 0
|
||||
? `ugyanannyi, mint az előző ${days} napban`
|
||||
: `${diff > 0 ? "+" : "−"}${num(Math.abs(diff))} az előző ${days} naphoz képest`;
|
||||
return <span className="stats-tile-sub">{text}</span>;
|
||||
}
|
||||
|
||||
function Tiles({
|
||||
period: p,
|
||||
previous: b,
|
||||
days,
|
||||
subscribers,
|
||||
}: {
|
||||
period: StatsPeriod;
|
||||
previous: StatsPeriod | null;
|
||||
days: number;
|
||||
subscribers: number;
|
||||
}) {
|
||||
const net = p.revenue_huf - p.refunded_huf;
|
||||
return (
|
||||
<dl className="stats-tiles">
|
||||
<div>
|
||||
<dt>Új tag</dt>
|
||||
<dd className="stats-tile-value">{num(p.signups)}</dd>
|
||||
<dd>
|
||||
<Delta now={p.signups} before={b?.signups} days={days} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Saját képletet készített</dt>
|
||||
<dd className="stats-tile-value">{num(p.own_charts)}</dd>
|
||||
<dd>
|
||||
<Delta now={p.own_charts} before={b?.own_charts} days={days} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Vásárlás</dt>
|
||||
<dd className="stats-tile-value">{huf(net)}</dd>
|
||||
<dd className="stats-tile-sub">
|
||||
{num(p.orders)} fizetés, {num(p.buyers)} vásárló
|
||||
{p.refunded_huf > 0 && `, ${huf(p.refunded_huf)} visszatérítve`}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Elemzés és kérdés</dt>
|
||||
<dd className="stats-tile-value">{num(p.analyses + p.questions)}</dd>
|
||||
<dd className="stats-tile-sub">
|
||||
{num(p.analyses)} elemzés, {num(p.questions)} kérdés
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Heti horoszkópot olvasott</dt>
|
||||
<dd className="stats-tile-value">{num(p.weekly_readers)}</dd>
|
||||
<dd className="stats-tile-sub">{num(subscribers)} tag kéri a hétfői levelet</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Fórum-hozzászólás</dt>
|
||||
<dd className="stats-tile-value">{num(p.forum_posts)}</dd>
|
||||
<dd>
|
||||
<Delta now={p.forum_posts} before={b?.forum_posts} days={days} />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>AI-költség</dt>
|
||||
<dd className="stats-tile-value">{usd(p.ai_cost_usd)}</dd>
|
||||
<dd className="stats-tile-sub">minden elemzés, válasz és próba</dd>
|
||||
</div>
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
const SERIES: { key: keyof StatsDay; label: string; value: (d: StatsDay) => number; unit: string }[] = [
|
||||
{ key: "signups", label: "Új tag", value: (d) => d.signups, unit: "új tag" },
|
||||
{ key: "own_charts", label: "Saját képlet", value: (d) => d.own_charts, unit: "saját képlet" },
|
||||
{ key: "analyses", label: "Elemzés és kérdés", value: (d) => d.analyses + d.questions, unit: "elemzés és kérdés" },
|
||||
{ key: "orders", label: "Fizetés", value: (d) => d.orders, unit: "fizetés" },
|
||||
{ key: "weekly_readers", label: "Heti horoszkóp", value: (d) => d.weekly_readers, unit: "heti olvasó" },
|
||||
{ key: "forum_posts", label: "Fórum", value: (d) => d.forum_posts, unit: "hozzászólás" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Day by day, one small chart per measure on the same days. Pointing at (or
|
||||
* tapping) a day shows that day's numbers in the line above; the table
|
||||
* below has them all.
|
||||
*/
|
||||
function Daily({ daily }: { daily: StatsDay[] }) {
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const day = hover !== null ? daily[hover] : null;
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Napról napra</h2>
|
||||
<p className="stats-readout" aria-hidden="true">
|
||||
{day ? (
|
||||
<>
|
||||
<strong>{longDay(day.date)}</strong>
|
||||
{SERIES.map((s) => ` · ${num(s.value(day))} ${s.unit}`).join("")}
|
||||
{day.revenue_huf > 0 && ` · ${huf(day.revenue_huf)}`}
|
||||
</>
|
||||
) : (
|
||||
<span className="muted">Mutass egy napra a számaiért.</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="stats-daily" onPointerLeave={() => setHover(null)}>
|
||||
{SERIES.map((s) => {
|
||||
const values = daily.map(s.value);
|
||||
const max = Math.max(...values, 0);
|
||||
const total = values.reduce((a, v) => a + v, 0);
|
||||
return (
|
||||
<div key={s.key} className="spark">
|
||||
<div className="spark-head">
|
||||
<span>{s.label}</span>
|
||||
<strong>{num(total)}</strong>
|
||||
</div>
|
||||
<div
|
||||
className="spark-plot"
|
||||
role="img"
|
||||
aria-label={`${s.label}: összesen ${total}, egy napon legfeljebb ${max}`}
|
||||
>
|
||||
{max > 0 && <span className="spark-max">{num(max)}</span>}
|
||||
<div className="spark-bars">
|
||||
{values.map((v, i) => (
|
||||
<span
|
||||
key={daily[i].date}
|
||||
className={i === hover ? "spark-col is-on" : "spark-col"}
|
||||
onPointerEnter={() => setHover(i)}
|
||||
onPointerDown={() => setHover(i)}
|
||||
>
|
||||
{v > 0 && <span className="spark-bar" style={{ height: `${Math.max((v / max) * 100, 6)}%` }} />}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="spark-axis" aria-hidden="true">
|
||||
<span>{daily.length > 0 && shortDay(daily[0].date)}</span>
|
||||
<span>{daily.length > 0 && shortDay(daily[daily.length - 1].date)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<details className="details">
|
||||
<summary>Napi táblázat</summary>
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nap</th>
|
||||
<th>Új tag</th>
|
||||
<th>Saját képlet</th>
|
||||
<th>Elemzés</th>
|
||||
<th>Kérdés</th>
|
||||
<th>Fizetés</th>
|
||||
<th>Bevétel</th>
|
||||
<th>Heti olvasó</th>
|
||||
<th>Fórum</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...daily].reverse().map((d) => (
|
||||
<tr key={d.date}>
|
||||
<td>{longDay(d.date)}</td>
|
||||
<td className="num">{d.signups}</td>
|
||||
<td className="num">{d.own_charts}</td>
|
||||
<td className="num">{d.analyses}</td>
|
||||
<td className="num">{d.questions}</td>
|
||||
<td className="num">{d.orders}</td>
|
||||
<td className="num">{d.revenue_huf ? huf(d.revenue_huf) : "–"}</td>
|
||||
<td className="num">{d.weekly_readers}</td>
|
||||
<td className="num">{d.forum_posts}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** A horizontal bar with its value at the end. */
|
||||
function Bar({ value, max, label }: { value: number; max: number; label: string }) {
|
||||
return (
|
||||
<span className="hbar">
|
||||
<span className="hbar-track">
|
||||
{value > 0 && <span className="hbar-fill" style={{ width: `${(value / max) * 100}%` }} />}
|
||||
</span>
|
||||
<span className="hbar-value">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Funnel({ data }: { data: Stats }) {
|
||||
const f = data.cohort.funnel;
|
||||
const steps: [string, number][] = [
|
||||
["Regisztrált", f.signups],
|
||||
["Megerősítette az e-mail-címét", f.verified],
|
||||
["Elkészítette a saját képletét", f.own_chart],
|
||||
["Elkezdte a fizetést", f.checkout],
|
||||
["Fizetett", f.bought],
|
||||
];
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Regisztrációtól a fizetésig</h2>
|
||||
<p className="hint">Az időszakban regisztráltak: ki meddig jutott el azóta.</p>
|
||||
</div>
|
||||
{f.signups === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem regisztrált senki.</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="funnel">
|
||||
{steps.map(([label, n], i) => (
|
||||
<li key={label}>
|
||||
<span>{label}</span>
|
||||
<Bar value={n} max={f.signups} label={i === 0 ? num(n) : `${num(n)} · ${pct(n, f.signups)}`} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="hint">
|
||||
Elemzést vagy kérdést kért (vásárolt vagy kapott egységgel): {num(f.ordered)} ({pct(f.ordered, f.signups)})
|
||||
· Heti horoszkópot olvasott: {num(f.weekly)} ({pct(f.weekly, f.signups)})
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Sources({ data }: { data: Stats }) {
|
||||
const c = data.cohort;
|
||||
const total = c.funnel.signups;
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Honnan jöttek</h2>
|
||||
<p className="hint">Az időszakban regisztráltak, az első látogatásuk szerint.</p>
|
||||
</div>
|
||||
{total === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem regisztrált senki.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table stats-sources">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Forrás</th>
|
||||
<th>Tag</th>
|
||||
<th>Saját képlet</th>
|
||||
<th>Fizetett</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{c.sources.map((s) => (
|
||||
<tr key={s.source}>
|
||||
<td>{SOURCE_LABELS[s.source] ?? s.source}</td>
|
||||
<td>
|
||||
<Bar value={s.signups} max={total} label={`${num(s.signups)} · ${pct(s.signups, total)}`} />
|
||||
</td>
|
||||
<td className="num">{num(s.own_chart)}</td>
|
||||
<td className="num">{num(s.bought)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="stats-split">
|
||||
<Shares
|
||||
title="Eszköz"
|
||||
rows={c.devices.map((d) => [DEVICE_LABELS[d.device] ?? d.device, d.signups])}
|
||||
total={total}
|
||||
/>
|
||||
<Shares
|
||||
title="Regisztráció módja"
|
||||
rows={c.methods.map((m) => [METHOD_LABELS[m.method] ?? m.method, m.signups])}
|
||||
total={total}
|
||||
/>
|
||||
</div>
|
||||
{c.details.length > 0 && (
|
||||
<div>
|
||||
<h3 className="stats-h3">Hivatkozó oldalak és kampányok</h3>
|
||||
<ul className="stats-list">
|
||||
{c.details.map((d) => (
|
||||
<li key={d.detail}>
|
||||
<code>{d.detail}</code>
|
||||
<span className="num">{num(d.signups)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<p className="hint">
|
||||
„Közvetlenül”: beírta a címet, könyvjelzőből vagy olyan alkalmazásból jött, amely nem mondja meg, honnan.
|
||||
„Nem ismert”: a mérés előtt regisztrált. A saját Facebook-bejegyzéseid linkjéhez tehetsz kampánycímkét
|
||||
(például <code>?utm_source=facebook&utm_campaign=heti</code>), az itt külön sorban látszik.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Shares({ title, rows, total }: { title: string; rows: [string, number][]; total: number }) {
|
||||
return (
|
||||
<div>
|
||||
<h3 className="stats-h3">{title}</h3>
|
||||
<ul className="stats-list">
|
||||
{rows.map(([label, n]) => (
|
||||
<li key={label}>
|
||||
<span>{label}</span>
|
||||
<span className="num">
|
||||
{num(n)} · {pct(n, total)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Packages({ data }: { data: Stats }) {
|
||||
const rows = data.packages;
|
||||
const total = rows.reduce((a, r) => a + r.revenue_huf, 0);
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Vásárlások csomagonként</h2>
|
||||
{rows.length === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem volt fizetés.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Csomag</th>
|
||||
<th>Darab</th>
|
||||
<th>Bevétel</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={`${r.package}-${r.gift}`}>
|
||||
<td>
|
||||
{r.name ?? r.package}
|
||||
{r.gift && <span className="hint"> (ajándékba)</span>}
|
||||
</td>
|
||||
<td className="num">{num(r.orders)}</td>
|
||||
<td className="num">{huf(r.revenue_huf)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th>Összesen</th>
|
||||
<td className="num">{num(rows.reduce((a, r) => a + r.orders, 0))}</td>
|
||||
<td className="num">{huf(total)}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Weekly({ data }: { data: Stats }) {
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Heti horoszkóp hetente</h2>
|
||||
<p className="hint">Hányan olvasták el (a szöveg az első megnyitáskor készül), és hány hétfői levél ment ki.</p>
|
||||
</div>
|
||||
{data.weekly.length === 0 ? (
|
||||
<p className="muted">Még senki nem olvasta.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Hét</th>
|
||||
<th>Olvasó</th>
|
||||
<th>Levél</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.weekly.map((w) => (
|
||||
<tr key={w.week_start}>
|
||||
<td>{weekRange(w.week_start, addDays(w.week_start, 6))}</td>
|
||||
<td className="num">{num(w.readers)}</td>
|
||||
<td className="num">{num(w.emails)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Content({ data }: { data: Stats }) {
|
||||
const rows = data.content;
|
||||
const cost = rows.reduce((a, r) => a + r.cost_usd, 0);
|
||||
return (
|
||||
<section className="card">
|
||||
<div>
|
||||
<h2>Amit az AI írt</h2>
|
||||
<p className="hint">Mindenkié az időszakban, az adminoké is. A költséget az OpenRouter adja meg.</p>
|
||||
</div>
|
||||
{rows.length === 0 ? (
|
||||
<p className="muted">Ebben az időszakban nem készült szöveg.</p>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="promo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fajta</th>
|
||||
<th>Elkészült</th>
|
||||
<th>Sikertelen</th>
|
||||
<th>Költség</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r.kind}>
|
||||
<td>{CONTENT_LABELS[r.kind] ?? r.kind}</td>
|
||||
<td className="num">{num(r.done)}</td>
|
||||
<td className="num">{r.failed ? num(r.failed) : "–"}</td>
|
||||
<td className="num">{usd(r.cost_usd)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th>Összesen</th>
|
||||
<td className="num">{num(rows.reduce((a, r) => a + r.done, 0))}</td>
|
||||
<td className="num">{num(rows.reduce((a, r) => a + r.failed, 0))}</td>
|
||||
<td className="num">{usd(cost)}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { AdminNav } from "@/components/AdminNav";
|
||||
import { requireMe } from "@/lib/server";
|
||||
|
||||
import { AdminStats } from "./AdminStats";
|
||||
|
||||
export const metadata: Metadata = { title: "Statisztika" };
|
||||
|
||||
export default async function AdminStatsPage() {
|
||||
const me = await requireMe("/admin/statisztika");
|
||||
if (!me.user.roles.includes("admin")) notFound();
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 1180 }}>
|
||||
<AdminNav current="/admin/statisztika" />
|
||||
<div className="page-head">
|
||||
<h1>Statisztika</h1>
|
||||
<p className="muted">
|
||||
Regisztrációk, képletek, vásárlások és a heti horoszkóp olvasói, és hogy honnan jönnek a tagok.
|
||||
</p>
|
||||
</div>
|
||||
<AdminStats />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
import { cameFrom } from "@/lib/arrival";
|
||||
|
||||
/** The part of Sign in with Apple JS (appleid.auth.js) we use. */
|
||||
interface AppleSignInResponse {
|
||||
@@ -98,7 +99,13 @@ export function AppleLogin({
|
||||
const name = [response.user?.name?.lastName, response.user?.name?.firstName].filter(Boolean).join(" ") || null;
|
||||
try {
|
||||
await api("/auth/apple", {
|
||||
body: { id_token: response.authorization.id_token, name, invite_token: inviteToken, referral },
|
||||
body: {
|
||||
id_token: response.authorization.id_token,
|
||||
name,
|
||||
invite_token: inviteToken,
|
||||
referral,
|
||||
came_from: cameFrom(),
|
||||
},
|
||||
});
|
||||
router.replace(target);
|
||||
router.refresh();
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
import { cameFrom } from "@/lib/arrival";
|
||||
|
||||
/** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */
|
||||
function GoogleMark() {
|
||||
@@ -74,7 +75,9 @@ export function GoogleLogin({
|
||||
setError(null);
|
||||
setUninvited(null);
|
||||
try {
|
||||
await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken, referral } });
|
||||
await api("/auth/google", {
|
||||
body: { id_token: response.credential, invite_token: inviteToken, referral, came_from: cameFrom() },
|
||||
});
|
||||
router.replace(target);
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { copyDialog } from "@/components/Dialogs";
|
||||
import { chromeIntent, type InAppBrowser } from "@/lib/inAppBrowser";
|
||||
|
||||
/** "a Facebook", "az Instagram": the Hungarian article, capitalised at the start of a sentence. */
|
||||
function named(app: string | null): string {
|
||||
if (!app) return "Egy alkalmazás";
|
||||
return `${/^[aáeéiíoóöőuúüű]/i.test(app) ? "Az" : "A"} ${app}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* On the login page inside an app's built-in browser (Facebook and co.):
|
||||
* why the Google button is missing, and the way out to the phone's own
|
||||
* browser. On Android a link opens the page in Chrome; on an iPhone only the
|
||||
* app's own menu can, so the text says where, and the link can be copied.
|
||||
*/
|
||||
export function InAppNotice({ browser, url, password }: { browser: InAppBrowser; url: string; password: boolean }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const where = browser.android ? "a Chrome-ban" : "a böngésződben (Safari)";
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
setCopied(true);
|
||||
} catch {
|
||||
await copyDialog({
|
||||
title: "A belépési oldal linkje",
|
||||
text: "Másold ki, és nyisd meg a böngésződben.",
|
||||
value: url,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="inapp-note" role="note">
|
||||
<strong>{named(browser.app)} beépített böngészőjében vagy</strong>
|
||||
<p>
|
||||
Itt a Google nem engedi a Google-fiókos belépést. {password ? "Lépj be e-mail-címmel, vagy nyisd" : "Nyisd"} meg
|
||||
az oldalt {where}, ott a Google-fiókoddal is beléphetsz.
|
||||
{!browser.android && " Ehhez koppints a jobb felső sarokban a ⋯ gombra, és válaszd a megnyitást böngészőben."}
|
||||
</p>
|
||||
<div className="inapp-actions">
|
||||
{browser.android && (
|
||||
<a className="btn btn-primary" href={chromeIntent(url)}>
|
||||
Megnyitás Chrome-ban
|
||||
</a>
|
||||
)}
|
||||
<button type="button" className="btn" onClick={() => void copy()}>
|
||||
{copied ? "Kimásolva" : "Link másolása"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { useState } from "react";
|
||||
import { PasswordInput } from "@/components/PasswordInput";
|
||||
import { Turnstile } from "@/components/Turnstile";
|
||||
import { ApiError, api, errorText } from "@/lib/api";
|
||||
import { cameFrom } from "@/lib/arrival";
|
||||
|
||||
type Mode = "login" | "register" | "forgot";
|
||||
|
||||
@@ -79,6 +80,7 @@ export function PasswordLogin({
|
||||
invite_token: inviteToken,
|
||||
referral,
|
||||
turnstile_token: token,
|
||||
came_from: cameFrom(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
@@ -6,11 +7,14 @@ import { Logo } from "@/components/SiteHeader";
|
||||
import { ZodiacWheel } from "@/components/ZodiacWheel";
|
||||
import { BACKEND_URL, getMe } from "@/lib/server";
|
||||
import { formatDate } from "@/lib/astro";
|
||||
import { inAppBrowser } from "@/lib/inAppBrowser";
|
||||
import { contents } from "@/lib/packageContents";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
import type { InvitationLanding, PublicConfig } from "@/lib/types";
|
||||
|
||||
import { AppleLogin } from "./AppleLogin";
|
||||
import { GoogleLogin } from "./GoogleLogin";
|
||||
import { InAppNotice } from "./InAppNotice";
|
||||
import { PasswordLogin } from "./PasswordLogin";
|
||||
|
||||
export const metadata: Metadata = { title: "Belépés" };
|
||||
@@ -123,6 +127,48 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
const password = config?.password_login === true;
|
||||
const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod;
|
||||
const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login";
|
||||
// Facebook's and other apps' built-in browsers: Google refuses to sign in
|
||||
// there, so the e-mail form comes first and the way out to the phone's own
|
||||
// browser (this same page, with its invitation or referral) is offered.
|
||||
const inApp = inAppBrowser((await headers()).get("user-agent") ?? "");
|
||||
const query = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
for (const v of Array.isArray(value) ? value : [value]) query.append(key, v);
|
||||
}
|
||||
// The phone's browser learns from this which app the visitor came out of (lib/arrival.ts).
|
||||
if (inApp) query.set("forras", (inApp.app ?? "app").toLowerCase());
|
||||
const here = `${await siteUrl()}/belepes${query.size ? `?${query}` : ""}`;
|
||||
|
||||
const google =
|
||||
clientId && !inApp ? (
|
||||
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||
) : null;
|
||||
const apple =
|
||||
clientId && appleId ? (
|
||||
<AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||
) : null;
|
||||
const social =
|
||||
google || apple ? (
|
||||
<div className="field" style={{ gap: 12 }}>
|
||||
{google}
|
||||
{apple}
|
||||
</div>
|
||||
) : null;
|
||||
const passwordForm = password ? (
|
||||
<PasswordLogin
|
||||
target={target}
|
||||
inviteToken={pendingInvite}
|
||||
referral={referral}
|
||||
initialMode={initialMode}
|
||||
turnstileKey={config?.turnstile_site_key ?? null}
|
||||
/>
|
||||
) : null;
|
||||
const or =
|
||||
social && passwordForm ? (
|
||||
<div className="auth-or" role="separator">
|
||||
<span>vagy</span>
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className="auth">
|
||||
@@ -149,35 +195,25 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
|
||||
{rawToken && (
|
||||
<InvitationCard invitation={inviteToken ? invitation : null} apple={appleId !== null} password={password} />
|
||||
)}
|
||||
{inApp && config !== null && <InAppNotice browser={inApp} url={here} password={password} />}
|
||||
{config === null ? (
|
||||
<p className="msg msg-error" role="alert">
|
||||
A szerver most nem érhető el. Próbáld újra egy kicsit később.
|
||||
</p>
|
||||
) : clientId || password ? (
|
||||
inApp ? (
|
||||
<>
|
||||
{clientId && (
|
||||
<div className="field" style={{ gap: 12 }}>
|
||||
<GoogleLogin clientId={clientId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||
{appleId && (
|
||||
<AppleLogin clientId={appleId} target={target} inviteToken={pendingInvite} referral={referral} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{clientId && password && (
|
||||
<div className="auth-or" role="separator">
|
||||
<span>vagy</span>
|
||||
</div>
|
||||
)}
|
||||
{password && (
|
||||
<PasswordLogin
|
||||
target={target}
|
||||
inviteToken={pendingInvite}
|
||||
referral={referral}
|
||||
initialMode={initialMode}
|
||||
turnstileKey={config?.turnstile_site_key ?? null}
|
||||
/>
|
||||
)}
|
||||
{passwordForm}
|
||||
{or}
|
||||
{social}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{social}
|
||||
{or}
|
||||
{passwordForm}
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<p className="msg msg-error" role="alert">
|
||||
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
interface ForumMail {
|
||||
replies: "off" | "daily" | "instant";
|
||||
followed: "off" | "daily";
|
||||
messages: "off" | "instant";
|
||||
mentions: "off" | "instant";
|
||||
/** Only for volunteer listeners. */
|
||||
listener: "off" | "instant" | null;
|
||||
weekly: boolean;
|
||||
}
|
||||
|
||||
interface Settings {
|
||||
weekly_horoscope: boolean;
|
||||
forum: ForumMail | null;
|
||||
}
|
||||
|
||||
/** Everything off: the weekly horoscope and every forum e-mail. */
|
||||
function allOff(s: Settings): Settings {
|
||||
return {
|
||||
weekly_horoscope: false,
|
||||
forum: s.forum
|
||||
? {
|
||||
replies: "off",
|
||||
followed: "off",
|
||||
messages: "off",
|
||||
mentions: "off",
|
||||
listener: s.forum.listener === null ? null : "off",
|
||||
weekly: false,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The e-mail settings behind an e-mail's footer link: the token in the link
|
||||
* stands for the login. Nothing changes until a button is pressed (mail
|
||||
* providers' link scanners open every link).
|
||||
*/
|
||||
export function MailSettings({ token }: { token: string | null }) {
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState<string | null>(null);
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
api<Settings>(`/public/notifications${query}`)
|
||||
.then(setSettings)
|
||||
.catch((e) => setLoadError(errorText(e)));
|
||||
}, [token, query]);
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<p className="msg msg-error" role="alert">
|
||||
Hiányzik a link vége. Nyisd meg a teljes linket a levélből.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (loadError) {
|
||||
return (
|
||||
<p className="msg msg-error" role="alert">
|
||||
Ez a link nem érvényes. Nyisd meg a teljes linket a levélből, vagy lépj be, és a Profil oldalon állítsd be.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (!settings) {
|
||||
return <p className="muted">Betöltés…</p>;
|
||||
}
|
||||
|
||||
async function save(next: Settings, done: string) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSaved(null);
|
||||
try {
|
||||
setSettings(await api<Settings>(`/public/notifications${query}`, { method: "PUT", body: next }));
|
||||
setSaved(done);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const forum = settings.forum;
|
||||
const setForum = (patch: Partial<ForumMail>) => {
|
||||
setSaved(null);
|
||||
setSettings({ ...settings, forum: forum ? { ...forum, ...patch } : null });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card field mail-settings" style={{ gap: 18 }}>
|
||||
<fieldset className="mail-set">
|
||||
<legend>Heti horoszkóp</legend>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={settings.weekly_horoscope}
|
||||
onChange={(e) => {
|
||||
setSaved(null);
|
||||
setSettings({ ...settings, weekly_horoscope: e.target.checked });
|
||||
}}
|
||||
/>
|
||||
<span>Hétfőnként szóljatok, ha itt az új heti horoszkópom</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
{forum && (
|
||||
<fieldset className="mail-set">
|
||||
<legend>Fórum</legend>
|
||||
<label htmlFor="mail-replies">Ha valaki válaszol nekem (a szálamban vagy a hozzászólásomra)</label>
|
||||
<select
|
||||
id="mail-replies"
|
||||
className="inp"
|
||||
value={forum.replies}
|
||||
onChange={(e) => setForum({ replies: e.target.value as ForumMail["replies"] })}
|
||||
>
|
||||
<option value="daily">Napi összesítőben, este</option>
|
||||
<option value="instant">Azonnal (szálanként óránként legfeljebb egy levél)</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
<label htmlFor="mail-followed">Új hozzászólás a követett szálaimban</label>
|
||||
<select
|
||||
id="mail-followed"
|
||||
className="inp"
|
||||
value={forum.followed}
|
||||
onChange={(e) => setForum({ followed: e.target.value as ForumMail["followed"] })}
|
||||
>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
<option value="daily">Napi összesítőben, este</option>
|
||||
</select>
|
||||
<label htmlFor="mail-messages">Privát üzenet vagy beszélgetési kérés</label>
|
||||
<select
|
||||
id="mail-messages"
|
||||
className="inp"
|
||||
value={forum.messages}
|
||||
onChange={(e) => setForum({ messages: e.target.value as ForumMail["messages"] })}
|
||||
>
|
||||
<option value="instant">Azonnal</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
<label htmlFor="mail-mentions">Ha valaki megemlít</label>
|
||||
<select
|
||||
id="mail-mentions"
|
||||
className="inp"
|
||||
value={forum.mentions}
|
||||
onChange={(e) => setForum({ mentions: e.target.value as ForumMail["mentions"] })}
|
||||
>
|
||||
<option value="instant">Azonnal</option>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
</select>
|
||||
{forum.listener !== null && (
|
||||
<>
|
||||
<label htmlFor="mail-listener">
|
||||
Kísérőként: ha egy meghallgatást kérő szál két órája válasz nélkül vár
|
||||
</label>
|
||||
<select
|
||||
id="mail-listener"
|
||||
className="inp"
|
||||
value={forum.listener}
|
||||
onChange={(e) => setForum({ listener: e.target.value as "off" | "instant" })}
|
||||
>
|
||||
<option value="off">Ne küldjetek</option>
|
||||
<option value="instant">Azonnal (hat óránként legfeljebb egy levél)</option>
|
||||
</select>
|
||||
</>
|
||||
)}
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={forum.weekly} onChange={(e) => setForum({ weekly: e.target.checked })} />
|
||||
<span>Heti összefoglaló vasárnap este: a hét legélénkebb szálai</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
)}
|
||||
|
||||
<div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={busy}
|
||||
onClick={() => void save(settings, "Elmentettük a beállításaidat.")}
|
||||
>
|
||||
{busy ? "Mentés…" : "Mentés"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn"
|
||||
disabled={busy}
|
||||
onClick={() => void save(allOff(settings), "Leiratkoztál: ezekről nem küldünk több levelet.")}
|
||||
>
|
||||
Mindenről leiratkozom
|
||||
</button>
|
||||
</div>
|
||||
{saved && (
|
||||
<p className="msg msg-ok" role="status">
|
||||
{saved}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
A jelszóval, a vásárlással és a számlával kapcsolatos leveleket ettől függetlenül megkapod.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { MailSettings } from "./MailSettings";
|
||||
|
||||
export const metadata: Metadata = { title: "Értesítések", robots: { index: false } };
|
||||
|
||||
/** Every e-mail setting, from the link in an e-mail's footer (no login needed). */
|
||||
export default async function MailSettingsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | string[]>>;
|
||||
}) {
|
||||
const raw = (await searchParams).token;
|
||||
const token = Array.isArray(raw) ? raw[0] : raw;
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 640 }}>
|
||||
<div className="page-head">
|
||||
<h1>Értesítések</h1>
|
||||
<p className="muted">Itt állíthatod be, miről kérsz levelet a Sorsfonalaktól.</p>
|
||||
</div>
|
||||
<MailSettings token={token ?? null} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -6,14 +6,30 @@ import { notFound } from "next/navigation";
|
||||
import { ForumNav } from "@/components/forum/ForumNav";
|
||||
import { ThemeToggle } from "@/components/forum/ThemeToggle";
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
||||
import { FORUM_PREVIEW, FORUM_THEME_COOKIE, type ForumNavData, type ForumTheme } from "@/lib/forum";
|
||||
import { forumEnabled, forumGet } from "@/lib/forumServer";
|
||||
|
||||
import "./forum.css";
|
||||
|
||||
const DESCRIPTION = "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "Fórum", template: "%s · Fórum · Sorsfonalak" },
|
||||
description: "Spirituális fórum a Sorsfonalakon: beszélgetés, meghallgatás, asztrológia, álmok.",
|
||||
description: DESCRIPTION,
|
||||
openGraph: {
|
||||
type: "website",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
title: "Sorsfonalak fórum",
|
||||
description: DESCRIPTION,
|
||||
images: [FORUM_PREVIEW],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: "Sorsfonalak fórum",
|
||||
description: DESCRIPTION,
|
||||
images: [FORUM_PREVIEW.url],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
||||
import { notFound, permanentRedirect, redirect } from "next/navigation";
|
||||
|
||||
import { ThreadView } from "@/components/forum/ThreadView";
|
||||
import type { ThreadPage } from "@/lib/forum";
|
||||
import { FORUM_PREVIEW, type ThreadPage } from "@/lib/forum";
|
||||
import { forumGet } from "@/lib/forumServer";
|
||||
|
||||
type Props = { params: Promise<{ id: string }> };
|
||||
@@ -19,18 +19,42 @@ async function load(param: string) {
|
||||
return forumGet<ThreadPage>(`/v1/forum/threads/${id}`);
|
||||
}
|
||||
|
||||
/** The start of a post for a description: one line, cut at a word, at most `max` characters. */
|
||||
function excerpt(text: string, max: number): string {
|
||||
const line = text.replace(/\s+/g, " ").trim();
|
||||
if (line.length <= max) return line;
|
||||
const cut = line.slice(0, max - 1);
|
||||
const words = cut.slice(0, Math.max(cut.lastIndexOf(" "), max / 2)).trimEnd();
|
||||
return `${words.replace(/[.,;:!?–-]+$/, "")}…`;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const res = await load((await params).id);
|
||||
if (!res?.ok) return { title: "Fórum", robots: { index: false } };
|
||||
const { thread, posts } = res.data;
|
||||
const open = thread.topic.visibility === "public" && !thread.deleted;
|
||||
const opening = posts.find((p) => p.is_opening)?.body ?? "";
|
||||
const url = `/forum/szal/${thread.id}-${thread.slug}`;
|
||||
// The link preview: a public thread's title and opening words; of a
|
||||
// members-only or removed one nothing (link previews are public).
|
||||
const preview = open
|
||||
? { title: thread.title, description: excerpt(opening, 200) }
|
||||
: { title: "Sorsfonalak fórum", description: "Beszélgetés a Sorsfonalak fórumán." };
|
||||
return {
|
||||
title: thread.title,
|
||||
description: open ? opening.slice(0, 160) : undefined,
|
||||
alternates: { canonical: `/forum/szal/${thread.id}-${thread.slug}` },
|
||||
description: open ? excerpt(opening, 160) : undefined,
|
||||
alternates: { canonical: url },
|
||||
// Members-only topics and removed threads stay out of search engines.
|
||||
robots: open ? undefined : { index: false, follow: false },
|
||||
openGraph: {
|
||||
type: "article",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
url,
|
||||
...preview,
|
||||
images: [FORUM_PREVIEW],
|
||||
},
|
||||
twitter: { card: "summary_large_image", ...preview, images: [FORUM_PREVIEW.url] },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1034,8 +1034,6 @@ a.pair-row:hover strong { color: var(--gold); }
|
||||
.lp-caption { display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
|
||||
.lp-caption .share-trio { justify-content: center; font-size: 15px; }
|
||||
.lp-asc { color: var(--gold); font-weight: 600; font-size: 12px; letter-spacing: 0.5px; }
|
||||
.lp-rise { opacity: 0; transform: translateY(14px); animation: lp-rise 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) forwards; }
|
||||
.lp-r1 { animation-delay: 0.1s; } .lp-r2 { animation-delay: 0.25s; } .lp-r3 { animation-delay: 0.4s; } .lp-r4 { animation-delay: 0.55s; }
|
||||
|
||||
.lp-band { border-top: 1px solid var(--line); padding: 96px 0; }
|
||||
.lp-alt { background: var(--panel-2); }
|
||||
@@ -1112,7 +1110,6 @@ body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
||||
@keyframes lp-fade { to { opacity: 1; } }
|
||||
@keyframes lp-draw { to { stroke-dashoffset: 0; } }
|
||||
@keyframes lp-spin { to { transform: rotate(360deg); } }
|
||||
@keyframes lp-rise { to { opacity: 1; transform: none; } }
|
||||
@keyframes lp-float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }
|
||||
@keyframes lp-pulse { 0%, 100% { transform: scale(1); opacity: 0.9; } 50% { transform: scale(1.6); opacity: 0.2; } }
|
||||
@media (max-width: 900px) { .lp-analysis-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||
@@ -1141,7 +1138,7 @@ body:has(.qdock-fab) .site-footer { padding-bottom: 88px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lp *, .lp-orbit { animation: none !important; }
|
||||
.lp-rise, .lp-wheel .w-point { opacity: 1; transform: none; }
|
||||
.lp-wheel .w-point { opacity: 1; transform: none; }
|
||||
.lp-wheel .w-aspect { stroke-dashoffset: 0; }
|
||||
.lp-wheel .w-aspect.w-asp-sextile { opacity: 1; }
|
||||
}
|
||||
@@ -1410,7 +1407,7 @@ span.tarot-fan-card { cursor: default; }
|
||||
}
|
||||
|
||||
/* The ☰ menu: instead of the header's link rows where they no longer fit
|
||||
on one line (logged out below 1240px; logged in below 1380px, with more
|
||||
on one line (logged out below 1240px; logged in below 1520px, with more
|
||||
links and the package). */
|
||||
.mobile-menu { display: none; margin-left: auto; }
|
||||
.mobile-menu-button {
|
||||
@@ -1439,7 +1436,7 @@ span.tarot-fan-card { cursor: default; }
|
||||
@media (max-width: 1500px) {
|
||||
.site-header .pkg-pill-detail { display: none; }
|
||||
}
|
||||
@media (max-width: 1380px) {
|
||||
@media (max-width: 1520px) {
|
||||
.mobile-menu-app { display: block; }
|
||||
.site-header .app-nav { display: none; }
|
||||
.site-header .who { margin-left: auto; }
|
||||
@@ -1853,3 +1850,89 @@ span.tarot-fan-card { cursor: default; }
|
||||
.update-note-later { border: 0; background: none; color: var(--ink-2, #c9cfdc); font: inherit; font-size: 14px; cursor: pointer; padding: 6px; }
|
||||
.update-note-later:hover { color: var(--gold); }
|
||||
@media (max-width: 479px) { .update-note { flex-wrap: wrap; justify-content: center; text-align: center; } }
|
||||
|
||||
/* Login inside Facebook's or another app's built-in browser: why, and the way out. */
|
||||
.inapp-note {
|
||||
display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; font-size: 14px;
|
||||
border: 1px solid rgba(217, 180, 106, 0.45); background: rgba(217, 180, 106, 0.07); border-radius: 10px;
|
||||
}
|
||||
.inapp-note p { margin: 0; color: var(--ink-2); }
|
||||
.inapp-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||
|
||||
/* The weekly horoscope page (one month at a time) and its link on the chart page. */
|
||||
.weekly-card { gap: 10px; }
|
||||
.weekly-text p { margin: 0 0 10px; }
|
||||
.weekly-text p:last-child { margin-bottom: 0; }
|
||||
.weekly-pager { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 10px; }
|
||||
.weekly-pager > :first-child { justify-self: start; }
|
||||
.weekly-pager > :last-child { justify-self: end; }
|
||||
.weekly-pager strong { font-family: var(--font-display); font-size: 22px; font-weight: 600; text-align: center; }
|
||||
.weekly-teaser { display: flex; flex-direction: column; gap: 6px; text-decoration: none; color: var(--ink-2); border-color: rgba(217, 180, 106, 0.35); }
|
||||
.weekly-teaser:hover { border-color: var(--gold); }
|
||||
.weekly-teaser-more { color: var(--gold); font-weight: 500; }
|
||||
@media (max-width: 480px) {
|
||||
.weekly-pager { grid-template-columns: 1fr 1fr; }
|
||||
.weekly-pager strong { grid-column: 1 / -1; grid-row: 1; }
|
||||
}
|
||||
|
||||
/* The e-mail settings behind an e-mail's footer link. */
|
||||
.mail-set { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
|
||||
.mail-set legend { font-family: var(--font-display); font-size: 20px; font-weight: 600; margin-bottom: 4px; }
|
||||
.mail-set label:not(.check) { font-size: 14px; color: var(--ink-2); margin-top: 6px; }
|
||||
.weekly-landing-lead { font-size: 17px; line-height: 1.6; max-width: 640px; }
|
||||
.weekly-landing-actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 6px; }
|
||||
.weekly-steps { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 10px; color: var(--ink-2); line-height: 1.55; }
|
||||
.weekly-steps strong { color: var(--ink); font-weight: 600; }
|
||||
|
||||
/* Admin → Statisztika: stat tiles, day-by-day small charts (one gold series
|
||||
each, the same days), horizontal bars with the value at the end. */
|
||||
.stats-filter { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
.stats-filter .hint { margin-left: 4px; }
|
||||
.stats-totals strong { color: var(--ink); font-weight: 600; }
|
||||
.stats-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; margin: 0; }
|
||||
.stats-tiles > div {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px;
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
}
|
||||
.stats-tiles dt { font-size: 13px; color: var(--muted); }
|
||||
.stats-tiles dd { margin: 0; }
|
||||
.stats-tile-value { font-size: 26px; font-weight: 600; line-height: 1.2; color: var(--ink); }
|
||||
.stats-tile-sub { font-size: 12px; color: var(--muted); }
|
||||
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 440px), 1fr)); gap: 18px; align-items: start; }
|
||||
.stats-readout { font-size: 14px; color: var(--ink-2); min-height: 44px; }
|
||||
.stats-readout strong { color: var(--ink); font-weight: 600; }
|
||||
.stats-daily { display: flex; flex-direction: column; gap: 10px; touch-action: pan-y; }
|
||||
.spark { display: grid; grid-template-columns: 150px minmax(0, 1fr); gap: 12px; align-items: end; }
|
||||
.spark-head { display: flex; flex-direction: column; font-size: 13px; color: var(--muted); padding-bottom: 2px; }
|
||||
.spark-head strong { font-size: 18px; color: var(--ink); font-weight: 600; }
|
||||
.spark-plot { position: relative; height: 52px; border-bottom: 1px solid var(--line-2); }
|
||||
.spark-max { position: absolute; top: -2px; right: 0; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.spark-bars { display: flex; height: 100%; align-items: stretch; padding-top: 14px; }
|
||||
.spark-col { flex: 1 1 0; min-width: 0; display: flex; align-items: flex-end; justify-content: center; padding: 0 1px; cursor: default; }
|
||||
.spark-col.is-on { background: rgba(217, 180, 106, 0.1); }
|
||||
.spark-bar { display: block; width: 100%; max-width: 24px; background: var(--gold); border-radius: 4px 4px 0 0; }
|
||||
.spark-col.is-on .spark-bar { background: var(--gold-hover); }
|
||||
.spark-axis { display: flex; justify-content: space-between; margin-left: 162px; font-size: 12px; color: var(--muted); }
|
||||
.hbar { display: flex; align-items: center; gap: 8px; min-width: 120px; }
|
||||
.hbar-track { flex: 1 1 auto; height: 12px; display: flex; }
|
||||
.hbar-fill { display: block; height: 100%; background: var(--gold); border-radius: 0 4px 4px 0; }
|
||||
.hbar-value { font-size: 13px; color: var(--ink-2); white-space: nowrap; font-variant-numeric: tabular-nums; min-width: 64px; }
|
||||
.funnel { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.funnel li { display: grid; grid-template-columns: minmax(0, 210px) minmax(0, 1fr); gap: 12px; align-items: center; font-size: 14px; }
|
||||
.stats-sources td { vertical-align: middle; }
|
||||
.stats-split { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; }
|
||||
.stats-h3 { font-family: var(--font-body); font-size: 14px; font-weight: 600; color: var(--ink-2); margin-bottom: 6px; }
|
||||
.stats-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 14px; }
|
||||
.stats-list li { display: flex; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--line); padding: 4px 0; }
|
||||
.stats-list code { overflow-wrap: anywhere; }
|
||||
@media (max-width: 620px) {
|
||||
.spark { grid-template-columns: minmax(0, 1fr); gap: 4px; }
|
||||
.spark-head { flex-direction: row; justify-content: space-between; align-items: baseline; }
|
||||
.spark-axis { margin-left: 0; }
|
||||
.funnel li { grid-template-columns: minmax(0, 1fr); gap: 4px; }
|
||||
}
|
||||
|
||||
/* The OAuth approval page (/oauth/engedely). */
|
||||
.oauth-scope { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.oauth-actions { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
|
||||
.oauth-actions .msg { flex-basis: 100%; }
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { Paragraphs } from "@/components/Rich";
|
||||
import example from "@/content/pelda-heti.json";
|
||||
import { weekRange } from "@/lib/weekly";
|
||||
|
||||
const LOGIN = "/belepes?vissza=/heti-horoszkop";
|
||||
|
||||
/**
|
||||
* The weekly horoscope for visitors: what it is, a real example written for
|
||||
* the example chart (the one of the Példaelemzés page), and the way in.
|
||||
*/
|
||||
export function WeeklyLanding() {
|
||||
return (
|
||||
<main className="page weekly-landing" style={{ maxWidth: 820 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Ingyenes · hétfőnként új</span>
|
||||
<h1>Heti horoszkóp, ami rólad szól</h1>
|
||||
<p className="muted weekly-landing-lead">
|
||||
Nem a csillagjegyedre írt általános szöveg: a hét égboltját a saját születési képletedre vetítjük. Melyik
|
||||
bolygó milyen fényszöget alkot a te pontjaiddal, melyik napon, és mit kérhet tőled a héten.
|
||||
</p>
|
||||
<div className="weekly-landing-actions">
|
||||
<Link href={LOGIN} className="btn btn-primary lp-btn">
|
||||
Belépés
|
||||
</Link>
|
||||
<Link href={`/belepes?mod=regisztracio&vissza=/heti-horoszkop`} className="btn lp-btn">
|
||||
Regisztráció
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<article className="card summary-card weekly-card" aria-labelledby="weekly-example-title">
|
||||
<span className="eyebrow">Példa · {weekRange(example.week_start, example.week_end)}</span>
|
||||
<h2 id="weekly-example-title" className="summary-title">
|
||||
{example.title}
|
||||
</h2>
|
||||
<div className="summary-text weekly-text" lang="hu">
|
||||
<Paragraphs text={example.text} />
|
||||
</div>
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
Ezt a heti horoszkópot a <Link href="/pelda">példaelemzés</Link> kitalált képletéhez írtuk (1990. március 15.,
|
||||
14:30, Szeged), ugyanúgy, ahogy a tiédet is megírjuk.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<section className="card field weekly-how" aria-labelledby="weekly-how-title" style={{ gap: 12 }}>
|
||||
<h2 id="weekly-how-title">Hogyan működik?</h2>
|
||||
<ol className="weekly-steps">
|
||||
<li>
|
||||
<strong>Megadod, mikor és hol születtél.</strong> Ebből percre pontosan kiszámoljuk a születési képletedet.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Hétfőnként új heti horoszkópot kapsz,</strong> a te képletedből és a hét égboltjából: a hét fő
|
||||
témája, a kulcsnapok és egy javaslat.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Hétfő reggel e-mailben szólunk,</strong> hogy itt az új. Ha nem kéred, egy kattintással
|
||||
kikapcsolhatod.
|
||||
</li>
|
||||
</ol>
|
||||
<div>
|
||||
<Link href={LOGIN} className="btn btn-primary">
|
||||
Belépés, és kérem a heti horoszkópomat
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { WeekCard, WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
import { MONTHS } from "@/lib/weekly";
|
||||
|
||||
const POLL_MS = 3000;
|
||||
const MAX_POLLS = 60;
|
||||
|
||||
interface Week {
|
||||
week_start: string;
|
||||
week_end: string;
|
||||
analysis: Analysis;
|
||||
}
|
||||
|
||||
interface Month {
|
||||
month: string;
|
||||
current_month: string;
|
||||
this_week: string;
|
||||
weeks: Week[];
|
||||
older: string | null;
|
||||
newer: string | null;
|
||||
email: boolean;
|
||||
}
|
||||
|
||||
/** "2026. november". */
|
||||
function monthName(key: string): string {
|
||||
const [y, m] = key.split("-").map(Number);
|
||||
return `${y}. ${MONTHS[m - 1]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One month of weekly horoscopes, the newest week first. In this month the
|
||||
* week's horoscope is asked for first (queued if new), then read until the
|
||||
* worker has written it (or given up); meanwhile its card shows the waiting
|
||||
* animation.
|
||||
*/
|
||||
export function WeeklyPage({ month, isAdmin }: { month: string | null; isAdmin: boolean }) {
|
||||
const [data, setData] = useState<Month | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [gaveUp, setGaveUp] = useState(false);
|
||||
// Bumped when an admin has this week's text written again: polls anew.
|
||||
const [round, setRound] = useState(0);
|
||||
const query = month ? `?month=${month}` : "";
|
||||
|
||||
/** This week's horoscope into the list (it may not be there yet). */
|
||||
const putWeek = (week: Week) =>
|
||||
setData((d) => (d ? { ...d, weeks: [week, ...d.weeks.filter((w) => w.week_start !== week.week_start)] } : d));
|
||||
|
||||
useEffect(() => {
|
||||
let stopped = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const wait = () => new Promise((resolve) => (timer = setTimeout(resolve, POLL_MS)));
|
||||
/**
|
||||
* This week's text: asked for once (queued if new, or written again if
|
||||
* the last attempt failed), then only read until the worker is done.
|
||||
*/
|
||||
const follow = async () => {
|
||||
let week: Week | null = null;
|
||||
for (let tries = 0; !week && tries < 5 && !stopped; tries++) {
|
||||
try {
|
||||
const got = await api<Week & { email: boolean }>("/weekly", { method: "POST" });
|
||||
week = { week_start: got.week_start, week_end: got.week_end, analysis: got.analysis };
|
||||
} catch {
|
||||
await wait();
|
||||
}
|
||||
}
|
||||
if (!week || stopped) return setGaveUp(!stopped);
|
||||
putWeek(week);
|
||||
for (let polls = 0; !stopped; polls++) {
|
||||
const { status } = week.analysis;
|
||||
if (status === "done" || status === "failed") return;
|
||||
if (polls >= MAX_POLLS) return setGaveUp(true);
|
||||
await wait();
|
||||
try {
|
||||
const id: string = week.analysis.id;
|
||||
const analysis: Analysis = await api<Analysis>(`/analyses/${id}`);
|
||||
if (stopped) return;
|
||||
week = { ...week, analysis };
|
||||
putWeek(week);
|
||||
} catch {
|
||||
// try again on the next tick
|
||||
}
|
||||
}
|
||||
};
|
||||
(async () => {
|
||||
try {
|
||||
const page = await api<Month>(`/weekly/history${query}`);
|
||||
if (stopped) return;
|
||||
setData(page);
|
||||
if (page.month === page.current_month) await follow();
|
||||
} catch (e) {
|
||||
if (!stopped) setError(errorText(e));
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [query, round]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (!data) {
|
||||
return <p className="muted">Betöltés…</p>;
|
||||
}
|
||||
|
||||
const restarted = (week: Week) => (a: Analysis) => {
|
||||
setGaveUp(false);
|
||||
setData((d) =>
|
||||
d ? { ...d, weeks: d.weeks.map((w) => (w.week_start === week.week_start ? { ...w, analysis: a } : w)) } : d,
|
||||
);
|
||||
if (week.week_start === data.this_week) setRound((r) => r + 1);
|
||||
};
|
||||
|
||||
const pager = (
|
||||
<nav className="weekly-pager" aria-label="Hónapok">
|
||||
{data.older ? (
|
||||
<Link href={`/heti-horoszkop?honap=${data.older}`} className="btn btn-sm">
|
||||
← Korábbi hónap
|
||||
</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<strong>{monthName(data.month)}</strong>
|
||||
{data.newer ? (
|
||||
<Link
|
||||
href={data.newer === data.current_month ? "/heti-horoszkop" : `/heti-horoszkop?honap=${data.newer}`}
|
||||
className="btn btn-sm"
|
||||
>
|
||||
Újabb hónap →
|
||||
</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="field" style={{ gap: 18 }}>
|
||||
{pager}
|
||||
{data.weeks.length === 0 ? (
|
||||
<p className="muted">Ebben a hónapban nem nézted meg a heti horoszkópodat.</p>
|
||||
) : (
|
||||
data.weeks.map((w) => (
|
||||
<WeekCard
|
||||
key={w.week_start}
|
||||
start={w.week_start}
|
||||
end={w.week_end}
|
||||
analysis={w.analysis}
|
||||
current={w.week_start === data.this_week}
|
||||
gaveUp={w.week_start === data.this_week && gaveUp}
|
||||
isAdmin={isAdmin}
|
||||
onRestarted={restarted(w)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
{(data.older || data.newer) && data.weeks.length > 1 && pager}
|
||||
<div className="card">
|
||||
<WeeklyEmailSwitch initial={data.email} label="Hétfőnként szóljatok e-mailben, ha itt az új heti horoszkópom" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { PublicHeader } from "@/components/SiteHeader";
|
||||
import { getMe } from "@/lib/server";
|
||||
import { siteUrl } from "@/lib/share";
|
||||
|
||||
import { WeeklyLanding } from "./Landing";
|
||||
import { WeeklyPage } from "./WeeklyPage";
|
||||
|
||||
/** Bumped when the preview image changes, so Facebook and co. fetch it again. */
|
||||
const PREVIEW_VERSION = 1;
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const base = await siteUrl();
|
||||
const title = "Heti horoszkóp, ami rólad szól";
|
||||
const description =
|
||||
"Ingyenes, hétfőnként új személyes heti horoszkóp a saját születési képletedből és a hét égboltjából: a hét fő témája, a kulcsnapok és egy javaslat.";
|
||||
const image = { url: `${base}/kep/heti-horoszkop.png?v=${PREVIEW_VERSION}`, width: 1200, height: 630, alt: title };
|
||||
return {
|
||||
title: "Heti horoszkóp",
|
||||
description,
|
||||
alternates: { canonical: `${base}/heti-horoszkop` },
|
||||
openGraph: {
|
||||
type: "website",
|
||||
siteName: "Sorsfonalak",
|
||||
locale: "hu_HU",
|
||||
url: `${base}/heti-horoszkop`,
|
||||
title,
|
||||
description,
|
||||
images: [image],
|
||||
},
|
||||
twitter: { card: "summary_large_image", title, description, images: [image.url] },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The weekly horoscope. Members: their own, one month at a time, the newest
|
||||
* first (`?honap=2026-11` pages back); this week's is written when the page
|
||||
* opens. Visitors: what it is, with an example, and the way in.
|
||||
*/
|
||||
export default async function WeeklyHoroscopePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | string[]>>;
|
||||
}) {
|
||||
const me = await getMe();
|
||||
if (!me) {
|
||||
return (
|
||||
<>
|
||||
<PublicHeader />
|
||||
<WeeklyLanding />
|
||||
</>
|
||||
);
|
||||
}
|
||||
const raw = (await searchParams).honap;
|
||||
const month = (Array.isArray(raw) ? raw[0] : raw) ?? null;
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 760 }}>
|
||||
<div className="page-head">
|
||||
<h1>Heti horoszkóp</h1>
|
||||
<p className="muted">Hétfőnként új, a saját képletedből és a hét égboltjából.</p>
|
||||
</div>
|
||||
{me.primary_chart_id ? (
|
||||
<WeeklyPage
|
||||
key={month ?? "now"}
|
||||
month={month && /^\d{4}-\d{2}$/.test(month) ? month : null}
|
||||
isAdmin={me.user.roles.includes("admin")}
|
||||
/>
|
||||
) : (
|
||||
<div className="card field" style={{ gap: 12 }}>
|
||||
<p style={{ margin: 0 }}>A heti horoszkóphoz előbb add meg a születési adataidat.</p>
|
||||
<div>
|
||||
<Link href="/profil#birth" className="btn btn-primary">
|
||||
Születési adatok megadása
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// The link preview image of the forum's pages (og:image), drawn from the
|
||||
// example chart. The pages link it with a version (?v=…).
|
||||
import example from "@/content/pelda.json";
|
||||
import { chartCard } from "@/lib/ogCard";
|
||||
import type { ChartResult } from "@/lib/types";
|
||||
|
||||
export async function GET() {
|
||||
return chartCard({
|
||||
chart: example.chart as unknown as ChartResult,
|
||||
timeKnown: true,
|
||||
eyebrow: "SORSFONALAK FÓRUM",
|
||||
title: "Ahol meghallgatnak.",
|
||||
text: "Beszélgetés, meghallgatás, asztrológia és álmok: egy nyugodt, figyelmes közösség.",
|
||||
lines: [
|
||||
{ glyph: "☽", label: "Meghallgatás" },
|
||||
{ glyph: "☿", label: "Beszélgetés" },
|
||||
{ glyph: "♀", label: "Asztrológia" },
|
||||
],
|
||||
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// The link preview image of the weekly horoscope page (og:image), drawn from
|
||||
// the example chart. The page links it with a version (?v=…).
|
||||
import example from "@/content/pelda.json";
|
||||
import { chartCard } from "@/lib/ogCard";
|
||||
import type { ChartResult } from "@/lib/types";
|
||||
|
||||
export async function GET() {
|
||||
return chartCard({
|
||||
chart: example.chart as unknown as ChartResult,
|
||||
timeKnown: true,
|
||||
eyebrow: "HETI HOROSZKÓP",
|
||||
title: "A te heted, nem a csillagjegyedé.",
|
||||
text: "Hétfőnként új, személyes horoszkóp a saját születési képletedből és a hét égboltjából. Ingyenes.",
|
||||
lines: [
|
||||
{ glyph: "☉", label: "A saját képletedből" },
|
||||
{ glyph: "☽", label: "A hét égboltjából" },
|
||||
{ glyph: "☿", label: "Hétfőnként új" },
|
||||
],
|
||||
cacheControl: "public, max-age=86400, s-maxage=604800",
|
||||
});
|
||||
}
|
||||
@@ -87,6 +87,15 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
||||
referralOpen={config?.referral_rewards ?? false}
|
||||
referralsLeft={me.referral_rewards.limit - me.referral_rewards.earned}
|
||||
/>
|
||||
{chart.id === me.primary_chart_id && (
|
||||
<Link href="/heti-horoszkop" className="card weekly-teaser">
|
||||
<span className="eyebrow">Heti horoszkóp</span>
|
||||
<span>Hétfőnként új, a saját képletedből és a hét égboltjából.</span>
|
||||
<span className="weekly-teaser-more">
|
||||
Elolvasom a heti horoszkópomat<span aria-hidden="true"> →</span>
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
<BigThree chart={chart} />
|
||||
{forumEnabled() && (
|
||||
<div className="card ask-forum-card">
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from "next";
|
||||
import { Cormorant_Garamond, Inter } from "next/font/google";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { Arrival } from "@/components/Arrival";
|
||||
import { DialogHost } from "@/components/Dialogs";
|
||||
import { KeyboardSafe } from "@/components/KeyboardSafe";
|
||||
import { NightSky } from "@/components/NightSky";
|
||||
@@ -45,6 +46,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<html lang="hu" className={`${cormorant.variable} ${inter.variable}`}>
|
||||
<body>
|
||||
<NightSky />
|
||||
<Arrival />
|
||||
<KeyboardSafe />
|
||||
<VersionWatcher />
|
||||
<DialogHost />
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
|
||||
export type OauthParams = Partial<
|
||||
Record<
|
||||
| "response_type"
|
||||
| "client_id"
|
||||
| "redirect_uri"
|
||||
| "code_challenge"
|
||||
| "code_challenge_method"
|
||||
| "scope"
|
||||
| "state"
|
||||
| "resource",
|
||||
string
|
||||
>
|
||||
>;
|
||||
|
||||
/** The admin's answer: the backend gives the address back to the client (with a code, or a refusal). */
|
||||
export function Approve({ params }: { params: OauthParams }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function answer(deny: boolean) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const r = await api<{ redirect_to: string }>("/oauth/authorize", { body: { ...params, deny } });
|
||||
window.location.assign(r.redirect_to);
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="oauth-actions">
|
||||
<button type="button" className="btn btn-primary" disabled={busy} onClick={() => answer(false)}>
|
||||
Engedélyezem
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={busy} onClick={() => answer(true)}>
|
||||
Mégse
|
||||
</button>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { Metadata } from "next";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { BACKEND_URL, getMe } from "@/lib/server";
|
||||
|
||||
import { Approve, type OauthParams } from "./Approve";
|
||||
|
||||
export const metadata: Metadata = { title: "Claude összekötése", robots: { index: false } };
|
||||
|
||||
type Props = { searchParams: Promise<Record<string, string | string[] | undefined>> };
|
||||
|
||||
const PARAMS = [
|
||||
"response_type",
|
||||
"client_id",
|
||||
"redirect_uri",
|
||||
"code_challenge",
|
||||
"code_challenge_method",
|
||||
"scope",
|
||||
"state",
|
||||
"resource",
|
||||
] as const;
|
||||
|
||||
interface Check {
|
||||
client_name: string;
|
||||
redirect_host: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The OAuth approval page (docs/mcp.md): Claude sends the admin here to
|
||||
* connect the admin tools. The backend checks the request first; only an
|
||||
* admin may approve it.
|
||||
*/
|
||||
export default async function OauthApprovalPage({ searchParams }: Props) {
|
||||
const raw = await searchParams;
|
||||
const params: OauthParams = {};
|
||||
const query = new URLSearchParams();
|
||||
for (const name of PARAMS) {
|
||||
const value = Array.isArray(raw[name]) ? raw[name][0] : raw[name];
|
||||
if (value !== undefined) {
|
||||
params[name] = value;
|
||||
query.set(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
let check: Check | null = null;
|
||||
let problem = "A kérés nem érkezett meg rendesen.";
|
||||
try {
|
||||
const res = await fetch(`${BACKEND_URL}/v1/oauth/authorize?${query}`, { cache: "no-store" });
|
||||
const body = await res.json();
|
||||
if (res.ok) check = body as Check;
|
||||
else problem = body?.error?.message ?? problem;
|
||||
} catch {
|
||||
problem = "A szerver most nem érhető el. Próbáld újra.";
|
||||
}
|
||||
|
||||
if (!check) {
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 560 }}>
|
||||
<div className="page-head">
|
||||
<h1>Az összekötés nem sikerült</h1>
|
||||
<p className="muted">{problem}</p>
|
||||
<p className="hint">Próbáld újra az összekötést Claude-ban.</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const me = await getMe();
|
||||
if (!me) redirect(`/belepes?vissza=${encodeURIComponent(`/oauth/engedely?${query}`)}`);
|
||||
if (!me.user.roles.includes("admin")) {
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 560 }}>
|
||||
<div className="page-head">
|
||||
<h1>Ehhez admin fiók kell</h1>
|
||||
<p className="muted">Az admin eszközöket csak admin fiókkal lehet Claude-dal összekötni.</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="page" style={{ maxWidth: 560 }}>
|
||||
<div className="page-head">
|
||||
<span className="eyebrow">Admin eszközök</span>
|
||||
<h1>{check.client_name} hozzáférést kér</h1>
|
||||
</div>
|
||||
<section className="card">
|
||||
<p>
|
||||
Ha engedélyezed, a(z) <strong>{check.client_name}</strong> a te admin jogoddal használhatja a Sorsfonalak
|
||||
admin eszközeit.
|
||||
</p>
|
||||
<ul className="oauth-scope">
|
||||
<li>
|
||||
Lekérdezheti a statisztikát, a visszajelzéseket, az értékeléseket, a hibanaplót, a háttérfeladatokat, a
|
||||
tagokat, a promókódokat és a meghívókat. A tagok e-mail-címe és neve rejtve marad.
|
||||
</li>
|
||||
<li>
|
||||
Elvégezheti a napi teendőket: promókód készítése, visszajelzés megválaszolása, feladat újraindítása, hiba
|
||||
törlése, meghívó küldése, fórumbejelentés lezárása, kitiltás. Minden ilyen lépés előtt rákérdez.
|
||||
</li>
|
||||
<li>Szerepkört, kreditet, csomagot, promptot és modellt nem módosíthat: ezek az admin oldalon maradnak.</li>
|
||||
</ul>
|
||||
{check.redirect_host && <p className="hint">Engedélyezés után visszakerülsz ide: {check.redirect_host}.</p>}
|
||||
<p className="hint">A kapcsolatot bármikor visszavonhatod: Admin → Claude.</p>
|
||||
<Approve params={params} />
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -124,6 +124,21 @@ const DATA: [string, string, string][] = [
|
||||
"Security, troubleshooting, preventing abuse",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"Weekly horoscope: the week's sky on your own chart, the text written from it, and whether you want the Monday notice e-mail",
|
||||
"The free weekly horoscope; a short e-mail on Mondays that the new one is there (sent by default; turn it off at any time in the e-mail's footer, on the Weekly horoscope page or on your Profile page)",
|
||||
"Performance of the contract; for the e-mail, legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"At sign-up: where you came to the site from (for example Facebook or a Google search, another site's address without its path, or the link's campaign tag), and whether from a phone, a tablet or a computer",
|
||||
"Statistics: seeing where members come from, and which of our posts or ads work",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
[
|
||||
"Which page you opened, where you came from, your browser and device type, your country and how long the page took to load (visitor statistics)",
|
||||
"Seeing how many people view each page and whether the site is fast enough",
|
||||
"Legitimate interest (Art. 6(1)(f))",
|
||||
],
|
||||
];
|
||||
|
||||
/** The privacy policy in English (the Hungarian one at /adatvedelem is the same in content). */
|
||||
@@ -229,7 +244,8 @@ export default async function PrivacyPolicyPage() {
|
||||
<p>
|
||||
<strong>How we use it:</strong> to create your account and recognise you when you sign in; your e-mail address
|
||||
for service e-mails (for example when a reading is ready, an invitation was accepted, or someone replied on the
|
||||
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these); your name for
|
||||
forum, when someone mentions you there, or the forum's weekly summary, if you asked for these) and for the
|
||||
weekly horoscope's Monday notice (unless you turned it off); your name for
|
||||
display;
|
||||
your language for the language of the site and your readings.
|
||||
</p>
|
||||
@@ -271,10 +287,11 @@ export default async function PrivacyPolicyPage() {
|
||||
<section>
|
||||
<h2>4. Readings and artificial intelligence</h2>
|
||||
<p>
|
||||
The short summary, the detailed readings, tarot readings and the answers to your questions are written by a
|
||||
large language model (artificial intelligence). The model receives the{" "}
|
||||
The short summary, the weekly horoscope, the detailed readings, tarot readings and the answers to your
|
||||
questions are written by a large language model (artificial intelligence). The model receives the{" "}
|
||||
<strong>astronomical data of the chart</strong> (the signs, degrees, houses and aspects of the planets), for
|
||||
a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail
|
||||
the weekly horoscope also the week's sky (where the planets are and the aspects they make to your chart),
|
||||
for a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail
|
||||
address, birth date, time or place. Please do not write names or sensitive data (such as health data) into
|
||||
your questions either. The readings are for entertainment and self-reflection and are not medical,
|
||||
financial, legal or other professional advice.
|
||||
@@ -305,6 +322,8 @@ export default async function PrivacyPolicyPage() {
|
||||
<strong>Cloudflare, Inc.</strong>: delivering traffic and protecting against attacks; processes your IP
|
||||
address and request data when the site loads. On the e-mail sign-up and password request forms its
|
||||
Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
|
||||
Its Web Analytics service measures visits and page speed without cookies or any identifier stored in the
|
||||
browser, and does not follow individual visitors.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Google LLC</strong>: signing in with a Google account.
|
||||
@@ -369,7 +388,18 @@ export default async function PrivacyPolicyPage() {
|
||||
<p>
|
||||
We use a cookie that is strictly necessary for the service (<code>sf_session</code>), which keeps you signed
|
||||
in. If you choose the light or dark theme on the forum, a second cookie (<code>sf_forum_theme</code>) keeps
|
||||
your choice for a year; it stores nothing else. We use no advertising or tracking cookies and no analytics.
|
||||
your choice for a year; it stores nothing else. We use no advertising or tracking cookies.
|
||||
</p>
|
||||
<p>
|
||||
Visits are counted by Cloudflare Web Analytics, without cookies or any identifier stored in the browser.
|
||||
When a page loads, a small script sends which page you opened, where you came from, your browser and device
|
||||
type, and how long the page took to load. We only see totals and cannot follow individual visitors.
|
||||
</p>
|
||||
<p>
|
||||
If you sign up, we save with your account where you came to the site from and from what kind of device. No
|
||||
cookie and nothing stored in the browser is used for this: the page only remembers it in its own memory
|
||||
during that visit and sends it with the sign-up. Nothing like this is stored about visitors who do not sign
|
||||
up.
|
||||
</p>
|
||||
<p>
|
||||
On the public birth chart page (no account needed), the birth data you enter are sent only for the
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
import { ROLE_LABELS, formatDate } from "@/lib/astro";
|
||||
import { WeeklyEmailSwitch } from "@/components/WeeklyHoroscope";
|
||||
import { backendGet, requireMe } from "@/lib/server";
|
||||
import type { Chart } from "@/lib/types";
|
||||
|
||||
@@ -84,6 +85,18 @@ export default async function ProfilePage() {
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="card" aria-labelledby="levelek-title" id="levelek">
|
||||
<h2 id="levelek-title">Levelek</h2>
|
||||
<WeeklyEmailSwitch
|
||||
initial={me.weekly_email}
|
||||
label="Heti horoszkóp: hétfőnként szólunk e-mailben, ha itt az új"
|
||||
/>
|
||||
<p className="hint" style={{ margin: 0 }}>
|
||||
A levélben csak annyi áll, hogy elkészült; a horoszkópot belépés után a Heti horoszkóp oldalon olvashatod.
|
||||
{!chart && " Ehhez előbb add meg a születési adataidat."}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="card" aria-labelledby="adataim">
|
||||
<h2 id="adataim">Adataim</h2>
|
||||
<p className="muted">
|
||||
|
||||
@@ -16,6 +16,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
return [
|
||||
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
|
||||
{ url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 },
|
||||
{ url: `${base}/heti-horoszkop`, changeFrequency: "weekly", priority: 0.8 },
|
||||
{ url: `${base}/kartyajoslas/pelda`, changeFrequency: "monthly", priority: 0.7 },
|
||||
{ url: `${base}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 },
|
||||
{ url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 },
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { Role } from "@/lib/types";
|
||||
import { FeedbackCount } from "./FeedbackCount";
|
||||
|
||||
const PAGES = [
|
||||
{ href: "/admin/statisztika", label: "Statisztika" },
|
||||
{ href: "/admin", label: "Felhasználók" },
|
||||
{ href: "/admin/meghivok", label: "Meghívók" },
|
||||
{ href: "/admin/promokodok", label: "Promókódok" },
|
||||
@@ -14,6 +15,7 @@ const PAGES = [
|
||||
{ href: "/admin/promptok", label: "Promptok" },
|
||||
{ href: "/admin/modellek", label: "Modellek" },
|
||||
{ href: "/admin/hibak", label: "Hibanapló" },
|
||||
{ href: "/admin/kapcsolatok", label: "Claude" },
|
||||
];
|
||||
|
||||
/** May manage the famous people (an admin or a creator). */
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { rememberArrival } from "@/lib/arrival";
|
||||
|
||||
// Right when the site's code loads in the browser, before any navigation
|
||||
// inside the site changes the address.
|
||||
rememberArrival();
|
||||
|
||||
/** Notes where the visit began (see lib/arrival.ts); draws nothing. */
|
||||
export function Arrival() {
|
||||
return null;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
export type NavIconName =
|
||||
| "chart"
|
||||
| "weekly"
|
||||
| "persons"
|
||||
| "compare"
|
||||
| "tarot"
|
||||
@@ -45,6 +46,13 @@ export function NavIcon({ name }: { name: NavIconName }) {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{name === "weekly" && (
|
||||
<>
|
||||
<rect x="4" y="5" width="16" height="15" rx="2.2" />
|
||||
<path d="M4 9.5h16M8.5 3v4M15.5 3v4" />
|
||||
<path d="M12 12l.9 2 2.1.9-2.1.9-.9 2-.9-2-2.1-.9 2.1-.9z" className="nav-icon-fill" />
|
||||
</>
|
||||
)}
|
||||
{name === "famous" && (
|
||||
<path d="M12 3l2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6 6.6 19.5l1.2-6L3.3 9.3l6.1-.7z" />
|
||||
)}
|
||||
|
||||
@@ -148,11 +148,12 @@ const EXPLORE: NavItem[] = [
|
||||
/**
|
||||
* The header of the logged-in app: the menu with gold marks (the free pages
|
||||
* in one "Felfedezés" dropdown), the Moon today, the package and the account.
|
||||
* Below 1380px the menu moves behind ☰, grouped.
|
||||
* Below 1520px the menu moves behind ☰, grouped.
|
||||
*/
|
||||
export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
|
||||
const own: NavItem[] = [
|
||||
{ href: "/keplet", label: "Képletem", icon: "chart" },
|
||||
{ href: "/heti-horoszkop", label: "Heti horoszkóp", icon: "weekly" },
|
||||
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
|
||||
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
|
||||
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import type { Analysis } from "@/lib/types";
|
||||
import { weekRange } from "@/lib/weekly";
|
||||
|
||||
import { AnalysisLoading } from "./AnalysisLoading";
|
||||
import { RateContent } from "./RateContent";
|
||||
import { RegenerateButton } from "./RegenerateButton";
|
||||
import { RetryNotice } from "./RetryNotice";
|
||||
import { Paragraphs } from "./Rich";
|
||||
|
||||
/**
|
||||
* Monday's e-mail about the weekly horoscope, on or off. Turned on, the first
|
||||
* one comes next Monday.
|
||||
*/
|
||||
export function WeeklyEmailSwitch({ initial, label }: { initial: boolean; label: string }) {
|
||||
const [on, setOn] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => setOn(initial), [initial]);
|
||||
|
||||
async function toggle(next: boolean) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setOn(next);
|
||||
try {
|
||||
await api("/weekly/email", { method: "PUT", body: { on: next } });
|
||||
} catch (e) {
|
||||
setOn(!next);
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="weekly-email">
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={on} disabled={busy} onChange={(e) => void toggle(e.target.checked)} />
|
||||
<span>{label}</span>
|
||||
</label>
|
||||
{error && (
|
||||
<p className="msg msg-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One week's horoscope: the text, or while the worker writes it the waiting
|
||||
* animation (this week's, the page polls it), or a note when it failed.
|
||||
*/
|
||||
export function WeekCard({
|
||||
start,
|
||||
end,
|
||||
analysis,
|
||||
current = false,
|
||||
gaveUp = false,
|
||||
isAdmin = false,
|
||||
onRestarted,
|
||||
}: {
|
||||
start: string;
|
||||
end: string;
|
||||
analysis: Analysis | null;
|
||||
/** This week: marked, and it may still be written. */
|
||||
current?: boolean;
|
||||
/** The page stopped waiting for it. */
|
||||
gaveUp?: boolean;
|
||||
isAdmin?: boolean;
|
||||
onRestarted?: (a: Analysis) => void;
|
||||
}) {
|
||||
const content = analysis?.status === "done" ? analysis.content : null;
|
||||
const titleId = `week-${start}`;
|
||||
return (
|
||||
<article
|
||||
className={current ? "card summary-card weekly-card weekly-current" : "card weekly-card"}
|
||||
aria-labelledby={titleId}
|
||||
aria-busy={!content && !gaveUp && analysis?.status !== "failed"}
|
||||
>
|
||||
<span className="eyebrow">
|
||||
{weekRange(start, end)}
|
||||
{current && " · ez a hét"}
|
||||
</span>
|
||||
{content ? (
|
||||
<>
|
||||
{isAdmin && analysis && onRestarted && (
|
||||
<RegenerateButton<Analysis> url={`/admin/analyses/${analysis.id}/regenerate`} onStarted={onRestarted} />
|
||||
)}
|
||||
<h2 id={titleId} className="summary-title">
|
||||
{content.title}
|
||||
</h2>
|
||||
<div className="summary-text weekly-text" lang={analysis?.language}>
|
||||
<Paragraphs text={content.text ?? ""} />
|
||||
</div>
|
||||
{analysis && <RateContent analysisId={analysis.id} />}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2 id={titleId} className="sr-only">
|
||||
Heti horoszkóp, {weekRange(start, end)}
|
||||
</h2>
|
||||
{gaveUp || analysis?.status === "failed" ? (
|
||||
<p className="muted" role="status">
|
||||
{current
|
||||
? "A heti horoszkóp most nem készült el. Töltsd újra az oldalt egy kicsit később."
|
||||
: "Ez a heti horoszkóp nem készült el."}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<AnalysisLoading
|
||||
compact
|
||||
text="A heti horoszkópod készül, ez fél percig is eltarthat…"
|
||||
since={analysis?.requested_at ?? analysis?.created_at}
|
||||
/>
|
||||
{analysis && (
|
||||
<RetryNotice
|
||||
status={analysis.status}
|
||||
error={analysis.error}
|
||||
nextAttemptAt={analysis.next_attempt_at}
|
||||
isAdmin={isAdmin}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"week_start": "2026-11-30",
|
||||
"week_end": "2026-12-06",
|
||||
"title": "Gondolatok, amelyek összeérnek",
|
||||
"text": "A héten a gondolkodásod és a szíved egymásra hangolódnak. A legtisztább üzenetet a Merkúr hozza: a trigonja a születési Merkúrod felett hétfőn pontos, ez a világos fejtartás napja. A Nap a Nyilas jegyében a születési Vénuszodra szextilt vet, a Merkúr pedig a Szaturnuszoddal is harmonizál. A háttérben a Plútó lassan dolgozik a születési Marsod közelében: mély, kitartó átalakulás, nem hirtelen fordulat.\n\nHétfőn a Mars szextilje a születési Jupiteroddal is kedvező, a Mars az 1. házban jár, így a kezdeményezőkedved most erős. Kedden csúcsnap jön: a Nap szextilje a Vénuszoddal és a Merkúr szextilje a Szaturnusszal a hét legtisztább harmóniája, miközben az utolsó negyedben álló Hold a Szűz jegyében, az 1. házban a dolgok lecsupaszítására hív. Szerdán a Merkúr trigonja a Napoddal megerősíti, hogy a szavaid mögött valódi meggyőződés áll. Pénteken a Vénusz Skorpióba lép a 3. házban, szombaton a Hold is követi, így a hét vége befelé forduló, mélyebb hangulatú. Vasárnap a Vénusz trigonja a Jupiterrel bőséges, nagylelkű zárást ad.\n\nJavaslat: kedden írd le azt a kérést vagy elhatározást, amit eddig halogattál, mert a Merkúr és a Szaturnusz összhangja most kitartást ad a szavaidnak. A hét végén engedj teret a csendnek a Hold skorpiós hullámzásában, és vasárnap, a Vénusz–Jupiter trigon jegyében, merj örülni annak, ami már a tiéd."
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Where this visit began, for the admin statistics of a new member: the
|
||||
* referring site's address (without its path), the link's campaign tags and
|
||||
* click id, and the app the visitor came out of (the login page's way out of
|
||||
* Facebook's browser adds `?forras=`). Read once, when the site first loads
|
||||
* in the tab, and kept in the page's memory only: nothing is stored in the
|
||||
* browser, and it is only sent with a sign-up on the same visit.
|
||||
*/
|
||||
export interface CameFrom {
|
||||
referrer: string | null;
|
||||
utm_source: string | null;
|
||||
utm_medium: string | null;
|
||||
utm_campaign: string | null;
|
||||
click: string | null;
|
||||
app: string | null;
|
||||
}
|
||||
|
||||
let arrival: CameFrom | null = null;
|
||||
|
||||
/** Called as the site first loads (components/Arrival.tsx). */
|
||||
export function rememberArrival(): void {
|
||||
if (arrival || typeof window === "undefined") return;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const tag = (name: string) => params.get(name)?.trim().slice(0, 60) || null;
|
||||
let referrer: string | null = null;
|
||||
try {
|
||||
referrer = document.referrer ? new URL(document.referrer).hostname || null : null;
|
||||
} catch {
|
||||
referrer = null;
|
||||
}
|
||||
arrival = {
|
||||
referrer,
|
||||
utm_source: tag("utm_source"),
|
||||
utm_medium: tag("utm_medium"),
|
||||
utm_campaign: tag("utm_campaign"),
|
||||
click: ["fbclid", "gclid", "ttclid"].find((id) => params.has(id)) ?? null,
|
||||
app: tag("forras"),
|
||||
};
|
||||
}
|
||||
|
||||
/** What to send with a sign-up (null when the site did not record it). */
|
||||
export function cameFrom(): CameFrom | null {
|
||||
return arrival;
|
||||
}
|
||||
@@ -29,6 +29,7 @@ export const TAG_LABELS: Record<string, string> = {
|
||||
|
||||
export const KIND_LABELS: Record<string, string> = {
|
||||
summary: "Rövid összefoglaló",
|
||||
weekly: "Heti horoszkóp",
|
||||
natal: "Képletelemzés",
|
||||
synastry: "Kapcsolati elemzés",
|
||||
forecast: "Éves előrejelzés",
|
||||
|
||||
@@ -280,6 +280,9 @@ export const INTENTS = {
|
||||
} as const;
|
||||
|
||||
/** `/forum/szal/123-nem-tudom-elengedni`: the number decides, the words are for reading. */
|
||||
/** The forum's link preview image (Facebook and co.); a thread adds its own title and text. */
|
||||
export const FORUM_PREVIEW = { url: "/kep/forum.png?v=1", width: 1200, height: 630, alt: "A Sorsfonalak fóruma" };
|
||||
|
||||
export function threadHref(t: { id: number; slug: string }, postId?: number): string {
|
||||
const path = t.slug ? `/forum/szal/${t.id}-${t.slug}` : `/forum/szal/${t.id}`;
|
||||
return postId ? `${path}#h${postId}` : path;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* The browsers built into apps: Facebook, Messenger, Instagram, TikTok, and
|
||||
* other Android apps that show pages in their own window (WebView). Google
|
||||
* does not allow signing in with a Google account in them (its error page
|
||||
* says "disallowed_useragent"), so the login page offers the e-mail login
|
||||
* and a way out to the phone's own browser instead.
|
||||
*/
|
||||
export interface InAppBrowser {
|
||||
/** The app's name for the text ("Facebook"); null for an unknown app. */
|
||||
app: string | null;
|
||||
android: boolean;
|
||||
}
|
||||
|
||||
export function inAppBrowser(userAgent: string): InAppBrowser | null {
|
||||
const android = /Android/i.test(userAgent);
|
||||
let app: string | null = null;
|
||||
if (/Instagram/i.test(userAgent)) app = "Instagram";
|
||||
else if (/MessengerForiOS|Orca-Android|FB_IAB\/MESSENGER/i.test(userAgent)) app = "Messenger";
|
||||
else if (/FBAN|FBAV|FB_IAB|FBIOS|FB4A/.test(userAgent)) app = "Facebook";
|
||||
else if (/TikTok|musical_ly|Bytedance/i.test(userAgent)) app = "TikTok";
|
||||
if (app) return { app, android };
|
||||
// Any other Android app's window: "; wv)" in the browser's name.
|
||||
if (android && /; wv\)/.test(userAgent)) return { app: null, android };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A link that opens the page in Chrome on Android, out of the app's window.
|
||||
* Without Chrome the phone falls back to the same page.
|
||||
*/
|
||||
export function chromeIntent(url: string): string {
|
||||
const u = new URL(url);
|
||||
const fallback = encodeURIComponent(url);
|
||||
return `intent://${u.host}${u.pathname}${u.search}#Intent;scheme=${u.protocol.replace(":", "")};package=com.android.chrome;S.browser_fallback_url=${fallback};end`;
|
||||
}
|
||||
@@ -18,8 +18,8 @@ export const ARBITRATION_BOARD = {
|
||||
web: "https://panaszrendezes.hu",
|
||||
};
|
||||
|
||||
export const PRIVACY_UPDATED = "2026. november 26.";
|
||||
export const PRIVACY_UPDATED_EN = "26 November 2026";
|
||||
export const PRIVACY_UPDATED = "2026. november 27.";
|
||||
export const PRIVACY_UPDATED_EN = "27 November 2026";
|
||||
|
||||
/** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */
|
||||
export const TERMS_UPDATED = "2026. november 26.";
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface Me {
|
||||
nps_due: boolean;
|
||||
/** Natal analyses earned by bringing new users through shared links. */
|
||||
referral_rewards: { earned: number; limit: number };
|
||||
/** Monday's e-mail about the weekly horoscope is on. */
|
||||
weekly_email: boolean;
|
||||
}
|
||||
|
||||
/** A package from the catalog (`GET /v1/packages`). */
|
||||
@@ -258,7 +260,7 @@ export interface SynastryListItem {
|
||||
|
||||
export interface Analysis {
|
||||
id: string;
|
||||
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity";
|
||||
kind: "natal" | "synastry" | "summary" | "forecast" | "celebrity" | "weekly";
|
||||
status: "pending" | "running" | "done" | "failed";
|
||||
model: string;
|
||||
language: string;
|
||||
@@ -272,6 +274,8 @@ export interface Analysis {
|
||||
next_attempt_at?: string;
|
||||
/** When the current text was asked for: the waiting page counts from here. */
|
||||
requested_at?: string;
|
||||
/** The Monday of a weekly horoscope. */
|
||||
week_start?: string | null;
|
||||
}
|
||||
|
||||
/** Admin: one failed attempt in the error log. */
|
||||
@@ -325,7 +329,7 @@ export interface ModelFunction {
|
||||
export interface AdminJob {
|
||||
id: string;
|
||||
type: "analysis" | "question";
|
||||
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity";
|
||||
kind: "summary" | "natal" | "synastry" | "forecast" | "question" | "celebrity" | "weekly";
|
||||
status: "pending" | "running";
|
||||
/** The model of the current attempt. */
|
||||
model: string;
|
||||
@@ -467,6 +471,8 @@ export interface AdminCelebrityRow {
|
||||
export interface AnalysisContent {
|
||||
title?: string;
|
||||
summary?: string;
|
||||
/** The weekly horoscope's paragraphs. */
|
||||
text?: string;
|
||||
sections?: Record<string, { title: string; body: string }>;
|
||||
strengths?: string[];
|
||||
challenges?: string[];
|
||||
@@ -881,3 +887,78 @@ export interface FeedbackSummary {
|
||||
comments: { score: number; comment: string; created_at: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
/** The headline numbers of a period on Admin → Statisztika. */
|
||||
export interface StatsPeriod {
|
||||
signups: number;
|
||||
own_charts: number;
|
||||
analyses: number;
|
||||
questions: number;
|
||||
orders: number;
|
||||
buyers: number;
|
||||
revenue_huf: number;
|
||||
refunded_huf: number;
|
||||
weekly_readers: number;
|
||||
forum_posts: number;
|
||||
ai_cost_usd: number;
|
||||
}
|
||||
|
||||
export interface StatsDay {
|
||||
date: string;
|
||||
signups: number;
|
||||
own_charts: number;
|
||||
analyses: number;
|
||||
questions: number;
|
||||
orders: number;
|
||||
revenue_huf: number;
|
||||
weekly_readers: number;
|
||||
forum_posts: number;
|
||||
}
|
||||
|
||||
/** Admin → Statisztika (`GET /v1/admin/stats?days=`). */
|
||||
export interface AdminStats {
|
||||
days: number;
|
||||
from: string;
|
||||
to: string;
|
||||
totals: {
|
||||
members: number;
|
||||
own_charts: number;
|
||||
buyers: number;
|
||||
revenue_huf: number;
|
||||
weekly_subscribers: number;
|
||||
forum_members: number;
|
||||
};
|
||||
period: StatsPeriod;
|
||||
/** The same length of time before the period (null for "since the start"). */
|
||||
previous: StatsPeriod | null;
|
||||
daily: StatsDay[];
|
||||
/** The members who signed up in the period. */
|
||||
cohort: {
|
||||
funnel: {
|
||||
signups: number;
|
||||
verified: number;
|
||||
own_chart: number;
|
||||
ordered: number;
|
||||
checkout: number;
|
||||
bought: number;
|
||||
weekly: number;
|
||||
};
|
||||
sources: { source: string; signups: number; own_chart: number; bought: number }[];
|
||||
details: { detail: string; signups: number }[];
|
||||
devices: { device: string; signups: number }[];
|
||||
methods: { method: string; signups: number }[];
|
||||
};
|
||||
packages: { package: string; name: string | null; gift: boolean; orders: number; revenue_huf: number }[];
|
||||
content: { kind: string; done: number; failed: number; cost_usd: number }[];
|
||||
weekly: { week_start: string; readers: number; emails: number }[];
|
||||
}
|
||||
|
||||
/** An MCP client an admin connected to the admin tools (docs/mcp.md). */
|
||||
export interface OauthGrant {
|
||||
id: string;
|
||||
client_name: string;
|
||||
redirect_host: string | null;
|
||||
user_email: string;
|
||||
created_at: string;
|
||||
last_used_at: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/** Dates of the weekly horoscope (shared by the server and the browser). */
|
||||
|
||||
export const MONTHS = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
|
||||
/** "november 30. – december 6." or "december 7–13.". */
|
||||
export function weekRange(start: string, end: string): string {
|
||||
const [, m1, d1] = start.split("-").map(Number);
|
||||
const [, m2, d2] = end.split("-").map(Number);
|
||||
return m1 === m2 ? `${MONTHS[m1 - 1]} ${d1}–${d2}.` : `${MONTHS[m1 - 1]} ${d1}. – ${MONTHS[m2 - 1]} ${d2}.`;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ mod sky;
|
||||
mod synastry;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod week;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -17,6 +17,7 @@ use crate::forecast::{self, ForecastRequest, ForecastResponse};
|
||||
use crate::natal::{self, NatalRequest, NatalResponse};
|
||||
use crate::sky::{self, EventsQuery, EventsResponse, SkyQuery, SkyResponse};
|
||||
use crate::synastry::{self, SynastryRequest, SynastryResponse};
|
||||
use crate::week::{self, WeekRequest, WeekResponse};
|
||||
|
||||
type AppResult<T> = Result<Json<T>, ApiError>;
|
||||
|
||||
@@ -30,6 +31,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/natal", post(natal_chart))
|
||||
.route("/v1/synastry", post(synastry_chart))
|
||||
.route("/v1/forecast", post(forecast_year))
|
||||
.route("/v1/week", post(week_of_chart))
|
||||
.route("/v1/sky", get(sky_now))
|
||||
.route("/v1/sky/events", get(sky_events))
|
||||
.layer(cors())
|
||||
@@ -167,6 +169,17 @@ async fn forecast_year(
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
async fn week_of_chart(
|
||||
State(state): State<Arc<AppState>>,
|
||||
body: Result<Json<WeekRequest>, JsonRejection>,
|
||||
) -> AppResult<WeekResponse> {
|
||||
let Json(request) = body?;
|
||||
let response = tokio::task::spawn_blocking(move || week::calculate(&state, request))
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(e.to_string()))??;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
async fn sky_now(
|
||||
State(state): State<Arc<AppState>>,
|
||||
query: Result<Query<SkyQuery>, QueryRejection>,
|
||||
|
||||
@@ -319,6 +319,38 @@ async fn forecast_year_with_solar_return() {
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn one_week_of_a_chart() {
|
||||
let birth = json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"});
|
||||
let (status, d) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-11-30"}))).await;
|
||||
assert_eq!(status, StatusCode::OK, "{d}");
|
||||
assert_eq!(d["timezone"], "Europe/Budapest");
|
||||
let w = &d["week"];
|
||||
assert_eq!((w["start"].as_str(), w["end"].as_str()), (Some("2026-11-30"), Some("2026-12-06")));
|
||||
assert_eq!(w["positions"].as_array().unwrap().len(), 9);
|
||||
assert!(w["positions"][0]["house"].as_u64().is_some());
|
||||
assert!(!w["moon_ingresses"].as_array().unwrap().is_empty());
|
||||
|
||||
// Unknown birth time: no houses.
|
||||
let (status, u) = call(
|
||||
"POST",
|
||||
"/v1/week",
|
||||
Some(json!({"birth": {"date": "1985-07-14", "country": "HU", "place": "Budapest"}, "start": "2026-11-30"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{u}");
|
||||
assert!(u["week"]["positions"][0]["house"].is_null());
|
||||
|
||||
// The week the clocks go back (Sunday 25 October): still Monday to Sunday.
|
||||
let (status, d) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-10-19"}))).await;
|
||||
assert_eq!(status, StatusCode::OK, "{d}");
|
||||
assert_eq!((d["week"]["start"].as_str(), d["week"]["end"].as_str()), (Some("2026-10-19"), Some("2026-10-25")));
|
||||
|
||||
// Not a Monday.
|
||||
let (status, _) = call("POST", "/v1/week", Some(json!({"birth": birth, "start": "2026-12-01"}))).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sky_at_a_moment() {
|
||||
// 2026-03-10 12:00 UTC: Mercury retrograde (26 Feb – 20 Mar), waning Moon.
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! `POST /v1/week`: one week of a natal chart, for the weekly horoscope: the
|
||||
//! planets' aspects to the natal points (with the day each is exact), where
|
||||
//! the planets stand, the Moon's sign changes, the lunar phases, and the
|
||||
//! planets' stations and sign changes. The week runs from Monday 0:00 to the
|
||||
//! next Monday on the clock of `tz` (default Europe/Budapest); the dates are
|
||||
//! local days there.
|
||||
|
||||
use astro_engine::{Week, calculate_week};
|
||||
use jiff::civil::Date;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::AppState;
|
||||
use crate::error::ApiError;
|
||||
use crate::natal::{self, NatalRequest};
|
||||
use crate::sky::DEFAULT_TZ;
|
||||
|
||||
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WeekRequest {
|
||||
/// Birth data as for `POST /v1/natal`.
|
||||
pub birth: NatalRequest,
|
||||
/// The Monday the week starts on, `YYYY-MM-DD`.
|
||||
pub start: String,
|
||||
#[serde(default)]
|
||||
pub tz: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct WeekResponse {
|
||||
pub timezone: String,
|
||||
pub week: Week,
|
||||
}
|
||||
|
||||
fn bad(msg: impl Into<String>) -> ApiError {
|
||||
ApiError::BadRequest(msg.into())
|
||||
}
|
||||
|
||||
pub fn calculate(state: &AppState, req: WeekRequest) -> Result<WeekResponse, ApiError> {
|
||||
let start: Date = req.start.parse().map_err(|_| bad("start must be a date (YYYY-MM-DD)"))?;
|
||||
if start.weekday() != jiff::civil::Weekday::Monday {
|
||||
return Err(bad("start must be a Monday"));
|
||||
}
|
||||
if !(1900..=2100).contains(&start.year()) {
|
||||
return Err(bad("start must be between 1900 and 2100"));
|
||||
}
|
||||
let zone_name = req.tz.unwrap_or_else(|| DEFAULT_TZ.to_string());
|
||||
let tz = state.atlas.zones.get(&zone_name)?;
|
||||
let natal = natal::calculate(state, req.birth).map_err(|e| e.for_person("birth"))?;
|
||||
|
||||
let jd_at = |date: Date| -> Result<(f64, f64), ApiError> {
|
||||
let zoned = date.to_zoned(tz.clone()).map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
let jd = zoned.timestamp().as_second() as f64 / 86_400.0 + UNIX_EPOCH_JD;
|
||||
Ok((jd, f64::from(zoned.offset().seconds()) / 3600.0))
|
||||
};
|
||||
let (start_jd, offset) = jd_at(start)?;
|
||||
let next = start.checked_add(jiff::Span::new().days(7)).map_err(|e| ApiError::Internal(e.to_string()))?;
|
||||
let (end_jd, _) = jd_at(next)?;
|
||||
let mut week = calculate_week(state.engine.as_ref(), &natal.chart, start_jd, end_jd, offset)
|
||||
.map_err(|e| ApiError::Calculation(e.to_string()))?;
|
||||
// The last day from the calendar: the offset at the start would be an hour
|
||||
// off in the week the clocks go back.
|
||||
week.end = start.checked_add(jiff::Span::new().days(6)).map_err(|e| ApiError::Internal(e.to_string()))?.to_string();
|
||||
Ok(WeekResponse { timezone: zone_name, week })
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "mcp"
|
||||
description = "Sorsfonalak MCP server: the admin tools for Claude, called with the admin's OAuth token"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
axum.workspace = true
|
||||
reqwest.workspace = true
|
||||
rmcp = { version = "3.12", default-features = false, features = ["server", "macros", "transport-streamable-http-server"] }
|
||||
schemars = "1"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
tokio = { workspace = true, features = ["time"] }
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
http-body-util = "0.1"
|
||||
@@ -0,0 +1,33 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Build from the repository root:
|
||||
# docker build -f services/mcp/Dockerfile -t sorsfonalak/mcp .
|
||||
|
||||
ARG RUST_VERSION=1.99
|
||||
|
||||
# --- 1. static (musl) build ----------------------------------------------------
|
||||
FROM rust:${RUST_VERSION}-alpine AS build
|
||||
RUN apk add --no-cache musl-dev
|
||||
WORKDIR /app
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates crates
|
||||
COPY services services
|
||||
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,target=/app/target,sharing=locked \
|
||||
cargo build --release --locked -p mcp \
|
||||
&& cp target/release/mcp /mcp
|
||||
# The log directory (LOG_DIR); a volume mounted here takes over its owner.
|
||||
RUN mkdir /logs
|
||||
|
||||
# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) ---
|
||||
FROM scratch
|
||||
COPY --from=build /mcp /mcp
|
||||
COPY --from=build --chown=65532:65532 /logs /logs
|
||||
ENV BIND_ADDR=0.0.0.0:8084 \
|
||||
LOG_FORMAT=json \
|
||||
RUST_LOG=info,rmcp=warn
|
||||
USER 65532:65532
|
||||
EXPOSE 8084
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
|
||||
CMD ["/mcp", "healthcheck"]
|
||||
ENTRYPOINT ["/mcp"]
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Calls of the site's API with the caller's token.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use reqwest::Method;
|
||||
use serde_json::Value;
|
||||
|
||||
pub struct Api {
|
||||
http: reqwest::Client,
|
||||
base: String,
|
||||
}
|
||||
|
||||
/// A refused or failed call: the status and the API's message.
|
||||
#[derive(Debug)]
|
||||
pub struct Failure {
|
||||
pub status: Option<StatusCode>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl Api {
|
||||
pub fn new(base: &str) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(60))
|
||||
.user_agent("sorsfonalak-mcp")
|
||||
.build()
|
||||
.expect("HTTP client");
|
||||
Self { http, base: base.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
/// `/oauth/whoami`: `Ok(Some)` for a valid token, `Ok(None)` for an
|
||||
/// unknown one, `Err(status)` otherwise.
|
||||
pub async fn whoami(&self, token: &str) -> Result<Option<Value>, StatusCode> {
|
||||
let response =
|
||||
self.http.get(format!("{}/oauth/whoami", self.base)).bearer_auth(token).send().await.map_err(|e| {
|
||||
tracing::warn!(error = %e, "whoami");
|
||||
StatusCode::BAD_GATEWAY
|
||||
})?;
|
||||
let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
|
||||
match status {
|
||||
StatusCode::OK => Ok(Some(response.json().await.map_err(|_| StatusCode::BAD_GATEWAY)?)),
|
||||
StatusCode::UNAUTHORIZED => Ok(None),
|
||||
other => Err(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// One call; the answer's JSON (`null` for an empty one).
|
||||
pub async fn call(
|
||||
&self,
|
||||
token: &str,
|
||||
method: Method,
|
||||
path: &str,
|
||||
query: &[(&str, String)],
|
||||
body: Option<&Value>,
|
||||
) -> Result<Value, Failure> {
|
||||
let mut request = self.http.request(method, format!("{}{path}", self.base)).bearer_auth(token).query(query);
|
||||
if let Some(body) = body {
|
||||
request = request.json(body);
|
||||
}
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Failure { status: None, message: format!("A szerver nem érhető el: {e}") })?;
|
||||
let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
|
||||
let bytes = response.bytes().await.map_err(|e| Failure { status: Some(status), message: e.to_string() })?;
|
||||
let value: Value =
|
||||
if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap_or(Value::Null) };
|
||||
if status.is_success() {
|
||||
return Ok(value);
|
||||
}
|
||||
let message = value["error"]["message"]
|
||||
.as_str()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| format!("A kérés nem sikerült ({status})."));
|
||||
Err(Failure { status: Some(status), message })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! The token check in front of `/mcp`. The backend knows the tokens: it is
|
||||
//! asked once a minute per token (`/oauth/whoami`); the tools send the token
|
||||
//! on with every call, and the backend checks it again there, so a revoked
|
||||
//! connection stops at once whatever this cache says.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE};
|
||||
use axum::http::{HeaderValue, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::App;
|
||||
|
||||
const CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
const CACHE_MAX: usize = 1000;
|
||||
|
||||
/// The caller's token, for the tools (in the HTTP request's extensions).
|
||||
#[derive(Clone)]
|
||||
pub struct Bearer(pub String);
|
||||
|
||||
/// What the backend said about a token.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Valid,
|
||||
/// Unknown, expired, revoked, or for another server.
|
||||
Invalid,
|
||||
/// Valid, but its owner is no admin any more.
|
||||
Forbidden,
|
||||
/// The backend did not answer.
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// Tokens found valid in the last minute (by their hash).
|
||||
#[derive(Default)]
|
||||
pub struct TokenCache(Mutex<HashMap<[u8; 32], Instant>>);
|
||||
|
||||
impl TokenCache {
|
||||
fn fresh(&self, key: &[u8; 32]) -> bool {
|
||||
self.0.lock().expect("token cache").get(key).is_some_and(|at| at.elapsed() < CACHE_TTL)
|
||||
}
|
||||
|
||||
fn remember(&self, key: [u8; 32]) {
|
||||
let mut map = self.0.lock().expect("token cache");
|
||||
if map.len() >= CACHE_MAX {
|
||||
map.retain(|_, at| at.elapsed() < CACHE_TTL);
|
||||
}
|
||||
map.insert(key, Instant::now());
|
||||
}
|
||||
|
||||
/// The backend refused the token in a tool call: the next request asks again
|
||||
/// (and gets 401, so the client logs in again or refreshes).
|
||||
pub fn forget(&self, token: &str) {
|
||||
let key: [u8; 32] = Sha256::digest(token.as_bytes()).into();
|
||||
self.0.lock().expect("token cache").remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the backend (or the cache) about a token.
|
||||
pub async fn check(app: &App, token: &str) -> Verdict {
|
||||
let key: [u8; 32] = Sha256::digest(token.as_bytes()).into();
|
||||
if app.tokens.fresh(&key) {
|
||||
return Verdict::Valid;
|
||||
}
|
||||
let verdict = match app.api.whoami(token).await {
|
||||
Ok(Some(who)) => {
|
||||
let resource = who["resource"].as_str();
|
||||
let ours = |r: &str| r.trim_end_matches('/') == app.config.mcp_public_url.trim_end_matches('/');
|
||||
if resource.is_none_or(ours) { Verdict::Valid } else { Verdict::Invalid }
|
||||
}
|
||||
Ok(None) => Verdict::Invalid,
|
||||
Err(status) if status == StatusCode::FORBIDDEN => Verdict::Forbidden,
|
||||
Err(status) if status == StatusCode::UNAUTHORIZED => Verdict::Invalid,
|
||||
Err(_) => Verdict::Unavailable,
|
||||
};
|
||||
if verdict == Verdict::Valid {
|
||||
app.tokens.remember(key);
|
||||
}
|
||||
verdict
|
||||
}
|
||||
|
||||
/// 401 (or 403) with where to find the OAuth metadata, as MCP clients expect.
|
||||
fn refuse(app: &App, status: StatusCode, error: Option<&str>) -> Response {
|
||||
let mut value = String::from("Bearer");
|
||||
if let Some(error) = error {
|
||||
value.push_str(&format!(" error=\"{error}\","));
|
||||
}
|
||||
value.push_str(&format!(" scope=\"admin\", resource_metadata=\"{}\"", app.config.resource_metadata_url()));
|
||||
let mut response =
|
||||
(status, axum::Json(serde_json::json!({ "error": error.unwrap_or("unauthorized") }))).into_response();
|
||||
if let Ok(header) = HeaderValue::from_str(&value) {
|
||||
response.headers_mut().insert(WWW_AUTHENTICATE, header);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// Middleware: only requests with a valid token reach the MCP service.
|
||||
pub async fn require_token(State(app): State<Arc<App>>, mut request: Request, next: Next) -> Response {
|
||||
let token = request
|
||||
.headers()
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(|t| t.trim().to_string())
|
||||
.filter(|t| !t.is_empty());
|
||||
let Some(token) = token else { return refuse(&app, StatusCode::UNAUTHORIZED, None) };
|
||||
match check(&app, &token).await {
|
||||
Verdict::Valid => {
|
||||
request.extensions_mut().insert(Bearer(token));
|
||||
next.run(request).await
|
||||
}
|
||||
Verdict::Invalid => refuse(&app, StatusCode::UNAUTHORIZED, Some("invalid_token")),
|
||||
Verdict::Forbidden => refuse(&app, StatusCode::FORBIDDEN, Some("insufficient_scope")),
|
||||
Verdict::Unavailable => {
|
||||
(StatusCode::SERVICE_UNAVAILABLE, axum::Json(serde_json::json!({ "error": "backend_unavailable" })))
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Sorsfonalak MCP server (docs/mcp.md): the admin tools for Claude.
|
||||
//!
|
||||
//! Claude connects to `/mcp` (Streamable HTTP, stateless). Without a valid
|
||||
//! token it gets 401 with the address of this server's OAuth metadata, which
|
||||
//! names the site as the authorization server: an admin approves the
|
||||
//! connection there, and the backend issues the tokens. Every tool calls the
|
||||
//! site's API (through the frontend's `/api/v1` proxy, like the admin pages)
|
||||
//! with the caller's token, so the backend decides what is allowed, and the
|
||||
//! answers go back with the members' e-mail addresses and names masked.
|
||||
//!
|
||||
//! Configuration: `API_URL` (default `http://localhost:3001/api/v1`),
|
||||
//! `PUBLIC_BASE_URL` (the site, the authorization server; default
|
||||
//! `http://localhost:3001`), `MCP_PUBLIC_URL` (this server's address as
|
||||
//! Claude sees it; default `http://localhost:8084/mcp`), `BIND_ADDR` (default
|
||||
//! `0.0.0.0:8084`), `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`.
|
||||
//!
|
||||
//! `mcp healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod api;
|
||||
mod auth;
|
||||
mod mask;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod tools;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router, middleware};
|
||||
use rmcp::transport::streamable_http_server::session::never::NeverSessionManager;
|
||||
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
|
||||
use serde_json::{Value, json};
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8084";
|
||||
|
||||
pub struct Config {
|
||||
/// The site's API (`…/api/v1`).
|
||||
pub api_url: String,
|
||||
/// The site: the OAuth authorization server.
|
||||
pub public_base_url: String,
|
||||
/// This server's `/mcp` address as clients see it (the tokens' audience).
|
||||
pub mcp_public_url: String,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
fn from_env() -> Self {
|
||||
let var = |name: &str, default: &str| {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.map(|v| v.trim().trim_end_matches('/').to_string())
|
||||
.filter(|v| !v.is_empty())
|
||||
.unwrap_or_else(|| default.to_string())
|
||||
};
|
||||
Self {
|
||||
api_url: var("API_URL", "http://localhost:3001/api/v1"),
|
||||
public_base_url: var("PUBLIC_BASE_URL", "http://localhost:3001"),
|
||||
mcp_public_url: var("MCP_PUBLIC_URL", "http://localhost:8084/mcp"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `scheme://host[:port]` of the MCP address.
|
||||
fn origin(&self) -> &str {
|
||||
let after_scheme = self.mcp_public_url.find("://").map_or(0, |i| i + 3);
|
||||
let end = self.mcp_public_url[after_scheme..].find('/').map_or(self.mcp_public_url.len(), |i| after_scheme + i);
|
||||
&self.mcp_public_url[..end]
|
||||
}
|
||||
|
||||
/// The host name of the MCP address (accepted as the `Host` header).
|
||||
fn host(&self) -> String {
|
||||
let origin = self.origin();
|
||||
let host = origin.split("://").nth(1).unwrap_or(origin);
|
||||
host.split(':').next().unwrap_or(host).to_string()
|
||||
}
|
||||
|
||||
/// Where the protected resource's metadata is (in the 401 answers).
|
||||
pub fn resource_metadata_url(&self) -> String {
|
||||
format!("{}/.well-known/oauth-protected-resource/mcp", self.origin())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
pub config: Config,
|
||||
pub api: api::Api,
|
||||
pub tokens: auth::TokenCache,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(config: Config) -> Self {
|
||||
Self { api: api::Api::new(&config.api_url), config, tokens: auth::TokenCache::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The protected resource's metadata (RFC 9728).
|
||||
async fn resource_metadata(axum::extract::State(app): axum::extract::State<Arc<App>>) -> Json<Value> {
|
||||
Json(json!({
|
||||
"resource": app.config.mcp_public_url,
|
||||
"authorization_servers": [app.config.public_base_url],
|
||||
"scopes_supported": ["admin"],
|
||||
"bearer_methods_supported": ["header"],
|
||||
"resource_name": "Sorsfonalak admin",
|
||||
"resource_documentation": format!("{}/admin", app.config.public_base_url),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn health() -> Json<Value> {
|
||||
Json(json!({ "status": "ok" }))
|
||||
}
|
||||
|
||||
pub fn router(app: Arc<App>) -> Router {
|
||||
let mut hosts = vec![app.config.host(), "localhost".to_string(), "127.0.0.1".to_string(), "mcp".to_string()];
|
||||
hosts.dedup();
|
||||
let config = StreamableHttpServerConfig::default()
|
||||
.with_legacy_session_mode(false)
|
||||
.with_json_response(true)
|
||||
.with_allowed_hosts(hosts);
|
||||
let tools_app = app.clone();
|
||||
let mcp = StreamableHttpService::new(
|
||||
move || Ok(tools::Tools::new(tools_app.clone())),
|
||||
Arc::new(NeverSessionManager::default()),
|
||||
config,
|
||||
);
|
||||
let protected =
|
||||
Router::new().nest_service("/mcp", mcp).layer(middleware::from_fn_with_state(app.clone(), auth::require_token));
|
||||
Router::new()
|
||||
.route("/healthz", get(health))
|
||||
.route("/.well-known/oauth-protected-resource", get(resource_metadata))
|
||||
.route("/.well-known/oauth-protected-resource/mcp", get(resource_metadata))
|
||||
.with_state(app)
|
||||
.merge(protected)
|
||||
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
|
||||
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||
return service_kit::healthcheck(addr);
|
||||
}
|
||||
let _log = service_kit::init_logging("mcp");
|
||||
let config = Config::from_env();
|
||||
tracing::info!(api = %config.api_url, resource = %config.mcp_public_url, "starting");
|
||||
let app = router(Arc::new(App::new(config)));
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "listening");
|
||||
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The members' personal data stays on the site: e-mail addresses go to
|
||||
//! Claude as `an***@gmail.com` (in free text too), and people's names as
|
||||
//! `[rejtve]`. Forum nicknames are pseudonyms and stay; so do the names of
|
||||
//! famous people and packages (a `name` is a person's only beside an `email`).
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// Keys whose text is always a person's name.
|
||||
const NAME_KEYS: [&str; 7] =
|
||||
["display_name", "from_name", "inviter_name", "recipient_name", "invited_by", "accepted_by", "buyer_name"];
|
||||
const HIDDEN: &str = "[rejtve]";
|
||||
|
||||
pub fn mask(value: &mut Value) {
|
||||
match value {
|
||||
Value::String(s) => {
|
||||
if s.contains('@') {
|
||||
*s = mask_emails(s);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(mask),
|
||||
Value::Object(map) => mask_object(map),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn mask_object(map: &mut Map<String, Value>) {
|
||||
let has_email = map.get("email").is_some_and(Value::is_string);
|
||||
for (key, child) in map.iter_mut() {
|
||||
let a_name = NAME_KEYS.contains(&key.as_str()) || (has_email && key == "name");
|
||||
if a_name && child.is_string() {
|
||||
*child = Value::String(HIDDEN.into());
|
||||
} else {
|
||||
mask(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn local_char(c: char) -> bool {
|
||||
c.is_alphanumeric() || "._%+-".contains(c)
|
||||
}
|
||||
|
||||
fn domain_char(c: char) -> bool {
|
||||
c.is_alphanumeric() || ".-".contains(c)
|
||||
}
|
||||
|
||||
/// Every e-mail address in the text: the first two characters of the name
|
||||
/// part, then `***`, and the domain.
|
||||
pub fn mask_emails(text: &str) -> String {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i] != '@' {
|
||||
out.push(chars[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// The name part is already in `out`: find where it starts.
|
||||
let mut start = i;
|
||||
while start > 0 && local_char(chars[start - 1]) {
|
||||
start -= 1;
|
||||
}
|
||||
let mut end = i + 1;
|
||||
while end < chars.len() && domain_char(chars[end]) {
|
||||
end += 1;
|
||||
}
|
||||
let domain: String = chars[i + 1..end].iter().collect::<String>().trim_end_matches('.').to_string();
|
||||
let local_len = i - start;
|
||||
if local_len == 0 || !domain.contains('.') {
|
||||
out.push('@');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let kept: String = chars[start..start + local_len.min(2)].iter().collect();
|
||||
for _ in 0..local_len {
|
||||
out.pop();
|
||||
}
|
||||
out.push_str(&kept);
|
||||
out.push_str("***@");
|
||||
out.push_str(&domain);
|
||||
i += 1 + domain.chars().count();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn addresses_in_text() {
|
||||
assert_eq!(mask_emails("anna.kovacs@gmail.com"), "an***@gmail.com");
|
||||
assert_eq!(mask_emails("Írj: b@freemail.hu, köszi."), "Írj: b***@freemail.hu, köszi.");
|
||||
assert_eq!(mask_emails("x@y nem cím, @ sem"), "x@y nem cím, @ sem");
|
||||
assert_eq!(mask_emails("a@b.hu és cc@dd.com."), "a***@b.hu és cc***@dd.com.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn people_but_not_packages_or_famous_names() {
|
||||
let mut v = json!({
|
||||
"users": [{"id": "1", "email": "anna@example.com", "display_name": "Kovács Anna", "roles": ["user"]}],
|
||||
"redeemed_by": {"email": "bea@example.com", "name": "Bea"},
|
||||
"package": {"id": "couple", "name": "Páros"},
|
||||
"celebrity": {"name": "Liszt Ferenc"},
|
||||
"message": "Hívj: anna@example.com",
|
||||
"recipient_name": "Cili",
|
||||
"count": 3,
|
||||
});
|
||||
mask(&mut v);
|
||||
assert_eq!(v["users"][0]["email"], "an***@example.com");
|
||||
assert_eq!(v["users"][0]["display_name"], "[rejtve]");
|
||||
assert_eq!(v["redeemed_by"], json!({"email": "be***@example.com", "name": "[rejtve]"}));
|
||||
assert_eq!(v["package"]["name"], "Páros");
|
||||
assert_eq!(v["celebrity"]["name"], "Liszt Ferenc");
|
||||
assert_eq!(v["message"], "Hívj: an***@example.com");
|
||||
assert_eq!(v["recipient_name"], "[rejtve]");
|
||||
assert_eq!(v["count"], 3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! The MCP server against a fake site API.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{HeaderMap, Request, StatusCode};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use crate::{App, Config, router};
|
||||
|
||||
const GOOD: &str = "good-token";
|
||||
const ELSEWHERE: &str = "token-for-another-server";
|
||||
const FORMER_ADMIN: &str = "former-admin-token";
|
||||
/// Valid at the check, revoked by the time of the tool call.
|
||||
const REVOKED: &str = "revoked-meanwhile";
|
||||
static REVOKED_CHECKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
/// What the fake API received: (path with query, the bearer token).
|
||||
type Calls = Arc<Mutex<Vec<(String, String)>>>;
|
||||
|
||||
fn bearer(headers: &HeaderMap) -> String {
|
||||
headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or("").trim_start_matches("Bearer ").to_string()
|
||||
}
|
||||
|
||||
async fn fake_whoami(headers: HeaderMap) -> (StatusCode, Json<Value>) {
|
||||
match bearer(&headers).as_str() {
|
||||
GOOD => (StatusCode::OK, Json(json!({"resource": "https://sorsfonalak.test/mcp", "scope": "admin"}))),
|
||||
ELSEWHERE => (StatusCode::OK, Json(json!({"resource": "https://other.test/mcp"}))),
|
||||
FORMER_ADMIN => (StatusCode::FORBIDDEN, Json(json!({"error": {"code": "forbidden"}}))),
|
||||
REVOKED => {
|
||||
REVOKED_CHECKS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
(StatusCode::OK, Json(json!({"resource": "https://sorsfonalak.test/mcp"})))
|
||||
}
|
||||
_ => (StatusCode::UNAUTHORIZED, Json(json!({"error": {"code": "unauthorized"}}))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fake_stats(
|
||||
State(calls): State<Calls>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<std::collections::HashMap<String, String>>,
|
||||
) -> Json<Value> {
|
||||
calls.lock().unwrap().push((format!("/admin/stats?days={}", q["days"]), bearer(&headers)));
|
||||
Json(json!({
|
||||
"totals": {"members": 3},
|
||||
"cohort": {"details": [{"detail": "utm_source=facebook", "signups": 2}]},
|
||||
"note": "Kérdezte: anna@example.com",
|
||||
"user": {"email": "bea@example.com", "name": "Bea"},
|
||||
}))
|
||||
}
|
||||
|
||||
async fn fake_users_patch() -> (StatusCode, Json<Value>) {
|
||||
(StatusCode::FORBIDDEN, Json(json!({"error": {"code": "forbidden", "message": "Ezt Claude-ból nem lehet."}})))
|
||||
}
|
||||
|
||||
async fn fake_ban(State(calls): State<Calls>, uri: axum::http::Uri, headers: HeaderMap) -> Json<Value> {
|
||||
calls.lock().unwrap().push((uri.path().to_string(), bearer(&headers)));
|
||||
Json(json!({"banned_until": "2026-11-28T10:00:00Z"}))
|
||||
}
|
||||
|
||||
/// The fake API on a free port; the MCP router pointed at it.
|
||||
async fn setup() -> (Router, Calls) {
|
||||
let calls: Calls = Arc::default();
|
||||
let api = Router::new()
|
||||
.route("/api/v1/oauth/whoami", get(fake_whoami))
|
||||
.route("/api/v1/admin/stats", get(fake_stats))
|
||||
.route("/api/v1/admin/promo-codes", post(fake_users_patch))
|
||||
.route(
|
||||
"/api/v1/admin/jobs",
|
||||
get(|| async { (StatusCode::UNAUTHORIZED, Json(json!({"error": {"code": "unauthorized"}}))) }),
|
||||
)
|
||||
.route("/api/v1/forum/members/{nickname}/ban", post(fake_ban))
|
||||
.with_state(calls.clone());
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, api).await.unwrap() });
|
||||
let config = Config {
|
||||
api_url: format!("http://{addr}/api/v1"),
|
||||
public_base_url: "https://sorsfonalak.test".into(),
|
||||
mcp_public_url: "https://sorsfonalak.test/mcp".into(),
|
||||
};
|
||||
(router(Arc::new(App::new(config))), calls)
|
||||
}
|
||||
|
||||
/// A JSON-RPC call to `/mcp`: the status, the `WWW-Authenticate` header, the body.
|
||||
async fn rpc(app: &Router, token: Option<&str>, body: Value) -> (StatusCode, Option<String>, Value) {
|
||||
let mut req = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/mcp")
|
||||
.header("host", "sorsfonalak.test")
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", "application/json, text/event-stream")
|
||||
.header("mcp-protocol-version", "2025-06-18");
|
||||
if let Some(t) = token {
|
||||
req = req.header("authorization", format!("Bearer {t}"));
|
||||
}
|
||||
let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
|
||||
let status = resp.status();
|
||||
let www = resp.headers().get("www-authenticate").map(|v| v.to_str().unwrap().to_string());
|
||||
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
// A JSON answer, or the data line of an event stream.
|
||||
let json = text
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("data:").map(str::trim).filter(|d| d.starts_with('{')))
|
||||
.unwrap_or(&text);
|
||||
(status, www, serde_json::from_str(json).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
fn call(id: i64, name: &str, arguments: Value) -> Value {
|
||||
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
|
||||
}
|
||||
|
||||
/// The text of a tool result.
|
||||
fn result_text(body: &Value) -> Value {
|
||||
serde_json::from_str(body["result"]["content"][0]["text"].as_str().unwrap()).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_a_token_claude_learns_where_to_log_in() {
|
||||
let (app, _) = setup().await;
|
||||
let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
|
||||
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}}});
|
||||
let (status, www, _) = rpc(&app, None, init.clone()).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
let expected = "resource_metadata=\"https://sorsfonalak.test/.well-known/oauth-protected-resource/mcp\"";
|
||||
assert!(www.as_deref().unwrap().contains(expected), "{www:?}");
|
||||
|
||||
// The metadata points at the site.
|
||||
let req = Request::builder().uri("/.well-known/oauth-protected-resource/mcp").body(Body::empty()).unwrap();
|
||||
let resp = app.clone().oneshot(req).await.unwrap();
|
||||
let meta: Value = serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||
assert_eq!(meta["resource"], "https://sorsfonalak.test/mcp");
|
||||
assert_eq!(meta["authorization_servers"], json!(["https://sorsfonalak.test"]));
|
||||
|
||||
// A wrong token, one for another server, one of a former admin.
|
||||
let (status, www, _) = rpc(&app, Some("nonsense"), init.clone()).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
assert!(www.unwrap().contains("error=\"invalid_token\""));
|
||||
assert_eq!(rpc(&app, Some(ELSEWHERE), init.clone()).await.0, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(rpc(&app, Some(FORMER_ADMIN), init.clone()).await.0, StatusCode::FORBIDDEN);
|
||||
|
||||
// A good one.
|
||||
let (status, _, body) = rpc(&app, Some(GOOD), init).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert_eq!(body["result"]["serverInfo"]["name"], "sorsfonalak");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tools_call_the_api_with_the_token_and_mask_people() {
|
||||
let (app, calls) = setup().await;
|
||||
let (_, _, body) = rpc(&app, Some(GOOD), json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})).await;
|
||||
let tools = body["result"]["tools"].as_array().unwrap_or_else(|| panic!("{body}"));
|
||||
let tool = |name: &str| tools.iter().find(|t| t["name"] == name).unwrap_or_else(|| panic!("no {name}"));
|
||||
assert_eq!(tool("get_stats")["annotations"]["readOnlyHint"], true);
|
||||
assert_eq!(tool("forum_ban")["annotations"]["destructiveHint"], true);
|
||||
assert_eq!(tool("create_promo_codes")["annotations"]["readOnlyHint"], false);
|
||||
assert!(tool("create_promo_codes")["inputSchema"]["required"].as_array().unwrap().contains(&json!("package")));
|
||||
assert_eq!(tools.len(), 34);
|
||||
|
||||
let (_, _, body) = rpc(&app, Some(GOOD), call(2, "get_stats", json!({"days": 7}))).await;
|
||||
assert_eq!(body["result"]["isError"], false, "{body}");
|
||||
let stats = result_text(&body);
|
||||
assert_eq!(stats["totals"]["members"], 3);
|
||||
assert_eq!(stats["note"], "Kérdezte: an***@example.com");
|
||||
assert_eq!(stats["user"], json!({"email": "be***@example.com", "name": "[rejtve]"}));
|
||||
assert_eq!(calls.lock().unwrap()[0], ("/admin/stats?days=7".to_string(), GOOD.to_string()));
|
||||
|
||||
// The API's refusal reaches Claude as a tool error.
|
||||
let (_, _, body) =
|
||||
rpc(&app, Some(GOOD), call(3, "create_promo_codes", json!({"package": "single", "count": 1}))).await;
|
||||
assert_eq!(body["result"]["isError"], true, "{body}");
|
||||
assert_eq!(body["result"]["content"][0]["text"], "Ezt Claude-ból nem lehet.");
|
||||
|
||||
// A nickname goes into the path encoded; a bad id never reaches the API.
|
||||
let (_, _, body) =
|
||||
rpc(&app, Some(GOOD), call(4, "forum_ban", json!({"nickname": "Hold fény", "reason": "hirdetés"}))).await;
|
||||
assert_eq!(body["result"]["isError"], false, "{body}");
|
||||
assert_eq!(calls.lock().unwrap()[1].0, "/api/v1/forum/members/Hold%20f%C3%A9ny/ban");
|
||||
let (_, _, body) = rpc(&app, Some(GOOD), call(5, "get_celebrity", json!({"id": "../users"}))).await;
|
||||
assert!(body["error"].is_object() || body["result"]["isError"] == true, "{body}");
|
||||
assert_eq!(calls.lock().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_token_the_backend_refuses_is_checked_again() {
|
||||
let (app, _) = setup().await;
|
||||
let (_, _, body) = rpc(&app, Some(REVOKED), call(1, "list_jobs", json!({}))).await;
|
||||
assert_eq!(body["result"]["isError"], true, "{body}");
|
||||
let checks = REVOKED_CHECKS.load(std::sync::atomic::Ordering::SeqCst);
|
||||
// Not from the cache: the backend is asked again.
|
||||
rpc(&app, Some(REVOKED), call(2, "list_jobs", json!({}))).await;
|
||||
assert_eq!(REVOKED_CHECKS.load(std::sync::atomic::Ordering::SeqCst), checks + 1);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user