mirror of
https://github.com/cita-777/metapi.git
synced 2026-11-21 21:56:52 +08:00
security: v1.3.1 — fix admin auth bypass, remove node:vm upstream execution, harden X-Forwarded-For handling (#634)
* fix(security): normalize admin auth path, drop node:vm challenge eval, trust XFF only from TRUSTED_PROXIES * docs: document TRUSTED_PROXIES in configuration reference * chore(release): bump version to 1.3.1 * fix(deps): upgrade fastify to 5.12.8 and @fastify/static to 10.1.10 Refs #629 Refs #631
This commit is contained in:
24 files changed
+583
-203
No files matched your search
@@ -27,4 +27,6 @@ PORT=4000
|
||||
DATA_DIR=./data
|
||||
NOTIFY_COOLDOWN_SEC=300
|
||||
ADMIN_IP_ALLOWLIST=
|
||||
# Comma-separated proxy IPs/CIDRs allowed to set X-Forwarded-For (e.g. 127.0.0.1,172.16.0.0/12). Empty = trust none.
|
||||
TRUSTED_PROXIES=
|
||||
TZ=Asia/Shanghai
|
||||
@@ -3,4 +3,4 @@ name: metapi
|
||||
description: Minimal metapi chart for digest-aware k3s update-center setups
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "1.3.0"
|
||||
appVersion: "1.3.1"
|
||||
@@ -10,6 +10,7 @@ PROXY_TOKEN=change-me-proxy-sk-token
|
||||
PORT=4000
|
||||
NOTIFY_COOLDOWN_SEC=300
|
||||
ADMIN_IP_ALLOWLIST=
|
||||
TRUSTED_PROXIES=
|
||||
TELEGRAM_ENABLED=false
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
TELEGRAM_CHAT_ID=
|
||||
|
||||
@@ -13,4 +13,5 @@ services:
|
||||
PORT: ${PORT:-4000}
|
||||
DATA_DIR: /app/data
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
TRUSTED_PROXIES: "${TRUSTED_PROXIES:-}"
|
||||
restart: unless-stopped
|
||||
@@ -133,6 +133,7 @@ Metapi 当前有三类主要配置入口:
|
||||
| `DATA_DIR` | 数据目录(SQLite 数据库存储位置) | `./data` |
|
||||
| `TZ` | 时区 | `Asia/Shanghai` |
|
||||
| `ACCOUNT_CREDENTIAL_SECRET` | 账号凭证加密密钥(用于加密存储的上游账号密码) | 默认使用 `AUTH_TOKEN` |
|
||||
| `TRUSTED_PROXIES` | 可信反向代理地址(逗号分隔的 IP / CIDR)。只有来自这些地址的连接才会采用 `X-Forwarded-For`;放在反向代理后面且依赖 `ADMIN_IP_ALLOWLIST` 或按 IP 限流时必须设置 | 空(不信任任何转发头) |
|
||||
|
||||
### 2. OAuth 与 Provider 登录
|
||||
|
||||
|
||||
@@ -251,6 +251,9 @@ Linux 安装包选择建议:
|
||||
|
||||
以下反向代理配置面向 Docker / 服务器模式。桌面版内置后端默认监听 `0.0.0.0:4000`,但通常仍作为单机桌面应用使用;如果要给局域网或公网客户端访问,请自行配置防火墙、反向代理和认证边界。若你显式设置了 `METAPI_DESKTOP_SERVER_PORT`,请把示例里的 `4000` 改成对应端口。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Metapi 默认不信任 `X-Forwarded-For`,客户端 IP 取 TCP 直连对端。放在反向代理后面且需要 `ADMIN_IP_ALLOWLIST` 或按 IP 限流时,请把反向代理自身的地址写进 `TRUSTED_PROXIES`(逗号分隔的 IP / CIDR,例如 `127.0.0.1,172.16.0.0/12`)。只有来自这些地址的连接才会采用转发头。
|
||||
|
||||
### Nginx
|
||||
|
||||
流式请求(SSE)需要关闭缓冲,否则流式输出会异常:
|
||||
|
||||
Generated
+133
-51
@@ -1,26 +1,26 @@
|
||||
{
|
||||
"name": "metapi",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "metapi",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"@fastify/static": "^10.1.10",
|
||||
"@visactor/react-vchart": "^2.0.20",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"electron-log": "^5.2.4",
|
||||
"electron-updater": "^6.6.2",
|
||||
"fastify": "^5.8.4",
|
||||
"fastify": "^5.12.8",
|
||||
"get-port": "^7.2.0",
|
||||
"marked": "^17.0.5",
|
||||
"minimatch": "^10.2.4",
|
||||
@@ -2573,9 +2573,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@fastify/send": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.1.0.tgz",
|
||||
"integrity": "sha512-TMYeQLCBSy2TOFmV95hQWkiTYgC/SEx7vMdV+wnZVX4tt8VBLKzmH8vV9OzJehV0+XBfg+WxPMt5wp+JBUKsVw==",
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.2.1.tgz",
|
||||
"integrity": "sha512-zOB8L9z444PnGbd1Nd7gNXPz/7bnDR8Z4KNTNSwLVQuE3cTGsU9qUj1N4SjXKK0Tq4cauZYTwB+tqvlqosuKsw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -2596,9 +2596,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@fastify/static": {
|
||||
"version": "9.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.0.0.tgz",
|
||||
"integrity": "sha512-r64H8Woe/vfilg5RTy7lwWlE8ZZcTrc3kebYFMEUBrMqlydhQyoiExQXdYAy2REVpST/G35+stAM8WYp1WGmMA==",
|
||||
"version": "10.1.10",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-10.1.10.tgz",
|
||||
"integrity": "sha512-CGwOoZiKg5m4SAqeiS8bzCSKDa71DMFQ7QeVsuWBOrfFu32DpVZWFFb0cpEg7e54YK6HZZsl4g/wfoKMnRQMUw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -2612,13 +2612,30 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@fastify/accept-negotiator": "^2.0.0",
|
||||
"@fastify/send": "^4.0.0",
|
||||
"content-disposition": "^1.0.1",
|
||||
"fastify-plugin": "^5.0.0",
|
||||
"@fastify/error": "^4.0.0",
|
||||
"@fastify/send": "^4.2.0",
|
||||
"content-disposition": "^3.0.0",
|
||||
"fastify-plugin": "^6.0.0",
|
||||
"fastq": "^1.17.1",
|
||||
"glob": "^13.0.0"
|
||||
"glob": "^14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@fastify/static/node_modules/fastify-plugin": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.1.tgz",
|
||||
"integrity": "sha512-4wW4RxSmvPXLrh5mgQEiu43qU3bw44N2ss4FTkTkQIbprUhE+/s43QX0j/ttcztdWK7PEkHqVthdc5GdEGDvjA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@hapi/address": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@hapi/address/-/address-5.1.1.tgz",
|
||||
@@ -3277,6 +3294,12 @@
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/nonrecursive-glob-match": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
|
||||
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
|
||||
"license": "BlueOak-1.0.0"
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
@@ -6454,15 +6477,15 @@
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.3.tgz",
|
||||
"integrity": "sha512-fy6KJm2RawA5RcHkLa1z/ScpBeA762UF9KmZQxwIbDtRJrgLzM10depAiEQ+CXYcoiqW1/m96OAAoke2nE9EeA==",
|
||||
"version": "5.0.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
|
||||
"integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/browserslist": {
|
||||
@@ -7162,12 +7185,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",
|
||||
"integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-3.0.0.tgz",
|
||||
"integrity": "sha512-ZH/0Xs9rMIFWCOmGdmS9eHBTF62qqQYNz4nVjQhkdIO/a0fCP4UIM3mRz/wiqL0L14YgAz/1xio4OaSY4+ON/A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=22"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
@@ -9260,9 +9283,9 @@
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/fastify": {
|
||||
"version": "5.8.4",
|
||||
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.4.tgz",
|
||||
"integrity": "sha512-sa42J1xylbBAYUWALSBoyXKPDUvM3OoNOibIefA+Oha57FryXKKCZarA1iDntOCWp3O35voZLuDg2mdODXtPzQ==",
|
||||
"version": "5.12.8",
|
||||
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.8.tgz",
|
||||
"integrity": "sha512-moP8exb2sCHLUbJkwp+I6C0padhy4D8lp0SdmzY7HhSdZuqm7O/u3o2aq7u8okaQ//33QDzj3G/u+FsSdB8Qzw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9281,11 +9304,11 @@
|
||||
"@fastify/proxy-addr": "^5.0.0",
|
||||
"abstract-logging": "^2.0.1",
|
||||
"avvio": "^9.0.0",
|
||||
"fast-json-stringify": "^6.0.0",
|
||||
"find-my-way": "^9.0.0",
|
||||
"fast-json-stringify": "^7.0.0",
|
||||
"find-my-way": "^9.10.0",
|
||||
"light-my-request": "^6.0.0",
|
||||
"pino": "^9.14.0 || ^10.1.0",
|
||||
"process-warning": "^5.0.0",
|
||||
"process-warning": "^5.1.0",
|
||||
"rfdc": "^1.3.1",
|
||||
"secure-json-parse": "^4.0.0",
|
||||
"semver": "^7.6.0",
|
||||
@@ -9308,6 +9331,46 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fastify/node_modules/fast-json-stringify": {
|
||||
"version": "7.3.4",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.3.4.tgz",
|
||||
"integrity": "sha512-ceZaDwrTGn/3xxGAU9jpoEI3udmpZz1Nr9W1aQf/OctkDo5Umg+7yMpEAUiiWBjArN9zxX1PF6V1jhjXuPxwNg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@fastify/merge-json-schemas": "^0.2.0",
|
||||
"ajv": "^8.12.0",
|
||||
"ajv-formats": "^3.0.1",
|
||||
"fast-uri": "^4.0.0",
|
||||
"json-schema-ref-resolver": "^3.0.0",
|
||||
"rfdc": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fastify/node_modules/fast-uri": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.3.tgz",
|
||||
"integrity": "sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/fastify/node_modules/semver": {
|
||||
"version": "7.7.4",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
||||
@@ -9413,9 +9476,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/find-my-way": {
|
||||
"version": "9.5.0",
|
||||
"resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.5.0.tgz",
|
||||
"integrity": "sha512-VW2RfnmscZO5KgBY5XVyKREMW5nMZcxDy+buTOsL+zIPnBlbKm+00sgzoQzq1EVh4aALZLfKdwv6atBGcjvjrQ==",
|
||||
"version": "9.10.0",
|
||||
"resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.10.0.tgz",
|
||||
"integrity": "sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
@@ -9758,14 +9821,14 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "13.0.6",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
|
||||
"integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
|
||||
"version": "14.0.4",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-14.0.4.tgz",
|
||||
"integrity": "sha512-mMiwNKoJZ4HAIRVJxotO6LsNRReA30gQwP9E2/p94tfLv+jygCNpKDjhhSL6OLY6LE371EZm5EAf7RpYuUqlsw==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"minimatch": "^10.2.2",
|
||||
"minimatch": "^11.0.5",
|
||||
"minipass": "^7.1.3",
|
||||
"path-scurry": "^2.0.2"
|
||||
"path-scurry": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
@@ -9774,6 +9837,22 @@
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/glob/node_modules/minimatch": {
|
||||
"version": "11.0.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.5.tgz",
|
||||
"integrity": "sha512-snPlVppFcYWfLLFQGhDxUyBcHNtMlWmn3jtj7pEaO+DP8pqL0IvAzXhMYmn1z9ASNtgmwLBdFxSf4tMUB0OTKA==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"@isaacs/nonrecursive-glob-match": "^1.1.0",
|
||||
"brace-expansion": "^5.0.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/global-agent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",
|
||||
@@ -12040,9 +12119,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/path-scurry": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
|
||||
"integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz",
|
||||
"integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"lru-cache": "^11.0.0",
|
||||
@@ -12056,9 +12135,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/path-scurry/node_modules/lru-cache": {
|
||||
"version": "11.2.6",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.6.tgz",
|
||||
"integrity": "sha512-ESL2CrkS/2wTPfuend7Zhkzo2u0daGJ/A2VucJOgQ/C48S/zB8MMeMHSGKYpXhIjbPxfuezITkaBH1wqv00DDQ==",
|
||||
"version": "11.5.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
|
||||
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
@@ -12487,9 +12566,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/process-warning": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
|
||||
"integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz",
|
||||
"integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -12886,9 +12965,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ret": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz",
|
||||
"integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==",
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/ret/-/ret-0.5.1.tgz",
|
||||
"integrity": "sha512-Z/nyvABwcRnRD2mMP7Kz6G1dFZZqX1mNErOnxF42OCQKE07b9k9hK9SQxHL3LFEZUdzQaLM4dId1E/E6Vm4WhA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
@@ -13112,9 +13191,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safe-regex2": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.0.0.tgz",
|
||||
"integrity": "sha512-YwJwe5a51WlK7KbOJREPdjNrpViQBI3p4T50lfwPuDhZnE3XGVTlGvi+aolc5+RvxDD6bnUmjVsU9n1eboLUYw==",
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.2.tgz",
|
||||
"integrity": "sha512-tAtCGFPPP02VroDVzp4daGi6bC7jWG+41D47GKf18FeH/ubvKQHT9VmhAkvtjNOmJwqtApzWeUpEhkyEYULvmw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -13128,6 +13207,9 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ret": "~0.5.0"
|
||||
},
|
||||
"bin": {
|
||||
"safe-regex2": "bin/safe-regex2.js"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-stable-stringify": {
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "metapi",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"description": "Meta-layer management and unified proxy for AI API aggregation platforms",
|
||||
"main": "dist/desktop/main.js",
|
||||
"keywords": [
|
||||
@@ -70,14 +70,14 @@
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"@fastify/static": "^10.1.10",
|
||||
"@visactor/react-vchart": "^2.0.20",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"dotenv": "^17.3.1",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"electron-log": "^5.2.4",
|
||||
"electron-updater": "^6.6.2",
|
||||
"fastify": "^5.8.4",
|
||||
"fastify": "^5.12.8",
|
||||
"get-port": "^7.2.0",
|
||||
"marked": "^17.0.5",
|
||||
"minimatch": "^10.2.4",
|
||||
|
||||
@@ -86,7 +86,7 @@ describe('buildConfig', () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('trusts forwarded client IP headers for reverse-proxy deployments', async () => {
|
||||
it('does not trust forwarded client IP headers by default', async () => {
|
||||
const app = Fastify(buildFastifyOptions(buildConfig({})));
|
||||
|
||||
app.get('/ip', async (request) => ({
|
||||
@@ -103,7 +103,32 @@ describe('buildConfig', () => {
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual({ ip: '203.0.113.5' });
|
||||
expect(response.json()).toEqual({ ip: '10.0.0.8' });
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('trusts forwarded client IP headers only from configured TRUSTED_PROXIES', async () => {
|
||||
const app = Fastify(buildFastifyOptions(buildConfig({ TRUSTED_PROXIES: '10.0.0.0/8' })));
|
||||
|
||||
app.get('/ip', async (request) => ({
|
||||
ip: request.ip,
|
||||
}));
|
||||
|
||||
const trusted = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/ip',
|
||||
remoteAddress: '10.0.0.8',
|
||||
headers: { 'x-forwarded-for': '203.0.113.5, 10.0.0.8' },
|
||||
});
|
||||
expect(trusted.json()).toEqual({ ip: '203.0.113.5' });
|
||||
|
||||
const untrusted = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/ip',
|
||||
remoteAddress: '198.51.100.20',
|
||||
headers: { 'x-forwarded-for': '203.0.113.5' },
|
||||
});
|
||||
expect(untrusted.json()).toEqual({ ip: '198.51.100.20' });
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -110,6 +110,8 @@ export function buildConfig(env: NodeJS.ProcessEnv) {
|
||||
smtpTo: env.SMTP_TO || '',
|
||||
notifyCooldownSec: Math.max(0, Math.trunc(parseNumber(env.NOTIFY_COOLDOWN_SEC, 300))),
|
||||
adminIpAllowlist: parseCsvList(env.ADMIN_IP_ALLOWLIST),
|
||||
// Socket peers (IPs/CIDRs) allowed to supply X-Forwarded-For. Empty = trust no proxy.
|
||||
trustedProxies: parseCsvList(env.TRUSTED_PROXIES),
|
||||
port: Math.trunc(parseNumber(env.PORT, 4000)),
|
||||
listenHost: parseListenHost(env),
|
||||
dataDir,
|
||||
@@ -177,7 +179,8 @@ export function buildFastifyOptions(
|
||||
): FastifyServerOptions {
|
||||
return {
|
||||
logger: true,
|
||||
trustProxy: true,
|
||||
// Only honor forwarded headers from explicitly configured proxies.
|
||||
trustProxy: appConfig.trustedProxies.length > 0 ? appConfig.trustedProxies : false,
|
||||
bodyLimit: appConfig.requestBodyLimit,
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { normalizeRequestPath } from './middleware/apiPath.js';
|
||||
|
||||
const DESKTOP_HEALTH_ROUTE = '/api/desktop/health';
|
||||
|
||||
export function isPublicApiRoute(url: string): boolean {
|
||||
return url === DESKTOP_HEALTH_ROUTE || url.startsWith('/api/oauth/callback/');
|
||||
const path = normalizeRequestPath(url);
|
||||
return path === DESKTOP_HEALTH_ROUTE || path.startsWith('/api/oauth/callback/');
|
||||
}
|
||||
|
||||
export async function registerDesktopRoutes(app: FastifyInstance) {
|
||||
|
||||
+13
-9
@@ -6,6 +6,12 @@ import {
|
||||
config,
|
||||
} from './config.js';
|
||||
import { authMiddleware } from './middleware/auth.js';
|
||||
import {
|
||||
createAdminAuthHook,
|
||||
isApiPath,
|
||||
isProxyApiPath,
|
||||
normalizeRequestPath,
|
||||
} from './middleware/apiPath.js';
|
||||
import { sitesRoutes } from './routes/api/sites.js';
|
||||
import { accountsRoutes } from './routes/api/accounts.js';
|
||||
import { checkinRoutes } from './routes/api/checkin.js';
|
||||
@@ -195,12 +201,9 @@ const app = Fastify(buildFastifyOptions(config));
|
||||
|
||||
await app.register(cors);
|
||||
|
||||
// Auth middleware for /api routes
|
||||
app.addHook('onRequest', async (request, reply) => {
|
||||
if (request.url.startsWith('/api/') && !isPublicApiRoute(request.url)) {
|
||||
await authMiddleware(request, reply);
|
||||
}
|
||||
});
|
||||
// Auth middleware for /api routes. The decision uses the matched route and the
|
||||
// router-equivalent normalized path, never the raw request-target prefix.
|
||||
app.addHook('onRequest', createAdminAuthHook(authMiddleware, isPublicApiRoute));
|
||||
|
||||
// Register API routes
|
||||
await app.register(registerDesktopRoutes);
|
||||
@@ -235,17 +238,18 @@ if (existsSync(webDir)) {
|
||||
setHeaders: (res, filePath) => {
|
||||
const normalizedPath = normalize(filePath);
|
||||
if (normalizedPath.includes(`${sep}assets${sep}`)) {
|
||||
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
res.header('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
return;
|
||||
}
|
||||
if (normalizedPath.endsWith(`${sep}index.html`)) {
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.header('Cache-Control', 'no-cache');
|
||||
}
|
||||
},
|
||||
});
|
||||
// SPA fallback
|
||||
app.setNotFoundHandler(async (request, reply) => {
|
||||
if (!request.url.startsWith('/api/') && !request.url.startsWith('/v1/')) {
|
||||
const normalizedPath = normalizeRequestPath(request.url);
|
||||
if (!isApiPath(normalizedPath) && !isProxyApiPath(normalizedPath)) {
|
||||
return reply.sendFile('index.html');
|
||||
}
|
||||
reply.code(404).send({ error: 'Not found' });
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { buildConfig, buildFastifyOptions } from '../config.js';
|
||||
import { isPublicApiRoute, registerDesktopRoutes } from '../desktop.js';
|
||||
import { createAdminAuthHook, isOriginFormTarget, normalizeRequestPath } from './apiPath.js';
|
||||
|
||||
const TEST_TOKEN = 'unit-test-admin-token';
|
||||
const ADMIN_ROUTES = ['/api/sites', '/api/settings/runtime', '/api/accounts/1'];
|
||||
|
||||
// Percent-encoding variants of a route, used to check that auth is decided on the
|
||||
// normalized path rather than on the raw request target.
|
||||
function percentEncodedForms(path: string): string[] {
|
||||
const encodeChar = (ch: string) => `%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`;
|
||||
const forms = new Set<string>();
|
||||
for (let i = 1; i < path.length; i += 1) {
|
||||
if (path[i] === '/') continue;
|
||||
forms.add(path.slice(0, i) + encodeChar(path[i]) + path.slice(i + 1));
|
||||
}
|
||||
forms.add(path.split('').map((ch, i) => (i === 0 || ch === '/' ? ch : encodeChar(ch))).join(''));
|
||||
return [...forms];
|
||||
}
|
||||
|
||||
describe('admin API auth guard', () => {
|
||||
let app: FastifyInstance;
|
||||
let handlerHits = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify({ ...buildFastifyOptions(buildConfig({})), logger: false });
|
||||
app.addHook('onRequest', createAdminAuthHook(async (request, reply) => {
|
||||
if (request.headers.authorization !== `Bearer ${TEST_TOKEN}`) {
|
||||
reply.code(401).send({ error: 'Missing Authorization header' });
|
||||
}
|
||||
}, isPublicApiRoute));
|
||||
await app.register(registerDesktopRoutes);
|
||||
for (const route of ['/api/sites', '/api/settings/runtime', '/api/accounts/:id']) {
|
||||
app.get(route, async () => {
|
||||
handlerHits += 1;
|
||||
return { ok: true };
|
||||
});
|
||||
}
|
||||
app.get('/api/oauth/callback/:provider', async () => ({ callback: true }));
|
||||
app.get('/public-page', async () => ({ page: true }));
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('requires auth on canonical admin routes and accepts the token', async () => {
|
||||
for (const url of ADMIN_ROUTES) {
|
||||
expect((await app.inject({ method: 'GET', url })).statusCode).toBe(401);
|
||||
const ok = await app.inject({ method: 'GET', url, headers: { authorization: `Bearer ${TEST_TOKEN}` } });
|
||||
expect(ok.statusCode).toBe(200);
|
||||
}
|
||||
});
|
||||
|
||||
it('never reaches an admin handler without auth for equivalent request targets', async () => {
|
||||
handlerHits = 0;
|
||||
for (const route of ADMIN_ROUTES) {
|
||||
for (const url of [...percentEncodedForms(route), `${route}?x=1`, `${route}/`]) {
|
||||
const response = await app.inject({ method: 'GET', url });
|
||||
expect([400, 401, 404], `unexpected ${response.statusCode} for ${url}`).toContain(response.statusCode);
|
||||
}
|
||||
}
|
||||
expect(handlerHits).toBe(0);
|
||||
});
|
||||
|
||||
it('still serves equivalent request targets to authenticated callers', async () => {
|
||||
let resolved = 0;
|
||||
for (const url of percentEncodedForms('/api/sites')) {
|
||||
const response = await app.inject({ method: 'GET', url, headers: { authorization: `Bearer ${TEST_TOKEN}` } });
|
||||
if (response.statusCode === 200) resolved += 1;
|
||||
}
|
||||
expect(resolved).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('only accepts origin-form request targets', () => {
|
||||
expect(isOriginFormTarget('/api/sites')).toBe(true);
|
||||
expect(isOriginFormTarget('*')).toBe(true);
|
||||
expect(isOriginFormTarget('http://localhost/api/sites')).toBe(false);
|
||||
expect(isOriginFormTarget('')).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps explicitly public API routes and non-API routes open', async () => {
|
||||
expect((await app.inject({ method: 'GET', url: '/api/desktop/health' })).statusCode).toBe(200);
|
||||
expect((await app.inject({ method: 'GET', url: '/api/oauth/callback/codex' })).statusCode).toBe(200);
|
||||
expect((await app.inject({ method: 'GET', url: '/public-page' })).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('does not treat a protected route as public because of its path shape', () => {
|
||||
expect(isPublicApiRoute('/api/oauth/callback/../../sites')).toBe(false);
|
||||
expect(isPublicApiRoute('/api/desktop/health')).toBe(true);
|
||||
});
|
||||
|
||||
it('normalizes request paths the way the router resolves them', () => {
|
||||
expect(normalizeRequestPath('/api/sites?x=1')).toBe('/api/sites');
|
||||
expect(normalizeRequestPath('/API//sites/')).toBe('/api/sites/');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Path helpers for deciding which requests belong to the admin API.
|
||||
*
|
||||
* Auth decisions must not depend on the raw request-target string: the router
|
||||
* decodes and normalizes the path before matching, so the guard derives the
|
||||
* path the same way (and errs towards treating a request as an API request).
|
||||
*/
|
||||
|
||||
const MAX_DECODE_PASSES = 3;
|
||||
|
||||
function decodePathOnce(path: string): string | null {
|
||||
try {
|
||||
return decodeURIComponent(path);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Only origin-form targets ("/path?query") and the asterisk form are accepted. */
|
||||
export function isOriginFormTarget(rawUrl: string | undefined): boolean {
|
||||
if (!rawUrl) return false;
|
||||
if (rawUrl === '*') return true;
|
||||
return rawUrl.charCodeAt(0) === 47 /* '/' */;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a request target into a canonical lowercase pathname: strip the
|
||||
* query/fragment, percent-decode (repeatedly, fail-safe), unify separators,
|
||||
* collapse duplicate slashes and resolve dot segments.
|
||||
*/
|
||||
export function normalizeRequestPath(rawUrl: string | undefined): string {
|
||||
let path = String(rawUrl || '/');
|
||||
const queryIndex = path.search(/[?#]/);
|
||||
if (queryIndex >= 0) path = path.slice(0, queryIndex);
|
||||
|
||||
for (let i = 0; i < MAX_DECODE_PASSES; i += 1) {
|
||||
const decoded = decodePathOnce(path);
|
||||
if (decoded === null || decoded === path) break;
|
||||
path = decoded;
|
||||
}
|
||||
|
||||
path = path.replace(/\\/g, '/').replace(/[\u0000-\u001f\u007f]/g, '');
|
||||
const segments: string[] = [];
|
||||
for (const segment of path.split('/')) {
|
||||
if (segment === '' || segment === '.') continue;
|
||||
if (segment === '..') {
|
||||
segments.pop();
|
||||
continue;
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
const trailingSlash = path.endsWith('/') && segments.length > 0 ? '/' : '';
|
||||
return `/${segments.join('/')}${trailingSlash}`.toLowerCase();
|
||||
}
|
||||
|
||||
function hasPrefix(path: string, prefix: string): boolean {
|
||||
return path === prefix || path.startsWith(`${prefix}/`);
|
||||
}
|
||||
|
||||
export function isApiPath(path: string): boolean {
|
||||
return hasPrefix(path, '/api');
|
||||
}
|
||||
|
||||
export function isProxyApiPath(path: string): boolean {
|
||||
return hasPrefix(path, '/v1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether a request must pass admin auth. Uses both the route the
|
||||
* router actually matched (authoritative) and the normalized request path
|
||||
* (covers unmatched requests), so either signal is enough to require auth.
|
||||
*/
|
||||
export function requiresAdminAuth(
|
||||
matchedRouteUrl: string | undefined,
|
||||
rawUrl: string | undefined,
|
||||
isPublicRoute: (path: string) => boolean,
|
||||
): boolean {
|
||||
const normalizedPath = normalizeRequestPath(rawUrl);
|
||||
const matched = matchedRouteUrl ? matchedRouteUrl.toLowerCase() : '';
|
||||
const matchedIsApi = matched ? isApiPath(matched) : false;
|
||||
if (!matchedIsApi && !isApiPath(normalizedPath)) return false;
|
||||
|
||||
// Public exemptions are decided on the matched route when there is one, so a
|
||||
// path that only *looks* public cannot reach a protected handler.
|
||||
if (matched) return !(matchedIsApi && isPublicRoute(matched));
|
||||
return !isPublicRoute(normalizedPath);
|
||||
}
|
||||
|
||||
type GuardRequest = { url: string; routeOptions?: { url?: string } };
|
||||
type GuardReply = { code(statusCode: number): { send(payload: unknown): unknown } };
|
||||
|
||||
/** Build the global onRequest hook that gates the admin API behind `authenticate`. */
|
||||
export function createAdminAuthHook<Req extends GuardRequest, Rep extends GuardReply>(
|
||||
authenticate: (request: Req, reply: Rep) => Promise<unknown>,
|
||||
isPublicRoute: (path: string) => boolean,
|
||||
) {
|
||||
return async function adminAuthHook(request: Req, reply: Rep) {
|
||||
if (!isOriginFormTarget(request.url)) {
|
||||
return reply.code(400).send({ error: 'Bad request target' });
|
||||
}
|
||||
if (requiresAdminAuth(request.routeOptions?.url, request.url, isPublicRoute)) {
|
||||
await authenticate(request, reply);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
}
|
||||
@@ -2,9 +2,23 @@ import { describe, expect, it } from 'vitest';
|
||||
import { extractClientIp, isIpAllowed } from './auth.js';
|
||||
|
||||
describe('auth middleware IP helpers', () => {
|
||||
it('extracts first forwarded IP and normalizes ipv4-mapped address', () => {
|
||||
const ip = extractClientIp('::ffff:10.0.0.1', '198.51.100.7, 203.0.113.2');
|
||||
expect(ip).toBe('198.51.100.7');
|
||||
it('uses the socket peer and ignores forwarded headers when no proxy is trusted', () => {
|
||||
expect(extractClientIp('::ffff:10.0.0.1', '198.51.100.7, 203.0.113.2', [])).toBe('10.0.0.1');
|
||||
expect(extractClientIp('203.0.113.50', ['198.51.100.7'], [])).toBe('203.0.113.50');
|
||||
});
|
||||
|
||||
it('ignores forwarded headers when the peer is not a trusted proxy', () => {
|
||||
expect(extractClientIp('203.0.113.50', '127.0.0.1', ['10.0.0.0/8'])).toBe('203.0.113.50');
|
||||
expect(isIpAllowed(extractClientIp('203.0.113.50', '127.0.0.1', ['10.0.0.0/8']), ['127.0.0.1'])).toBe(false);
|
||||
});
|
||||
|
||||
it('resolves the nearest untrusted hop when the peer is a trusted proxy', () => {
|
||||
expect(extractClientIp('::ffff:10.0.0.1', '198.51.100.7', ['10.0.0.0/8'])).toBe('198.51.100.7');
|
||||
// Client-supplied entries left of the hop added by the trusted proxy are not believed.
|
||||
expect(extractClientIp('10.0.0.1', '127.0.0.1, 198.51.100.7', ['10.0.0.0/8'])).toBe('198.51.100.7');
|
||||
expect(extractClientIp('10.0.0.1', '198.51.100.7, 10.0.0.2', ['10.0.0.0/8'])).toBe('198.51.100.7');
|
||||
expect(extractClientIp('10.0.0.1', undefined, ['10.0.0.0/8'])).toBe('10.0.0.1');
|
||||
expect(extractClientIp('10.0.0.1', 'not-an-ip', ['10.0.0.0/8'])).toBe('10.0.0.1');
|
||||
});
|
||||
|
||||
it('allows request when allowlist is empty', () => {
|
||||
|
||||
@@ -79,16 +79,38 @@ export function findInvalidIpAllowlistEntries(allowlist: string[]): string[] {
|
||||
return allowlist.filter((item) => parseAllowlistEntry(item) === null);
|
||||
}
|
||||
|
||||
export function extractClientIp(remoteIp: string | null | undefined, xForwardedFor?: string | string[] | undefined): string {
|
||||
if (Array.isArray(xForwardedFor)) {
|
||||
const first = xForwardedFor.find((item) => item && item.trim().length > 0);
|
||||
if (first) {
|
||||
return normalizeIp(first.split(',')[0]);
|
||||
}
|
||||
} else if (typeof xForwardedFor === 'string' && xForwardedFor.trim().length > 0) {
|
||||
return normalizeIp(xForwardedFor.split(',')[0]);
|
||||
function joinHeaderValues(value: string | string[] | undefined): string {
|
||||
if (Array.isArray(value)) return value.filter((item) => item && item.trim().length > 0).join(',');
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the client IP. Forwarded headers are only honored when the direct
|
||||
* socket peer is a configured trusted proxy; the chain is then walked from the
|
||||
* right, skipping trusted hops, so a client cannot prepend a spoofed address.
|
||||
*/
|
||||
export function extractClientIp(
|
||||
remoteIp: string | null | undefined,
|
||||
xForwardedFor?: string | string[] | undefined,
|
||||
trustedProxies: string[] = config.trustedProxies,
|
||||
): string {
|
||||
const peerIp = normalizeIp(remoteIp);
|
||||
if (!trustedProxies || trustedProxies.length === 0) return peerIp;
|
||||
if (!peerIp || !isIpAllowed(peerIp, trustedProxies)) return peerIp;
|
||||
|
||||
const forwardedChain = joinHeaderValues(xForwardedFor)
|
||||
.split(',')
|
||||
.map((item) => normalizeIp(item))
|
||||
.filter((item) => item.length > 0);
|
||||
|
||||
let clientIp = peerIp;
|
||||
for (let i = forwardedChain.length - 1; i >= 0; i -= 1) {
|
||||
const hop = forwardedChain[i];
|
||||
if (isIP(hop) === 0) break;
|
||||
clientIp = hop;
|
||||
if (!isIpAllowed(hop, trustedProxies)) break;
|
||||
}
|
||||
return normalizeIp(remoteIp);
|
||||
return clientIp;
|
||||
}
|
||||
|
||||
export function isIpAllowed(clientIp: string, allowlist: string[]): boolean {
|
||||
@@ -106,8 +128,12 @@ export function isIpAllowed(clientIp: string, allowlist: string[]): boolean {
|
||||
});
|
||||
}
|
||||
|
||||
export function getRequestClientIp(request: FastifyRequest): string {
|
||||
return extractClientIp(request.socket?.remoteAddress ?? request.ip, request.headers['x-forwarded-for']);
|
||||
}
|
||||
|
||||
export async function authMiddleware(request: FastifyRequest, reply: FastifyReply) {
|
||||
const clientIp = extractClientIp(request.ip, request.headers['x-forwarded-for']);
|
||||
const clientIp = getRequestClientIp(request);
|
||||
if (!isIpAllowed(clientIp, config.adminIpAllowlist)) {
|
||||
reply.code(403).send({ error: 'IP not allowed' });
|
||||
return;
|
||||
|
||||
@@ -23,17 +23,8 @@ function normalizeIp(rawIp: string | null | undefined): string {
|
||||
return ip;
|
||||
}
|
||||
|
||||
// request.ip honors forwarded headers only from TRUSTED_PROXIES (see buildFastifyOptions).
|
||||
function extractClientIp(request: FastifyRequest): string {
|
||||
const forwarded = request.headers['x-forwarded-for'];
|
||||
if (Array.isArray(forwarded)) {
|
||||
const first = forwarded.find((value) => typeof value === 'string' && value.trim().length > 0);
|
||||
if (first) return normalizeIp(first.split(',')[0]);
|
||||
}
|
||||
|
||||
if (typeof forwarded === 'string' && forwarded.trim().length > 0) {
|
||||
return normalizeIp(forwarded.split(',')[0]);
|
||||
}
|
||||
|
||||
return normalizeIp(request.ip);
|
||||
}
|
||||
|
||||
|
||||
@@ -219,7 +219,8 @@ describe('settings and auth events', () => {
|
||||
expect(savedMaxBodyBytes?.value).toBe(JSON.stringify(131072));
|
||||
});
|
||||
|
||||
it('returns current recognized admin IP in runtime settings response', async () => {
|
||||
it('ignores forwarded headers from untrusted peers when reporting admin IP', async () => {
|
||||
(config as any).trustedProxies = [];
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/settings/runtime',
|
||||
@@ -231,11 +232,31 @@ describe('settings and auth events', () => {
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = response.json() as { currentAdminIp?: string; serverTimeZone?: string };
|
||||
expect(body.currentAdminIp).toBe('203.0.113.5');
|
||||
expect(body.currentAdminIp).toBe('10.0.0.8');
|
||||
expect(typeof body.serverTimeZone).toBe('string');
|
||||
expect((body.serverTimeZone || '').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('returns forwarded admin IP when the peer is a configured trusted proxy', async () => {
|
||||
(config as any).trustedProxies = ['10.0.0.0/8'];
|
||||
try {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/settings/runtime',
|
||||
remoteAddress: '10.0.0.8',
|
||||
headers: {
|
||||
'x-forwarded-for': '203.0.113.5, 10.0.0.8',
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = response.json() as { currentAdminIp?: string };
|
||||
expect(body.currentAdminIp).toBe('203.0.113.5');
|
||||
} finally {
|
||||
(config as any).trustedProxies = [];
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects proxy token that does not start with sk-', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
parseBackupWebdavExportPayload,
|
||||
} from '../../contracts/settingsRoutePayloads.js';
|
||||
import { formatUtcSqlDateTime, getResolvedTimeZone } from '../../services/localTimeService.js';
|
||||
import { extractClientIp, findInvalidIpAllowlistEntries, isIpAllowed } from '../../middleware/auth.js';
|
||||
import { findInvalidIpAllowlistEntries, getRequestClientIp, isIpAllowed } from '../../middleware/auth.js';
|
||||
import { invalidateSiteProxyCache, normalizeSiteProxyUrl, withExplicitProxyRequestInit } from '../../services/siteProxy.js';
|
||||
import { performFactoryReset } from '../../services/factoryResetService.js';
|
||||
import { normalizeLogCleanupRetentionDays } from '../../shared/logCleanupRetentionDays.js';
|
||||
@@ -837,7 +837,7 @@ function buildRuntimeDatabaseState(saved: RuntimeDatabaseConfig | null) {
|
||||
|
||||
export async function settingsRoutes(app: FastifyInstance) {
|
||||
await app.get('/api/settings/runtime', async (request) => {
|
||||
const currentAdminIp = extractClientIp(request.ip, request.headers['x-forwarded-for']);
|
||||
const currentAdminIp = getRequestClientIp(request);
|
||||
return getRuntimeSettingsResponse(currentAdminIp);
|
||||
});
|
||||
|
||||
@@ -901,7 +901,7 @@ export async function settingsRoutes(app: FastifyInstance) {
|
||||
|
||||
const body = parsedBody.data as RuntimeSettingsBody;
|
||||
const changedLabels: string[] = [];
|
||||
const currentRequestIp = extractClientIp(request.ip, request.headers['x-forwarded-for']);
|
||||
const currentRequestIp = getRequestClientIp(request);
|
||||
|
||||
const webhookTouched = body.webhookUrl !== undefined || body.webhookEnabled !== undefined;
|
||||
const nextWebhookUrl = body.webhookUrl !== undefined
|
||||
|
||||
@@ -467,15 +467,16 @@ describe('update center routes', () => {
|
||||
});
|
||||
|
||||
it('forces a live refresh on manual check and persists the refreshed snapshot', async () => {
|
||||
const nextVersion = getNextPatchVersion((await import('../../services/updateCenterVersionService.js')).getCurrentRuntimeVersion());
|
||||
await saveValidConfig();
|
||||
fetchLatestStableGitHubReleaseMock.mockResolvedValue({
|
||||
source: 'github-release',
|
||||
rawVersion: 'v1.3.1',
|
||||
normalizedVersion: '1.3.1',
|
||||
tagName: 'v1.3.1',
|
||||
displayVersion: '1.3.1',
|
||||
rawVersion: `v${nextVersion}`,
|
||||
normalizedVersion: nextVersion,
|
||||
tagName: `v${nextVersion}`,
|
||||
displayVersion: nextVersion,
|
||||
publishedAt: '2026-03-31T10:00:00Z',
|
||||
url: 'https://github.com/cita-777/metapi/releases/tag/v1.3.1',
|
||||
url: `https://github.com/cita-777/metapi/releases/tag/v${nextVersion}`,
|
||||
});
|
||||
fetchLatestDockerHubTagMock.mockResolvedValue({
|
||||
source: 'docker-hub-tag',
|
||||
@@ -507,7 +508,7 @@ describe('update center routes', () => {
|
||||
expect(checkResponse.statusCode).toBe(200);
|
||||
expect(checkResponse.json()).toMatchObject({
|
||||
githubRelease: {
|
||||
normalizedVersion: '1.3.1',
|
||||
normalizedVersion: nextVersion,
|
||||
},
|
||||
dockerHubTag: {
|
||||
digest: 'sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
|
||||
@@ -524,10 +525,10 @@ describe('update center routes', () => {
|
||||
expect(getUpdateCenterHelperStatusMock).toHaveBeenCalledTimes(1);
|
||||
expect(await loadUpdateCenterRuntimeState()).toEqual(expect.objectContaining({
|
||||
lastResolvedSource: 'github-release',
|
||||
lastResolvedDisplayVersion: '1.3.1',
|
||||
lastResolvedDisplayVersion: nextVersion,
|
||||
statusSnapshot: {
|
||||
githubRelease: expect.objectContaining({
|
||||
normalizedVersion: '1.3.1',
|
||||
normalizedVersion: nextVersion,
|
||||
}),
|
||||
dockerHubTag: expect.objectContaining({
|
||||
digest: 'sha256:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
|
||||
@@ -790,6 +791,7 @@ describe('update center routes', () => {
|
||||
});
|
||||
|
||||
it('streams deployment logs for known tasks and rejects unknown task ids', async () => {
|
||||
const nextVersion = getNextPatchVersion((await import('../../services/updateCenterVersionService.js')).getCurrentRuntimeVersion());
|
||||
await saveValidConfig();
|
||||
|
||||
const missingResponse = await app.inject({
|
||||
@@ -805,7 +807,7 @@ describe('update center routes', () => {
|
||||
return {
|
||||
success: true,
|
||||
targetSource: 'docker-hub-tag',
|
||||
targetTag: '1.3.1',
|
||||
targetTag: nextVersion,
|
||||
targetDigest: null,
|
||||
previousRevision: '13',
|
||||
finalRevision: '14',
|
||||
@@ -819,7 +821,7 @@ describe('update center routes', () => {
|
||||
url: '/api/update-center/deploy',
|
||||
payload: {
|
||||
source: 'docker-hub-tag',
|
||||
targetVersion: '1.3.1',
|
||||
targetVersion: nextVersion,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { ApiTokenInfo, BasePlatformAdapter, CheckinResult, BalanceInfo, UserInfo, TokenVerifyResult, CreateApiTokenOptions, type SiteAnnouncement } from './base.js';
|
||||
import type { RequestInit as UndiciRequestInit } from 'undici';
|
||||
import { createContext, runInContext } from 'node:vm';
|
||||
import { withSiteProxyRequestInit } from '../siteProxy.js';
|
||||
import { fetchJsonWithShieldCookieRetry } from './newApiShield.js';
|
||||
import { fetchJsonWithShieldCookieRetry, solveNewApiAcwScV2 } from './newApiShield.js';
|
||||
|
||||
export class NewApiAdapter extends BasePlatformAdapter {
|
||||
readonly platformName: string = 'new-api';
|
||||
@@ -386,78 +385,9 @@ export class NewApiAdapter extends BasePlatformAdapter {
|
||||
};
|
||||
}
|
||||
|
||||
private parseChallengeArg1(html: string): string | null {
|
||||
const match = html.match(/var\s+arg1\s*=\s*['"]([0-9a-fA-F]+)['"]/);
|
||||
return match?.[1]?.toUpperCase() || null;
|
||||
}
|
||||
|
||||
private parseChallengeMapping(html: string): number[] | null {
|
||||
const match = html.match(/for\(var m=\[([^\]]+)\],p=L\(0x115\)/);
|
||||
if (!match?.[1]) return null;
|
||||
|
||||
const values = match[1].split(',').map((raw) => {
|
||||
const v = raw.trim().toLowerCase();
|
||||
if (!v) return Number.NaN;
|
||||
if (v.startsWith('0x')) return Number.parseInt(v.slice(2), 16);
|
||||
return Number.parseInt(v, 10);
|
||||
});
|
||||
if (values.some((v) => Number.isNaN(v))) return null;
|
||||
return values;
|
||||
}
|
||||
|
||||
private parseChallengeXorSeed(html: string): string | null {
|
||||
const fnStart = html.indexOf('function a0i()');
|
||||
const bStart = html.indexOf('function b(');
|
||||
const rotateStart = html.indexOf('(function(a,c){');
|
||||
const rotateEnd = html.indexOf('),!(function', rotateStart);
|
||||
if (fnStart < 0 || bStart < 0 || bStart <= fnStart || rotateStart < 0 || rotateEnd < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const helperCode = html.slice(fnStart, bStart);
|
||||
const rotateCode = `${html.slice(rotateStart, rotateEnd + 1)})`;
|
||||
|
||||
try {
|
||||
const sandbox: Record<string, unknown> = { decodeURIComponent };
|
||||
createContext(sandbox);
|
||||
runInContext(helperCode, sandbox, { timeout: 100 });
|
||||
runInContext(rotateCode, sandbox, { timeout: 100 });
|
||||
const decoder = sandbox['a0j'];
|
||||
if (typeof decoder !== 'function') return null;
|
||||
const seed = (decoder as (idx: number) => unknown)(0x115);
|
||||
if (typeof seed !== 'string' || !/^[0-9a-f]+$/i.test(seed)) return null;
|
||||
return seed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private solveAcwScV2(html: string): string | null {
|
||||
const arg1 = this.parseChallengeArg1(html);
|
||||
const mapping = this.parseChallengeMapping(html);
|
||||
const xorSeed = this.parseChallengeXorSeed(html);
|
||||
if (!arg1 || !mapping || !xorSeed) return null;
|
||||
|
||||
const q: string[] = [];
|
||||
for (let i = 0; i < arg1.length; i += 1) {
|
||||
const ch = arg1[i];
|
||||
for (let j = 0; j < mapping.length; j += 1) {
|
||||
if (mapping[j] === i + 1) {
|
||||
q[j] = ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const reordered = q.join('');
|
||||
let out = '';
|
||||
for (let i = 0; i < reordered.length && i < xorSeed.length; i += 2) {
|
||||
const left = Number.parseInt(reordered.slice(i, i + 2), 16);
|
||||
const right = Number.parseInt(xorSeed.slice(i, i + 2), 16);
|
||||
if (Number.isNaN(left) || Number.isNaN(right)) return null;
|
||||
out += (left ^ right).toString(16).padStart(2, '0');
|
||||
}
|
||||
|
||||
return out || null;
|
||||
// Shared pure parser: never executes upstream-supplied script.
|
||||
return solveNewApiAcwScV2(html);
|
||||
}
|
||||
|
||||
private upsertCookie(cookieHeader: string, name: string, value: string): string {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const vmCalls: string[] = [];
|
||||
vi.mock('node:vm', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:vm')>();
|
||||
return {
|
||||
...actual,
|
||||
createContext: (...args: Parameters<typeof actual.createContext>) => {
|
||||
vmCalls.push('createContext');
|
||||
return actual.createContext(...args);
|
||||
},
|
||||
runInContext: (...args: Parameters<typeof actual.runInContext>) => {
|
||||
vmCalls.push('runInContext');
|
||||
return actual.runInContext(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { solveNewApiAcwScV2 } = await import('./newApiShield.js');
|
||||
const { NewApiAdapter } = await import('./newApi.js');
|
||||
|
||||
const CHALLENGE_HTML = readFileSync(new URL('./__fixtures__/anyrouter-challenge.html', import.meta.url), 'utf8');
|
||||
const CHALLENGE_ACW = '699dbedad126579b6bc0ebb91eaae8d7af3548b5';
|
||||
const MARKER = '__metapiShieldTestMarker';
|
||||
|
||||
afterEach(() => {
|
||||
vmCalls.length = 0;
|
||||
delete (globalThis as Record<string, unknown>)[MARKER];
|
||||
});
|
||||
|
||||
describe('new-api shield challenge solver', () => {
|
||||
it('solves the challenge by parsing data only, without node:vm', () => {
|
||||
expect(solveNewApiAcwScV2(CHALLENGE_HTML)).toBe(CHALLENGE_ACW);
|
||||
const adapter = new NewApiAdapter() as unknown as { solveAcwScV2(html: string): string | null };
|
||||
expect(adapter.solveAcwScV2(CHALLENGE_HTML)).toBe(CHALLENGE_ACW);
|
||||
expect(vmCalls).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not run upstream-supplied script from the challenge page', () => {
|
||||
// Replace the page's helper functions with script that would leave a marker if executed.
|
||||
const marker = `globalThis.${MARKER}=true;`;
|
||||
const tampered = CHALLENGE_HTML
|
||||
.replace('function a0i(){', `function a0i(){${marker}`)
|
||||
.replace('(function(a,c){', `(function(a,c){${marker}`);
|
||||
expect(tampered).not.toBe(CHALLENGE_HTML);
|
||||
|
||||
solveNewApiAcwScV2(tampered);
|
||||
const adapter = new NewApiAdapter() as unknown as { solveAcwScV2(html: string): string | null };
|
||||
adapter.solveAcwScV2(tampered);
|
||||
|
||||
expect((globalThis as Record<string, unknown>)[MARKER]).toBeUndefined();
|
||||
expect(vmCalls).toEqual([]);
|
||||
});
|
||||
|
||||
it('fails closed when the seed cannot be parsed unambiguously', () => {
|
||||
expect(solveNewApiAcwScV2('<html><script>var arg1="ABC123";</script></html>')).toBeNull();
|
||||
const withoutTable = CHALLENGE_HTML.replace(/function a0i\(\)\{var N=\[[^\]]*\]/, 'function a0i(){var N=[]');
|
||||
expect(solveNewApiAcwScV2(withoutTable)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { RequestInit as UndiciRequestInit } from 'undici';
|
||||
import { createContext, runInContext } from 'node:vm';
|
||||
import { withSiteProxyRequestInit } from '../siteProxy.js';
|
||||
|
||||
const SHIELD_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36';
|
||||
@@ -67,38 +66,44 @@ function parseChallengeMapping(html: string): number[] | null {
|
||||
return values;
|
||||
}
|
||||
|
||||
function parseChallengeXorSeed(html: string): string | null {
|
||||
const fnStart = html.indexOf('function a0i()');
|
||||
const bStart = html.indexOf('function b(');
|
||||
const rotateStart = html.indexOf('(function(a,c){');
|
||||
const rotateEnd = html.indexOf('),!(function', rotateStart);
|
||||
if (fnStart < 0 || bStart < 0 || bStart <= fnStart || rotateStart < 0 || rotateEnd < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const helperCode = html.slice(fnStart, bStart);
|
||||
const rotateCode = `${html.slice(rotateStart, rotateEnd + 1)})`;
|
||||
const CHALLENGE_STRING_TABLE_PATTERN = /function\s+[\w$]+\(\)\s*\{\s*var\s+[\w$]+\s*=\s*\[([^\]]*)\]/;
|
||||
const CHALLENGE_STRING_LITERAL_PATTERN = /'([A-Za-z0-9+/=]*)'/g;
|
||||
|
||||
// The challenge page ships a string table encoded with a case-swapped base64
|
||||
// alphabet. Decode it as data only: upstream script is never executed.
|
||||
function decodeChallengeTableEntry(encoded: string): string | null {
|
||||
const standard = encoded.replace(/[a-zA-Z]/g, (ch) => (
|
||||
ch === ch.toLowerCase() ? ch.toUpperCase() : ch.toLowerCase()
|
||||
));
|
||||
try {
|
||||
const sandbox: Record<string, unknown> = { decodeURIComponent };
|
||||
createContext(sandbox);
|
||||
runInContext(helperCode, sandbox, { timeout: 100 });
|
||||
runInContext(rotateCode, sandbox, { timeout: 100 });
|
||||
const decoder = sandbox.a0j;
|
||||
if (typeof decoder !== 'function') return null;
|
||||
const seed = (decoder as (index: number) => unknown)(0x115);
|
||||
if (typeof seed !== 'string' || !/^[0-9a-f]+$/i.test(seed)) return null;
|
||||
return seed;
|
||||
return Buffer.from(standard, 'base64').toString('utf8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseChallengeXorSeed(html: string, expectedLength: number): string | null {
|
||||
const table = html.match(CHALLENGE_STRING_TABLE_PATTERN)?.[1];
|
||||
if (!table || expectedLength <= 0) return null;
|
||||
|
||||
const candidates = new Set<string>();
|
||||
for (const match of table.matchAll(CHALLENGE_STRING_LITERAL_PATTERN)) {
|
||||
const decoded = decodeChallengeTableEntry(match[1]);
|
||||
if (decoded && decoded.length === expectedLength && /^[0-9a-f]+$/i.test(decoded)) {
|
||||
candidates.add(decoded.toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
// Fail closed unless exactly one plausible seed is present.
|
||||
return candidates.size === 1 ? [...candidates][0] : null;
|
||||
}
|
||||
|
||||
export function solveNewApiAcwScV2(html: string): string | null {
|
||||
const arg1 = parseChallengeArg1(html);
|
||||
const mapping = parseChallengeMapping(html);
|
||||
const xorSeed = parseChallengeXorSeed(html);
|
||||
if (!arg1 || !mapping || !xorSeed) return null;
|
||||
if (!arg1 || !mapping) return null;
|
||||
const xorSeed = parseChallengeXorSeed(html, arg1.length);
|
||||
if (!xorSeed) return null;
|
||||
|
||||
const reordered: string[] = [];
|
||||
for (let i = 0; i < arg1.length; i += 1) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { tr } from '../i18n.js';
|
||||
import { SITE_DOCS_URL } from '../docsLink.js';
|
||||
import { buildUpdateReminder } from './helpers/updateCenterPresentation.js';
|
||||
|
||||
const VERSION = '1.3.0';
|
||||
const VERSION = '1.3.1';
|
||||
|
||||
const FEATURES = [
|
||||
{ icon: '🌐', title: '统一代理网关', desc: '一个 Key、一个入口,兼容 OpenAI / Claude 下游格式' },
|
||||
|
||||
Reference in new issue
Block a user