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
这个提交包含在:
Guoguo
2026-04-28 08:46:59 -07:00
父节点 543808b76e
当前提交 b80e872600
修改 42 个文件,包含 495 行新增1216 行删除
+20 -16
查看文件
@@ -7,6 +7,7 @@ Page({
scanProgress: 0,
regions: 0x7F,
regionData: [],
timeout: false,
error: ''
},
@@ -21,42 +22,45 @@ Page({
startScan: function () {
var self = this
self.setData({ scanning: true, scanProgress: 0 })
self.setData({ scanning: true, scanProgress: 0, timeout: false })
var progressTimer = setInterval(function () {
this._progressTimer = setInterval(function () {
var p = self.data.scanProgress + 2
if (p > 98) p = 98
self.setData({ scanProgress: p })
}, 100)
ble.on('status', function (status) {
this._onStatus = function (status) {
if (status.mode_state === 0x01) {
self.setData({ scanProgress: 50 })
} else if (status.mode_state === 0x04 || status.mode_state === 0x00) {
clearInterval(progressTimer)
clearInterval(self._progressTimer)
self.setData({ scanning: false, scanProgress: 100 })
if (status.region_mask) {
self.parseScanResults(status)
}
var names = ble.getRegionName(status.region_mask || 0x7F)
self.setData({ regionData: self.parseScanResults(names) })
}
})
}
ble.on('status', this._onStatus)
ble.queryStatus().catch(function () {})
setTimeout(function () {
clearInterval(progressTimer)
clearInterval(self._progressTimer)
if (!self.data.scanning) return
self.setData({ scanning: false, scanProgress: 100 })
self.parseScanResults({ region_mask: self.data.regions })
self.setData({ scanning: false, timeout: true })
wx.showToast({ title: '扫描超时,请重试', icon: 'none' })
}, 5000)
},
parseScanResults: function (status) {
var regions = ble.getRegionName(status.region_mask || 0x7F)
var data = regions.map(function (name) {
return { region: name, pd: (Math.random() * 0.3 + 0.3).toFixed(2) }
parseScanResults: function (regions) {
return regions.map(function (name) {
return { region: name, pd: '--' }
})
this.setData({ regionData: data })
},
onUnload: function () {
if (this._progressTimer) clearInterval(this._progressTimer)
if (this._onStatus) ble.off('status', this._onStatus)
},
onNext: function () {
+4 -2
查看文件
@@ -24,6 +24,7 @@ Page({
onUnload: function () {
clearTimeout(this._scanTimer)
ble.stopScan()
if (this._onBindResult) ble.off('bind_result', this._onBindResult)
},
startBleConnect: function () {
@@ -55,7 +56,7 @@ Page({
doBind: function () {
var self = this
var userId = app.globalData.userId || ''
ble.on('bind_result', function (result) {
this._onBindResult = function (result) {
if (result.success) {
http.post('/api/v1/device/bind/confirm', {
device_id: self.data.deviceId,
@@ -71,7 +72,8 @@ Page({
} else {
self.setData({ state: 'error', error: '设备绑定失败' })
}
})
}
ble.on('bind_result', this._onBindResult)
ble.bindDevice(userId, self.data.bindToken).catch(function (err) {
self.setData({ state: 'error', error: err.error_msg || '绑定命令失败' })
+7 -3
查看文件
@@ -6,6 +6,7 @@ Page({
records: [],
total: 0,
totalHours: 0,
totalMs: 0,
monthCount: 0,
page: 1,
pageSize: 20,
@@ -43,14 +44,14 @@ Page({
page: page,
page_size: self.data.pageSize
}).then(function (data) {
var totalMs = 0
var pageMs = 0
var now = new Date()
var monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
var monthCount = 0
var monthCount = refresh ? 0 : self.data.monthCount
var records = (data.records || []).map(function (r) {
var durationMin = Math.floor((r.total_duration_ms || 0) / 60000)
totalMs += (r.total_duration_ms || 0)
pageMs += (r.total_duration_ms || 0)
r.duration_text = durationMin + '分钟'
r.region_names = ble.getRegionName(r.regions || 0).join('、')
r.wavelength_name = ble.getWavelengthName(r.wavelength || 2)
@@ -62,9 +63,12 @@ Page({
return r
})
var totalMs = refresh ? pageMs : self.data.totalMs + pageMs
self.setData({
records: refresh ? records : self.data.records.concat(records),
total: data.total || 0,
totalMs: totalMs,
totalHours: Math.round(totalMs / 3600000),
monthCount: monthCount,
page: page,
+11 -3
查看文件
@@ -17,15 +17,23 @@ Page({
onShow: function () {
this.checkState()
ble.on('status', this.onBleStatus.bind(this))
this._onStatus = this.onBleStatus.bind(this)
ble.on('status', this._onStatus)
},
_cleanup: function () {
if (this._onStatus) {
ble.off('status', this._onStatus)
this._onStatus = null
}
},
onHide: function () {
ble.off('status')
this._cleanup()
},
onUnload: function () {
ble.off('status')
this._cleanup()
},
checkState: function () {
+6 -1
查看文件
@@ -38,7 +38,12 @@ Page({
if (!this.data.subscription || this.data.subscription.status === 0) {
wx.navigateTo({ url: '/pages/subscribe-plans/subscribe-plans' })
} else {
wx.navigateTo({ url: '/pages/subscribe-prompt/subscribe-prompt' })
var sub = this.data.subscription
wx.showModal({
title: '订阅信息',
content: '套餐类型:' + (sub.plan_type || '未知') + '\n剩余天数:' + (sub.remaining_days || 0) + '天',
showCancel: false
})
}
},
@@ -21,27 +21,10 @@ Page({
},
onPurchase: function () {
var self = this
if (!self.data.selected) {
wx.showToast({ title: '请选择套餐', icon: 'none' })
return
}
self.setData({ purchasing: true })
http.post('/api/v1/subscription/purchase', {
plan_type: self.data.selected,
payment_method: 'wechat'
}).then(function (data) {
return http.post('/api/v1/subscription/verify', {
order_id: data.order_id,
plan_type: self.data.selected
})
}).then(function () {
self.setData({ purchasing: false })
wx.redirectTo({ url: '/pages/subscribe-success/subscribe-success' })
}).catch(function () {
self.setData({ purchasing: false })
wx.showToast({ title: '购买失败', icon: 'none' })
wx.showModal({
title: '暂未开放',
content: '在线购买功能尚未开放,请联系管理员开通订阅。',
showCancel: false
})
}
})
@@ -5,15 +5,23 @@ Page({
expiryDate: ''
},
onLoad: function () {
onLoad: function (options) {
var app = getApp()
this.setData({ statusBarHeight: app.globalData.statusBarHeight })
var planMap = { yearly: '年卡会员', monthly: '月卡会员', trial: '试用会员' }
var durationMap = { yearly: 365, monthly: 30, trial: 7 }
var plan = options.plan || 'yearly'
var now = new Date()
now.setFullYear(now.getFullYear() + 1)
now.setDate(now.getDate() + (durationMap[plan] || 365))
var y = now.getFullYear()
var m = ('0' + (now.getMonth() + 1)).slice(-2)
var d = ('0' + now.getDate()).slice(-2)
this.setData({ expiryDate: y + '年' + m + '月' + d + '日' })
this.setData({
planName: planMap[plan] || '会员',
expiryDate: y + '年' + m + '月' + d + '日'
})
},
onStartSmart: function () {
+17 -12
查看文件
@@ -16,7 +16,6 @@ Page({
paused: false,
completed: false,
startedAt: 0,
localTimer: null
},
onLoad: function (options) {
@@ -31,18 +30,21 @@ Page({
startedAt: Date.now()
})
ble.on('status', this.onStatus.bind(this))
ble.on('treatment_complete', this.onComplete.bind(this))
ble.on('exception', this.onException.bind(this))
this._onStatus = this.onStatus.bind(this)
this._onComplete = this.onComplete.bind(this)
this._onException = this.onException.bind(this)
ble.on('status', this._onStatus)
ble.on('treatment_complete', this._onComplete)
ble.on('exception', this._onException)
this.startLocalTimer()
this.syncCommands()
},
onUnload: function () {
ble.off('status')
ble.off('treatment_complete')
ble.off('exception')
if (this.data.localTimer) clearInterval(this.data.localTimer)
if (this._onStatus) ble.off('status', this._onStatus)
if (this._onComplete) ble.off('treatment_complete', this._onComplete)
if (this._onException) ble.off('exception', this._onException)
if (this._localTimer) clearInterval(this._localTimer)
},
startLocalTimer: function () {
@@ -57,7 +59,7 @@ Page({
self.finishAsComplete()
}
}, 1000)
this.setData({ localTimer: timer })
this._localTimer = timer
},
updateProgress: function (remaining) {
@@ -95,12 +97,14 @@ Page({
var app = getApp()
app.globalData.currentTreatment = result
var self = this
setTimeout(function () {
wx.redirectTo({
url: '/pages/treatment-done/treatment-done?session_id=' + result.session_id +
'&regions=' + result.regions +
'&duration=' + result.total_duration_ms +
'&avg_pd=' + result.avg_pd
'&avg_pd=' + result.avg_pd +
'&mode=' + (self.data.mode || 0)
})
}, 1000)
},
@@ -108,10 +112,11 @@ Page({
finishAsComplete: function () {
var elapsed = Math.min(this.data.duration, Date.now() - this.data.startedAt)
this.onComplete({
session_id: 'SESS' + Date.now(),
session_id: 'LOCAL_' + Date.now(),
regions: this.data.regions,
total_duration_ms: elapsed,
avg_pd: 0
avg_pd: 0,
source: 'client_timer'
})
},
@@ -9,6 +9,7 @@ Page({
regions: 0,
duration: 0,
avgPd: 0,
mode: 0,
durationText: '',
regionNames: [],
syncing: false,
@@ -34,6 +35,7 @@ Page({
duration: durationMs,
avgPd: options.avg_pd || 0,
durationText: durationText,
mode: parseInt(options.mode) || 0,
regionNames: ble.getRegionName(parseInt(options.regions) || 0)
})
@@ -42,6 +44,7 @@ Page({
syncRecord: function () {
var self = this
var treatment = (app.globalData.currentTreatment) || {}
self.setData({ syncing: true })
http.post('/api/v1/treatment/sync', {
@@ -51,8 +54,9 @@ Page({
end_time: new Date().toISOString(),
regions: self.data.regions,
total_duration_ms: self.data.duration,
mode: 0,
avg_pd: self.data.avgPd
mode: self.data.mode,
avg_pd: self.data.avgPd,
source: treatment.source || 'device'
}).then(function () {
self.setData({ syncing: false, synced: true })
}).catch(function () {
@@ -29,7 +29,7 @@ Page({
var self = this
http.get('/api/v1/subscription').then(function (sub) {
self.setData({
subExpired: sub.status !== 'active',
subExpired: sub.status !== 1,
subDays: sub.remaining_days || 0
})
}).catch(function () {})
+8 -2
查看文件
@@ -21,20 +21,26 @@ Page({
var self = this
self.setData({ checking: true, result: null, error: '' })
ble.on('status', function (status) {
if (this._onStatus) ble.off('status', this._onStatus)
this._onStatus = function (status) {
self.setData({ checking: false })
if (status.bind_status === 1) {
self.setData({ result: 'ok' })
} else {
self.setData({ result: 'fail', error: '请确认设备已正确佩戴' })
}
})
}
ble.on('status', this._onStatus)
ble.queryStatus().catch(function (err) {
self.setData({ checking: false, result: 'fail', error: err.error_msg || '查询失败' })
})
},
onUnload: function () {
if (this._onStatus) ble.off('status', this._onStatus)
},
onNext: function () {
wx.navigateTo({ url: '/pages/treatment-setup/treatment-setup' })
},