diff --git a/backend/backend-site/server.py b/backend/backend-site/server.py index 999de63..6bc36a2 100644 --- a/backend/backend-site/server.py +++ b/backend/backend-site/server.py @@ -60,6 +60,19 @@ def payplatform_api(path, params=None): return {"ec": -1, "em": "调用失败:%r" % e} +def _hook_unverified(oid_af, order, why, ip): + """没验证过的爱发电回调:只留最近 50 条在 kv「hook_unverified」里,给金钻人工核对用(2026-10-06 安全加固)。 + 字段全部截断,不进账本 pay_orders —— 伪造的报文刷再多也只占这 50 格。""" + try: + lst = STORE.kv_get("hook_unverified", []) or [] + lst.append({"ts": now().isoformat(timespec="seconds"), "out_trade_no": str(oid_af)[:64], "why": why[:60], + "amount": str(order.get("show_amount") or order.get("total_amount") or "")[:16], + "title": ("%s %s" % (order.get("plan_title") or "", order.get("title") or "")).strip()[:60], "ip": str(ip)[:45]}) + STORE.kv_put("hook_unverified", lst[-50:]) + except Exception as e: + log("记待核对回调失败:%s" % e) + + def payplatform_find_order(out_trade_no, pages=3): """按订单号反查(确认这笔真的存在、真的付款了)。返回订单 dict 或 None。""" for pg in range(1, pages + 1): @@ -401,7 +414,8 @@ def gift_claim(bid, token, ip): return False, "这批券过期了" with LOCK: cs = load_codes() - mine = [c for c, r in cs.items() if r.get("gift") == bid and r.get("claim_token") == tok] + mine = [c for c, r in cs.items() if r.get("gift") == bid and isinstance(tok, str) and tok + and hmac.compare_digest(str(r.get("claim_token") or ""), tok)] # 定长比较(2026-10-06 安全加固) if mine: return False, "你已经领过啦 —— 这批每人限一张 😉 想多要就等下一波福利" ip_n = len([c for c, r in cs.items() @@ -2266,10 +2280,16 @@ class H(BaseHTTPRequestHandler): obj = json.loads(raw.decode("utf-8", "replace") or "{}") except ValueError: obj = {"_parse_error": True, "_raw": raw[:2000].decode("utf-8", "replace")} + # 回调日志(2026-10-06 安全加固):这个地址谁都能 POST —— 只记几个关键头 + 正文前 4KB, + # 超过 5MB 轮转成 .1(只留一份旧的),不然一个人就能把磁盘写满。 try: + if os.path.exists(PAYPLATFORM_LOG) and os.path.getsize(PAYPLATFORM_LOG) > 5 * 1024 * 1024: + os.replace(PAYPLATFORM_LOG, PAYPLATFORM_LOG + ".1") + keep = {k: v for k, v in self.headers.items() if k.lower() in ("user-agent", "content-type", "x-real-ip", "x-forwarded-for")} + body = json.dumps(obj, ensure_ascii=False) with open(PAYPLATFORM_LOG, "a", encoding="utf-8") as f: - f.write(json.dumps({"ts": now().isoformat(timespec="seconds"), "ip": ip_of(self), - "headers": dict(self.headers.items()), "body": obj}, + f.write(json.dumps({"ts": now().isoformat(timespec="seconds"), "ip": ip_of(self), "headers": keep, + "body": body[:4096] + ("…(截断)" if len(body) > 4096 else "")}, ensure_ascii=False) + "\n") except OSError: pass @@ -2300,21 +2320,17 @@ class H(BaseHTTPRequestHandler): if int(order.get("status") or 0) != 2: log("爱发电回调:%s 状态不是已付款(status=%s),先不发码" - % (oid_af, order.get("status"))) - led[oid_af] = {"ts": now().isoformat(timespec="seconds"), "status": order.get("status"), - "amount": order.get("show_amount") or order.get("total_amount"), - "code": None, "note": "未付款"} - STORE.ledger_save(led) + % (oid_af[:64], str(order.get("status"))[:8])) + # ⚠️ 2026-10-06 安全加固:没经过开放接口验证的报文**不写进账本**(原来会把任何人编的单号 / 金额 + # 写进库里的 pay_orders,一刷就是成千上万条,每次存账本还要整表重写 → 拖慢真付款)。 + _hook_unverified(oid_af, order, "未付款(status=%s)" % str(order.get("status"))[:8], ip_of(self)) return self.js({"ec": 200, "em": ""}) real = payplatform_find_order(oid_af) if not real: # 没验过就不发码 —— 宁可让金钻手工补,也不给伪造的报文发货 - log("⚠️ 爱发电回调:%s 在开放接口里查不到(可能官方延迟/伪造),没发码" % oid_af) - led[oid_af] = {"ts": now().isoformat(timespec="seconds"), "code": None, - "amount": order.get("show_amount") or order.get("total_amount"), - "note": "接口没查到,待人工核对", "need_human": True} - STORE.ledger_save(led) + log("⚠️ 爱发电回调:%s 在开放接口里查不到(可能官方延迟/伪造),没发码" % oid_af[:64]) + _hook_unverified(oid_af, order, "接口没查到,待人工核对", ip_of(self)) return self.js({"ec": 200, "em": ""}) n_img_af = payplatform_img_count(real) diff --git a/backend/backend-site/tests/回执复现测试.py b/backend/backend-site/tests/回执复现测试.py index ef171c6..ce35e4e 100644 --- a/backend/backend-site/tests/回执复现测试.py +++ b/backend/backend-site/tests/回执复现测试.py @@ -199,6 +199,22 @@ m2 = S.read_meta(h2) check("洞:同一笔付款改报文里的订单号,不能再激活另一单", (m2 or {}).get("state") in ("unpaid", "paid"), "第二单状态=%s" % (m2 or {}).get("state")) +# 2026-10-06 安全加固:伪造的回调(没付款 / 开放接口查不到)不能写进账本,刷再多也只占 50 格待核对 +led0 = len(S.STORE.ledger_all()) +for k in range(60): + fake = {"data": {"order": {"out_trade_no": "FAKE%04d" % k, "status": 1 if k % 2 else 2, + "total_amount": "999", "title": "x" * 500}}} + req("POST", "/api/payplatform-hook", fake) +pend = S.STORE.kv_get("hook_unverified", []) or [] +check("洞:伪造回调刷 60 次 → 账本一条都不多,待核对清单封顶 50 条、字段截断", + len(S.STORE.ledger_all()) == led0 and len(pend) == 50 and all(len(x.get("title", "")) <= 60 for x in pend), + "账本 %d → %d,待核对 %d 条" % (led0, len(S.STORE.ledger_all()), len(pend))) +logsz = os.path.getsize(S.PAYPLATFORM_LOG) if os.path.exists(S.PAYPLATFORM_LOG) else 0 +hook_big = {"data": {"order": {"out_trade_no": "BIG", "status": 1}}, "junk": "y" * 60000} +req("POST", "/api/payplatform-hook", hook_big) +grew = (os.path.getsize(S.PAYPLATFORM_LOG) if os.path.exists(S.PAYPLATFORM_LOG) else 0) - logsz +check("加固:回调日志一条最多记 4KB 正文(60KB 的报文不会整包写盘)", 0 < grew < 6000, "这一条写了 %d 字节" % grew) + # ================================================================== 5. 重渲换皮肤绕过 PNG 核验 st, j, _ = submit([S.gen_codes(1)[0]], ["stand"]) r_oid, r_tok = j["order"], j["token"] diff --git a/backend/backend-tools/ys_admin.py b/backend/backend-tools/ys_admin.py index 79312a2..e20667d 100644 --- a/backend/backend-tools/ys_admin.py +++ b/backend/backend-tools/ys_admin.py @@ -496,7 +496,8 @@ const STN={unpaid:'待付款',paid:'买家说付好了',waiting:'排队中',work const STC={unpaid:'n',paid:'g',waiting:'b',working:'b',done:'g',failed:'r',void:'n'}; const CSTN={active:'还没用',inactive:'停用',bound:'已激活',used:'已核销'}; const CSTC={active:'g',inactive:'n',bound:'b',used:'n'}; -function esc(s){const d=document.createElement('div');d.textContent=s==null?'':String(s);return d.innerHTML;} +/* 转义:连引号一起转(2026-10-06 安全加固:原来用 textContent 只转 <>&,放进属性里会被买家写的备注撑破) */ +function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));} function when(s){return String(s||'').replace('T',' ').slice(5,16);} function toast(t){const e=$('#toast');e.textContent=t;e.classList.add('on');clearTimeout(e._t);e._t=setTimeout(()=>e.classList.remove('on'),2600);} function copytxt(t,what){ diff --git a/backend/deploy/nginx-片段.md b/backend/deploy/nginx-片段.md index 62b2243..2ec322b 100644 --- a/backend/deploy/nginx-片段.md +++ b/backend/deploy/nginx-片段.md @@ -132,3 +132,36 @@ location /order/ { 防护全在后端自己的限流 + 两把令牌 + 来源 IP 门上。 - **没做多机/负载均衡**:单机单进程,够用。 - **HTTPS 用自动签发的证书**,续期自动化,没有额外动作。 + + +## ⑤ 安全加固(2026-10-06,线上已加) + +```nginx +# 文件:/etc/nginx/snippets/jz-sec-base.conf +add_header Strict-Transport-Security "max-age=31536000" always; +add_header X-Content-Type-Options "nosniff" always; +add_header X-Frame-Options "SAMEORIGIN" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; +add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always; + +# 文件:/etc/nginx/snippets/jz-sec-csp.conf(只给本站页面) +add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' blob:; font-src 'self' data:; connect-src 'self'; frame-src https://player.bilibili.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always; + +# server 块里: +include snippets/jz-sec-base.conf; +include snippets/jz-sec-csp.conf; +location ~* (\.bak[^/]*|\.maint[^/]*|\.old[^/]*|\.orig|\.swp|~|\.v[0-9]+-(live|new)[^/]*)$ { return 404; } +location ~* ^/(order/)?preview-[^/]*\.html$ { return 404; } +location ~ /\.(?!well-known/) { return 404; } +location = /content/site.json { return 404; } +location = /order/content/order.json { return 404; } +# 回调单独限流(http 级:limit_req_zone $binary_remote_addr zone=jzhook:1m rate=20r/m;) +location ~ ^/order/api/(payplatform|afdian)-hook$ { + limit_req zone=jzhook burst=10 nodelay; limit_req_status 429; client_max_body_size 64k; + rewrite ^/order/api/(.*)$ /api/$1 break; proxy_pass http://localhost:; + proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; + add_header Cache-Control "no-store" always; include snippets/jz-sec-base.conf; +} +# ⚠️ 每个自己写了 add_header 的 location 里都要再 include 上面两个文件(nginx 不继承 server 级的 add_header) +# nginx.conf 的 http 块:server_tokens off; +``` diff --git a/portal/about.html b/portal/about.html index 1b629ac..33c154f 100644 --- a/portal/about.html +++ b/portal/about.html @@ -10,7 +10,7 @@ - + @@ -29,13 +29,13 @@ try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: r - + - - - + + + diff --git a/portal/assets/pages.js b/portal/assets/pages.js index 66b8735..2c50afe 100644 --- a/portal/assets/pages.js +++ b/portal/assets/pages.js @@ -165,8 +165,9 @@ /* 自助渲染:渲染机在不在线、每张多少钱(读下单那边的接口 / 内容文件,拿不到就不写) */ (function desk() { var s = $('#deskStatus'), p = $('#deskPrice'); - fetch('/order/content/order.json', { cache: 'no-cache' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (o) { - var per = o && o.prices && o.prices.per; + /* 价格读下单页公开的价格接口(内容后台的原始 order.json 不对外,2026-10-06 安全加固) */ + fetch('/order/api/payinfo', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (o) { + var per = o && o.per; if (p && per) p.textContent = '每张 ' + per + ' 元起,一般 40 秒左右出图'; }).catch(function () {}); fetch('/order/api/status', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (j) { diff --git a/portal/assets/universe/gate.js b/portal/assets/universe/gate.js index 85707f0..f45fb0b 100644 --- a/portal/assets/universe/gate.js +++ b/portal/assets/universe/gate.js @@ -16,7 +16,8 @@ var all = uv.lit.concat(uv.empty).sort(function (a, b) { return a.no < b.no ? -1 : 1; }); slots.innerHTML = all.map(function (u, i) { var lk = uv.looks[u.no] || {}, c = u.empty ? '' : (lk.accent || u.tone || '#9A6BE0'); - return ''; + var e = window.JZP ? window.JZP.esc : function (x) { return String(x).replace(/[&<>"']/g, ''); }; + return ''; }).join(''); gate.style.setProperty('--n', all.length); gate.classList.add('scan'); diff --git a/portal/gallery.html b/portal/gallery.html index e8c5f23..2a1642a 100644 --- a/portal/gallery.html +++ b/portal/gallery.html @@ -10,7 +10,7 @@ - + @@ -50,15 +50,15 @@ try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: r - + - - - - + + + + diff --git a/portal/index.html b/portal/index.html index ffa0fc7..b856ef6 100644 --- a/portal/index.html +++ b/portal/index.html @@ -10,7 +10,7 @@ - + @@ -35,13 +35,13 @@ try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: r - + - - - + + + diff --git a/portal/links.html b/portal/links.html index 824c3b8..06e7562 100644 --- a/portal/links.html +++ b/portal/links.html @@ -10,7 +10,7 @@ - + @@ -25,13 +25,13 @@ try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: r - + - - - + + + diff --git a/portal/tools.html b/portal/tools.html index e717e62..2e63aa8 100644 --- a/portal/tools.html +++ b/portal/tools.html @@ -10,7 +10,7 @@ - + @@ -26,13 +26,13 @@ try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: r - + - - - + + + diff --git a/portal/universe.html b/portal/universe.html index 3d94c11..634c783 100644 --- a/portal/universe.html +++ b/portal/universe.html @@ -10,8 +10,8 @@ - - + + @@ -32,18 +32,18 @@ try{if(sessionStorage.getItem('jz-boot')||matchMedia('(prefers-reduced-motion: r - + - - - - - + + + + +