提交图
39 次代码提交
作者 SHA1 备注 提交日期
Guoguo c21a0912c6 fix: auto-cleanup stale payment orders and expired pending bindings
- closeStaleOrders: marks payment orders older than 24h as 'closed'
- closeExpiredPending: marks expired binding requests (bind_status=3) as cancelled
- Both run on app startup (SCF cold start), no cron needed
- countPendingByUser already filters to 2h window (previous commit)
2026-05-18 03:52:03 -07:00
Guoguo 343eeca89a fix: pending order count only includes orders created within 2 hours 2026-05-18 03:49:11 -07:00
Guoguo 05e990eda5 fix: payment security hardening — 3 CRITICAL + 3 HIGH
CRITICAL fixes:
- C1: Notify amount validation now unconditional (was skippable if amount field missing)
- C2: Sync endpoint validates payer_total against order amount before activation
- C3: Order ID uses crypto.randomBytes(6) instead of Math.random (collision-safe)

HIGH fixes:
- H1: Payment endpoints rate limited to 5/min per IP
- H2: Max 5 pending orders per user, reject new ones until completed/cancelled
- H3: Purchase endpoint returns error (not mock) when wxpay unconfigured in production

Also fixed:
- Notify handler asserts Buffer body, rejects non-Buffer (L3)
- Notify error response is generic, no internal message leak (M1)
- Private key cached in memory after first read (L2)
- Fixed duplicate paymentOrderDao const declaration
2026-05-18 03:45:57 -07:00
Guoguo 0ef359b563 fix: add WECHAT_APPID to production guard 2026-05-18 03:18:45 -07:00
Guoguo 731122064b fix: 5 critical payment issues from code review
1. Move notify route before authMiddleware (WeChat callback has no JWT)
2. Add await to verifyNotifySignature call (was fire-and-forget)
3. Remove dangerous verify fallback — all signature failures now throw
4. Payment sync polls 3x before giving up, never redirects to success
   page unless confirmed paid
5. Production guard enforces all WX_MCH_* env vars on startup
2026-05-18 03:16:44 -07:00
Guoguo e9681cdd21 fix: implement real notify signature verification + replay protection
- Fetch and cache WeChat platform certificates via /v3/certificates
- Verify notification RSA-SHA256 signature against platform cert
- Reject notifications with timestamp older than 5 minutes (anti-replay)
- Split decryptResource (raw string) from decryptNotifyResource (JSON)
  so platform cert PEM decryption works correctly
2026-05-18 03:11:33 -07:00
Guoguo 78ea1a03c5 feat: WeChat Pay V3 integration (fill credentials to activate)
Server:
- New lib/wxpay.js: native crypto RSA-SHA256 signing, JSAPI prepay,
  AES-256-GCM notify decryption, order query (no npm deps)
- New dao/payment-order.dao.js: createOrder, markPrepay,
  markPaidAndActivateSubscription (idempotent + transactional)
- New routes/payment.js: GET order status, POST order sync
- New routes/payment-notify.js: WeChat async callback handler with
  signature verification, amount/appid/mchid validation
- Modified subscription/purchase: auto-detects wxpay config, returns
  real payment_params or mock fallback
- Schema: payment_orders table with out_trade_no unique key
- app.js: express.raw() for notify path, payment routes mounted
- config.js: wxpay block with 7 env vars
- .env.example: all WeChat Pay fields documented
- .gitignore: certs/, *.pem, *.p12

Miniprogram:
- subscribe-plans doPurchase: calls real purchase API, falls back to
  mockPurchase only when server returns mock:true
- Added syncAndRedirect for post-payment order confirmation
- api.js: getPaymentOrder, syncPaymentOrder
- Removed "模拟支付"/"测试环境" from UI text
2026-05-18 03:07:59 -07:00
Guoguo 92416261ee feat: production readiness — feature gaps + config hardening
Miniprogram:
- Add BLE reconnect button on home page when disconnected
- Add loading states to index, profile, subscribe-plans pages
- Add profile editing (avatar + nickname) with COS upload
- Enable pull-to-refresh on history page
- Fix auto-scan self.options → self.data inconsistency
- Add console.error to silent catch blocks
- Gate 'Simple Peripheral' BLE scan behind __DEV__ flag
- Add production config comment to env.js

Admin console:
- Add empty state '暂无数据' to all 5 list views
- Replace plain text plan input with select dropdown
- Add type="date" to record date filters
- Add production config comment

Server:
- CORS origin restricted in production (env CORS_ORIGIN)
- DB pool size configurable via DB_POOL_SIZE env var
- .env.example updated with WeChat Pay + production fields
2026-05-15 09:07:41 -07:00
Guoguo 624f52f4cc fix: admin records filter by user_id instead of keyword search
- RecordView passes user_id as separate filter param, not as keyword
- Admin records endpoint forwards user_id to DAO
- treatmentDao.listAdmin supports exact user_id match filter
- Added visible filter tag with clear button in RecordView
2026-05-11 07:15:40 -07:00
Guoguo 0c65ef95f8 fix: cross-audit fixes — file validation, type safety, dedup
- Avatar upload: whitelist image MIME types and extensions (jpg/png/gif/webp)
- Normalize device_id to String for strict comparison in treatment sync
- Add ORDER BY expire_time DESC to purchase/adminCreate subscription queries
- Deduplicate readBearer: middleware imports from lib/auth.js
- Parameterize createTrial INTERVAL instead of string concatenation
- Add rate limiting (20/15min) to avatar upload and phone auth endpoints
2026-05-11 06:22:24 -07:00
Guoguo 583fcb7e3d feat: add user deactivation and vendor BLE protocol 2026-05-11 21:14:41 +08:00
Guoguo c95d47e0c1 fix: audit fixes — treatment sync, avatar upload, code consistency
- Always sync treatment end (not just early stop), pass start/end times
- treatment-done uses api.syncTreatment instead of raw http.post
- Move getApp() from module level to onLoad in treatment-done
- Avatar upload only returns URL, no longer updates profile directly
- COS CDN domain configurable via COS_CDN_DOMAIN env var
- Fix operator precedence in request.js token expiry check
- Remove unused result variable from COS putObject
2026-05-07 06:36:28 -07:00
Guoguo 06b6ee6b02 fix: avatar picker uses chooseMedia, COS domain to tx.vsai.net.cn
- Replace chooseAvatar button with chooseMedia (more reliable, works on all versions)
- COS avatar URL uses tx.vsai.net.cn instead of generated bucket domain
- Phone shows '已授权' only (no actual number displayed)
2026-05-07 06:23:42 -07:00
Guoguo 9019573662 fix: serverless adapter binary body support, hide phone number in register
- Keep body as Buffer instead of utf8 string for multipart/form-data
- Set content-length header for multer compatibility
- Phone authorization shows '已授权' instead of actual number
2026-05-07 05:58:41 -07:00
Guoguo 52456d850e fix: audit fixes for registration flow
- loadProfile() now returns Promise (was missing return)
- Avatar upload via COS instead of storing WeChat temp path
- Add POST /user/avatar endpoint with multer + COS SDK
- Incomplete registration detection: redirect to register if phone is empty
2026-05-06 06:18:21 -07:00
Guoguo 563e515bce feat: add registration page for new miniprogram users
- New register page with chooseAvatar, nickname input (random default),
  and required phone number authorization via getPhoneNumber
- Login simplified: removed deprecated wx.getUserProfile, checks
  is_new_user flag to redirect new users to registration
- Server login response now includes is_new_user field
2026-05-06 06:12:34 -07:00
Guoguo 2eb38195f1 fix: address critical security and data integrity issues from cross-audit
- Add expire_time > NOW() filter to findActive() preventing stale subscriptions
- Add express-rate-limit on login endpoints (user: 10/15min, admin: 5/15min)
- Add production guard for default admin credentials
- Fix BLE bindDevice userId encoding (uint32 instead of hexToBytes on numeric)
- Wrap adminCreate in transaction to prevent race condition
- Add settings cache invalidation after admin saves
- Read trial_days from settings instead of hardcoding 7
- Fix double JSON.stringify in commandDao.finish call
- Cancel stale pending bindings before creating new ones
- Reduce token refresh grace period from 3 days to 1 day
- Fix subscribe-success to fetch expiry from server (correct for renewals)
- Add keep-alive name property to DashboardView and SettingsView
- Fix BLE disconnect() to preserve listener registrations across reconnects
2026-05-05 02:33:25 -07:00
Guoguo 031678c03f feat: complete feature gaps across all modules
Server:
- Add settings-cache with 60s TTL for feature toggle checks
- Enforce maintenance_mode on login, enable_binding on device bind

Admin console:
- Remove dead "发送通知" button from user detail
- Firmware check calls real API and compares versions

Miniprogram:
- Wear-check: dynamic battery/connected from BLE state
- Login: hide non-functional phone auth button
- Treating: show actual selected regions instead of hardcoded "全脸"
- Index: display subscription status with tap to manage
- Auto-scan: show "待检测" instead of "--" for PD data
- Agreements: tap shows "内容建设中" modal
2026-05-02 08:48:26 -07:00
Guoguo 1017fb5dae fix: subscription extend instead of overwrite, improve placeholder pages
- Subscription purchase now extends expire_time when user has active
  subscription, instead of cancelling and replacing
- Admin subscription creation uses same extend logic
- Subscribe page shows "续费" button and extend message for renewals
- Help and contact pages: add pink header, centered icon + text
2026-04-29 08:35:58 -07:00
Guoguo 9bdccdcec8 chore: remove duplicate logDao require in subscription route 2026-04-29 08:24:15 -07:00
Guoguo 66cc846da1 fix: mock purchase now actually activates subscription
POST /api/v1/subscription/purchase only creates an order without
activating. Add POST /api/v1/subscription/mock-purchase that does
purchase + verify in one step (non-production only). Miniprogram
subscribe page now calls mock-purchase so subscriptions take effect.
2026-04-29 08:22:08 -07:00
Guoguo 17f5366c23 feat: show trial plan with used/disabled state on subscribe page
- Add GET /api/v1/subscription/plans public endpoint for pricing
- Subscription API now returns trial_used field
- Subscribe-plans page shows trial card, greyed out with "已使用" tag
  when trial has been used
- Trial activation calls dedicated trial API, not purchase
- Prices fetched from server settings, fallback to defaults
2026-04-29 08:15:27 -07:00
Guoguo e8f076c914 feat: fetch subscription prices from server settings
- Add GET /api/v1/subscription/plans public endpoint (no auth needed)
  that reads prices from system_settings table
- Subscribe-plans page now loads prices from server on show
- Falls back to hardcoded defaults if API fails
- Add api.getPlans() to miniprogram API module
2026-04-29 08:07:47 -07:00
Guoguo 52fb7799a3 fix: default NODE_ENV to development for testing phase 2026-04-29 06:11:43 -07:00
Guoguo 62a63f9c9b fix: resolve final audit issues
- firmware route: extract insertId from ResultSetHeader correctly
- admin device detail: add null check and flatten response to match
  frontend's expected field structure
- device command result: add ownership verification before finishing
  command (security fix)
2026-04-29 06:02:18 -07:00
Guoguo bb4b80f867 refactor: restructure entire project for human maintainability
Server:
- Add Express framework, replace custom router/request parser
- Create DAO layer (12 files) centralizing all 73 SQL queries
- Rewrite 7 route files as thin Express controllers calling DAOs
- Add SCF-to-Express adapter (lib/serverless.js)
- Add auth middleware (middleware/auth.js)
- Remove dead code from lib/auth.js

Admin console:
- Extract DataTable component (table + pagination)
- Extract ConfirmModal component (modal + form styles)
- Create listMixin for paginated list pages
- Move form styles to common.css for slot compatibility
- Refactor device + subscription pages as examples

Miniprogram:
- Split 734-line BLE monolith into 4 focused modules
  (protocol, connection, commands, barrel index)
- Create API module (utils/api.js) with named functions
- Create page utilities (utils/page.js)
- Refactor index + profile pages to use API module
2026-04-29 05:58:20 -07:00
Guoguo 9f0e629c82 fix: resolve quality audit issues
- utils.js: force UTC+8 output to match MySQL timezone on SCF
- admin subscriptions: return stats (plan counts + revenue) in response
- admin devices: implement keyword search filter
- device-detail: fix binding history field names (bind_time/unbind_time/bind_status)
- user-detail: fix treatment time field (start_time not started_at)
- dashboard: show actual mode per treatment, use sub_stats from dashboard API
2026-04-29 05:37:36 -07:00
Guoguo 8d1cde8636 fix: resolve 8 bugs and add admin features
Miniprogram:
- Profile "我的设备": show unbind option when device bound, scan when not
- Add device status indicator (已绑定/未绑定) to profile menu

Admin console:
- Login: add @confirm to inputs so Enter key submits the form
- Record detail: wire up 详情 link with modal showing full record info
- Dashboard: add subscription stats row (月卡/年卡/试用/收入)
- Subscription: add 取消 action for active subscriptions
- Format: fix -8h timezone display for UTC ISO date strings

Server:
- POST /api/v1/admin/subscriptions/cancel: cancel active subscriptions
- Dashboard API: include sub_stats (plan counts + monthly revenue)
- IP extraction: add X-Forwarded-For fallback for logging
2026-04-29 05:33:12 -07:00
Guoguo 775112130d feat: add mock-bind endpoint to bypass token flow for testing
The bind + confirm two-step flow has timezone issues between Node.js
(UTC on SCF) and MySQL (timezone +08:00) that cause bind_token to
fail validation. Add POST /api/v1/device/mock-bind that does bind +
confirm in one atomic step, skipping the token entirely. Only
available when NODE_ENV != production.

Update ble-connect and index page mock buttons to use mock-bind.
2026-04-29 05:10:12 -07:00
Guoguo 3e8cd8764a fix: use MySQL DATE_ADD instead of JS dates for bind token expiry
SCF runs in UTC but MySQL connection uses timezone +08:00, causing
bind_expires computed in JS to mismatch NOW() in SQL queries.
Use DATE_ADD(NOW(), INTERVAL ...) directly in SQL to guarantee
consistent timezone for both storage and comparison.
2026-04-29 04:57:31 -07:00
Guoguo 2578c06a74 fix: back button alignment, mock bind flow, and timezone bug
- nav-back: add text-align:left to override page-header's center
- ble-connect mock: call bind API first to get fresh token before
  confirm, instead of relying on potentially stale URL params
- utils.js: use local time instead of UTC for toMysqlDate, fixing
  timezone mismatch with MySQL NOW() that caused bind tokens to
  appear immediately expired
2026-04-29 04:54:42 -07:00
Guoguo 1f55e430c8 feat: add password change, trial subscription, batch import, UX improvements
Server:
- POST /api/v1/admin/password: admin password change with bcrypt migration
- POST /api/v1/subscription/trial: user trial activation, one per user
- POST /api/v1/admin/devices/batch: bulk device import (up to 500)
- Add trial plan (7 days, free) to PLANS constant

Admin console:
- Settings page: add password change form with validation
- Device page: add batch import modal with textarea input

Miniprogram:
- Treating page: add back button with stop-treatment confirmation
- Index page: add mock device bind button (dev mode only)
2026-04-28 19:42:23 -07:00
Guoguo 4ec42e7816 fix: resolve password migration crash and schema constraints
- Login bcrypt migration: write password_salt = '' instead of NULL,
  which violated the NOT NULL constraint and caused 500 errors
- Schema: widen password_hash from CHAR(64) to VARCHAR(100) for bcrypt
  compatibility, add DEFAULT '' to password_salt
- init-db: add ALTER TABLE migrations for existing databases
- app.js: enrich error logging with method, path, SQL error details
2026-04-28 19:14:13 -07:00
Guoguo 4b6e577dfb fix: correct init-db hashPassword call for bcrypt migration
hashPassword now uses bcrypt (single arg), not SHA-256 (password+salt).
The old call silently ignored the salt param but was misleading.
2026-04-28 19:06:11 -07:00
Guoguo 6201b97fcd fix: resolve critical audit issues across all modules
Server: add filter/search/pagination to admin list endpoints, enrich
user/device queries with JOINs and subqueries, prevent duplicate active
subscriptions on creation.

Admin console: fix record page TypeError on numeric record_id, correct
mode comparison (integer vs string), fix device detail field names and
command opcode, remove hardcoded login credentials, wire up dead buttons
(unbind, view logs, export), fix user/subscription field mappings.

Miniprogram: fix subscription status string/number mismatches across
index/treatment-setup/profile pages, fix device name field reference,
fix treatment-done null device_id by capturing at onLoad.
2026-04-28 18:46:03 -07:00
Guoguo 91d5937d8e feat: implement P0 security and reliability improvements
- bcrypt password hashing with auto-migration from SHA-256
- BLE command retry (3 attempts, 500ms delay, skip on disconnect)
- BLE auto-reconnect with service re-discovery on disconnect
- Treatment page disconnect/reconnect event handling
- Token refresh endpoint with 3-day grace period
- Client-side token auto-refresh when <24h remaining
- Single treatment record detail API with ownership check
2026-04-28 18:12:30 -07:00
Guoguo b80e872600 fix: comprehensive security, quality and consistency fixes
Server:
- Block startup with default JWT secrets in production
- Make subscription verify admin-only (no payment integration yet)
- Add device ownership validation on command/result, event, treatment/sync
- Remove admin token from request body fallback
- Add pageParams boundary protection (pageSize capped at 100)
- Fix COS getObjectUrl to use callback-based Promise
- Add settings key whitelist matching frontend fields
- Add user existence check before subscription creation
- Fix firmware always returning has_update:true
- Replace hardcoded trial subscription with actual DB query
- Extract shared utilities (limitClause, toMysqlDate, formatDate)

Miniprogram:
- Replace fake PD random data with placeholder
- Mark client-timer treatment completions with source field
- Disable mock.js
- Fix BLE listener leaks (save refs, cleanup in onUnload)
- Fix ble.off clearing all listeners (pass specific callback)
- Add BLE disconnect detection via onBLEConnectionStateChange
- Fix subscription status type consistency (number not string)
- Fix scan callback accumulation in ble.js
- Fix history stats accumulation across pages
- Fix subscribe-success/treatment-done hardcoded values
- Fix profile subscription view logic
- Replace purchase flow with admin-contact modal
- Add error logging in command-sync report

Admin console:
- Fix AdminLayout logout (require->import, logout->clearToken)
- Remove all mock data from production request.js
- Replace dashboard fake data with real API calls
- Replace monthly_revenue with subscription_count
- Fix subscription stats fallback (|| -> ??)
- Add token expiry tracking (7 days)
- Unify device status map and subscription status text
- Fix user page record link navigation
- Fix subscription createForm.user_id type handling
- Add error feedback in all empty catch blocks
- Remove unused remember checkbox and uview-plus dependency
- Extract common CSS to shared stylesheet (-900 lines)
- Extract formatDate to shared utils/format.js
- Show real admin name in layout header
2026-04-28 08:46:59 -07:00
Guoguo a1b189483f fix: use WeChat profile authorization login 2026-04-28 23:00:13 +08:00
Guoguo 444c91c0b0 refactor: migrate to Tencent Cloud backend 2026-04-28 22:56:47 +08:00