功能:收口小程序前后台安全与防重复提交

This commit is contained in:
xiaowang
2026-04-20 16:02:57 +08:00
parent eb1c209d79
commit a3df262fae
237 changed files with 14068 additions and 728 deletions
+78
View File
@@ -0,0 +1,78 @@
const inflightScopes = new Map()
function resolveScopeId(scope) {
if (scope && typeof scope === 'string') {
return scope
}
if (scope && typeof scope.route === 'string' && scope.route) {
return scope.route
}
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const current = pages[pages.length - 1]
if (current && current.route) {
return current.route
}
return 'global'
}
function getScopeMap(scopeId) {
if (!inflightScopes.has(scopeId)) {
inflightScopes.set(scopeId, new Map())
}
return inflightScopes.get(scopeId)
}
function createGuardError(message, scopeId, actionKey) {
const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb')
error.isActionGuardError = true
error.scopeId = scopeId
error.actionKey = actionKey
return error
}
async function run(scope, actionKey, task, options) {
const scopeId = resolveScopeId(scope)
const normalizedKey = String(actionKey || 'default')
const scopeMap = getScopeMap(scopeId)
if (scopeMap.get(normalizedKey)) {
return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey))
}
scopeMap.set(normalizedKey, true)
try {
return await Promise.resolve().then(() => task())
} finally {
scopeMap.delete(normalizedKey)
if (!scopeMap.size) {
inflightScopes.delete(scopeId)
}
}
}
function isRunning(scope, actionKey) {
const scopeId = resolveScopeId(scope)
const scopeMap = inflightScopes.get(scopeId)
if (!scopeMap) {
return false
}
return Boolean(scopeMap.get(String(actionKey || 'default')))
}
function clearScope(scope) {
inflightScopes.delete(resolveScopeId(scope))
}
function isGuardError(error) {
return Boolean(error && error.isActionGuardError)
}
module.exports = {
run,
isRunning,
clearScope,
isGuardError,
createGuardError
}
+66 -4
View File
@@ -1,4 +1,61 @@
const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage')
const SIGNED_URL_SAFE_BUFFER_MS = 60 * 1000
function parseSignedUrlExpireAt(url) {
const rawUrl = String(url || '').trim()
if (!rawUrl || rawUrl.indexOf('?') < 0) {
return 0
}
const queryString = rawUrl.slice(rawUrl.indexOf('?') + 1)
const params = {}
queryString.split('&').forEach(segment => {
if (!segment) {
return
}
const dividerIndex = segment.indexOf('=')
const key = dividerIndex >= 0 ? segment.slice(0, dividerIndex) : segment
const value = dividerIndex >= 0 ? segment.slice(dividerIndex + 1) : ''
params[decodeURIComponent(key)] = decodeURIComponent(value)
})
const awsDate = params['X-Amz-Date']
const awsExpireSeconds = Number(params['X-Amz-Expires'] || 0)
if (awsDate && awsExpireSeconds > 0 && awsDate.length >= 16) {
const year = Number(awsDate.slice(0, 4))
const month = Number(awsDate.slice(4, 6)) - 1
const day = Number(awsDate.slice(6, 8))
const hour = Number(awsDate.slice(9, 11))
const minute = Number(awsDate.slice(11, 13))
const second = Number(awsDate.slice(13, 15))
const baseTimestamp = Date.UTC(year, month, day, hour, minute, second)
if (!Number.isNaN(baseTimestamp)) {
return baseTimestamp + awsExpireSeconds * 1000
}
}
const expires = Number(params.Expires || 0)
if (expires > 0) {
return expires * 1000
}
return 0
}
function sanitizeStoredUserInfo(userInfo) {
if (!userInfo || typeof userInfo !== 'object') {
return userInfo
}
const nextUserInfo = {
...userInfo
}
const avatarExpireAt = parseSignedUrlExpireAt(nextUserInfo.avatar)
if (avatarExpireAt > 0 && avatarExpireAt <= Date.now() + SIGNED_URL_SAFE_BUFFER_MS) {
nextUserInfo.avatar = ''
}
return nextUserInfo
}
function getAccessToken() {
return getStorage(STORAGE_KEYS.ACCESS_TOKEN, '')
@@ -9,7 +66,11 @@ function getRefreshToken() {
}
function getStoredUserInfo() {
return getStorage(STORAGE_KEYS.USER_INFO, null)
const userInfo = sanitizeStoredUserInfo(getStorage(STORAGE_KEYS.USER_INFO, null))
if (userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
}
return userInfo
}
function getNeedSetPassword() {
@@ -33,7 +94,7 @@ function setSession(payload) {
setStorage(STORAGE_KEYS.REFRESH_TOKEN, payload.refreshToken)
if (payload.userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, payload.userInfo)
setStorage(STORAGE_KEYS.USER_INFO, sanitizeStoredUserInfo(payload.userInfo))
}
if (payload.needSetPassword) {
@@ -49,7 +110,7 @@ function updateStoredUserInfo(userInfo) {
return
}
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
setStorage(STORAGE_KEYS.USER_INFO, sanitizeStoredUserInfo(userInfo))
}
function setNeedSetPassword(value) {
@@ -88,5 +149,6 @@ module.exports = {
updateStoredUserInfo,
setNeedSetPassword,
setPreferredMiniLoginShopId,
clearSession
clearSession,
sanitizeStoredUserInfo
}
+108
View File
@@ -0,0 +1,108 @@
const CACHE_PREFIX = 'miniCache:'
const memoryCache = {}
const inflightCache = {}
function now() {
return Date.now()
}
function buildKey(key) {
return `${CACHE_PREFIX}${key}`
}
function clearExpiredEntry(key, entry) {
if (!entry) {
return
}
if (entry.expireAt && entry.expireAt <= now()) {
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
}
function getCache(key, defaultValue) {
if (!key) {
return defaultValue
}
const localEntry = memoryCache[key]
if (localEntry && (!localEntry.expireAt || localEntry.expireAt > now())) {
return localEntry.value
}
clearExpiredEntry(key, localEntry)
try {
const storedEntry = wx.getStorageSync(buildKey(key))
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
memoryCache[key] = storedEntry
return storedEntry.value
}
clearExpiredEntry(key, storedEntry)
} catch (error) {}
return defaultValue
}
function setCache(key, value, ttlMs) {
if (!key) {
return value
}
const expireAt = ttlMs && ttlMs > 0 ? now() + ttlMs : 0
const entry = {
value,
expireAt
}
memoryCache[key] = entry
try {
wx.setStorageSync(buildKey(key), entry)
} catch (error) {}
return value
}
function removeCache(key) {
if (!key) {
return
}
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
function removeByPrefix(prefix) {
Object.keys(memoryCache).forEach(key => {
if (key.startsWith(prefix)) {
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
})
}
function remember(key, ttlMs, loader) {
const cached = getCache(key, undefined)
if (cached !== undefined) {
return Promise.resolve(cached)
}
if (inflightCache[key]) {
return inflightCache[key]
}
inflightCache[key] = Promise.resolve()
.then(() => loader())
.then(value => setCache(key, value, ttlMs))
.finally(() => {
delete inflightCache[key]
})
return inflightCache[key]
}
module.exports = {
getCache,
setCache,
removeCache,
removeByPrefix,
remember
}
+60 -6
View File
@@ -1,3 +1,11 @@
function safeRequire(modulePath) {
try {
return require(modulePath)
} catch (error) {
return {}
}
}
function getEnvVersion() {
if (typeof wx === 'undefined') {
return 'develop'
@@ -48,24 +56,70 @@ function getRuntimePlatform() {
return 'unknown'
}
function normalizeDomain(value, fallbackValue) {
const target = String(value || fallbackValue || '').trim()
if (!target) {
return ''
}
return target.replace(/\/+$/, '')
}
function ensureHttps(value, envVersion) {
if (!value) {
throw new Error(`Missing API domain for ${envVersion}`)
}
if (envVersion !== 'develop' && !value.startsWith('https://')) {
throw new Error(`${envVersion} environment must use HTTPS`)
}
return value
}
const localOverride = safeRequire('./config.local')
const ENV_VERSION = getEnvVersion()
const RUNTIME_PLATFORM = getRuntimePlatform()
const IS_DEVTOOLS = RUNTIME_PLATFORM === 'devtools'
const LOCAL_API_DOMAIN = 'http://127.0.0.1:80'
const REMOTE_API_DOMAIN = 'https://yunail.art'
const USE_LOCAL_API = ENV_VERSION === 'develop' && IS_DEVTOOLS
const API_DOMAIN = USE_LOCAL_API ? LOCAL_API_DOMAIN : REMOTE_API_DOMAIN
const DEFAULT_DOMAINS = {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
const DOMAIN_MAP = {
...DEFAULT_DOMAINS,
...(localOverride.domains || {})
}
const DEFAULT_DEVELOP_TARGET = IS_DEVTOOLS ? 'local' : 'dev-remote'
const DEVELOP_TARGET = String(localOverride.developTarget || DEFAULT_DEVELOP_TARGET)
const API_DOMAIN = ensureHttps(
ENV_VERSION === 'develop'
? normalizeDomain(DOMAIN_MAP[DEVELOP_TARGET], DOMAIN_MAP['dev-remote'])
: normalizeDomain(DOMAIN_MAP[ENV_VERSION], DOMAIN_MAP.release),
ENV_VERSION
)
module.exports = {
ENV_VERSION,
RUNTIME_PLATFORM,
IS_DEVTOOLS,
USE_LOCAL_API,
DEVELOP_TARGET,
API_DOMAIN,
API_BASE_URL: `${API_DOMAIN}/api`,
IS_DEV_ENV: ENV_VERSION === 'develop',
REQUEST_TIMEOUT: 10000,
REQUEST_TIMEOUT: Number(localOverride.requestTimeout || 10000),
ENABLE_REQUEST_SIGNING: localOverride.enableRequestSigning !== false,
IDLE_TIMEOUT_MS: 60 * 60 * 1000,
IDLE_WARNING_MS: 2 * 60 * 1000,
CACHE_TTL: {
banner: 5 * 60 * 1000,
publicShops: 5 * 60 * 1000,
tags: 10 * 60 * 1000,
homeList: 2 * 60 * 1000,
signedUrl: 50 * 60 * 1000
},
DEFAULT_AVATAR: 'https://api.dicebear.com/7.x/avataaars/svg?seed=default',
DEFAULT_PRODUCT_IMAGE: 'https://via.placeholder.com/200x200?text=Product',
DEFAULT_SHOP_IMAGE: 'https://via.placeholder.com/200x200?text=Shop',
@@ -0,0 +1,12 @@
module.exports = {
developTarget: 'local',
requestTimeout: 10000,
enableRequestSigning: true,
domains: {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
}
+177
View File
@@ -0,0 +1,177 @@
function utf8ToBytes(text) {
const encoded = unescape(encodeURIComponent(String(text || '')))
const bytes = []
for (let index = 0; index < encoded.length; index += 1) {
bytes.push(encoded.charCodeAt(index))
}
return bytes
}
function bytesToHex(bytes) {
return (Array.isArray(bytes) ? bytes : []).map(item => item.toString(16).padStart(2, '0')).join('')
}
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount))
}
function sha256Bytes(messageBytes) {
const k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
const h = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]
const bytes = Array.isArray(messageBytes) ? messageBytes.slice() : []
const bitLength = BigInt(bytes.length) * 8n
bytes.push(0x80)
while ((bytes.length % 64) !== 56) {
bytes.push(0)
}
for (let index = 7; index >= 0; index -= 1) {
bytes.push(Number((bitLength >> BigInt(index * 8)) & 0xffn))
}
const words = new Array(64)
for (let offset = 0; offset < bytes.length; offset += 64) {
for (let index = 0; index < 16; index += 1) {
const start = offset + index * 4
words[index] = (
(bytes[start] << 24) |
(bytes[start + 1] << 16) |
(bytes[start + 2] << 8) |
bytes[start + 3]
) >>> 0
}
for (let index = 16; index < 64; index += 1) {
const s0 = (rightRotate(words[index - 15], 7) ^ rightRotate(words[index - 15], 18) ^ (words[index - 15] >>> 3)) >>> 0
const s1 = (rightRotate(words[index - 2], 17) ^ rightRotate(words[index - 2], 19) ^ (words[index - 2] >>> 10)) >>> 0
words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0
}
let a = h[0]
let b = h[1]
let c = h[2]
let d = h[3]
let e = h[4]
let f = h[5]
let g = h[6]
let innerH = h[7]
for (let index = 0; index < 64; index += 1) {
const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0
const choice = ((e & f) ^ ((~e) & g)) >>> 0
const temp1 = (innerH + s1 + choice + k[index] + words[index]) >>> 0
const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0
const majority = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
const temp2 = (s0 + majority) >>> 0
innerH = g
g = f
f = e
e = (d + temp1) >>> 0
d = c
c = b
b = a
a = (temp1 + temp2) >>> 0
}
h[0] = (h[0] + a) >>> 0
h[1] = (h[1] + b) >>> 0
h[2] = (h[2] + c) >>> 0
h[3] = (h[3] + d) >>> 0
h[4] = (h[4] + e) >>> 0
h[5] = (h[5] + f) >>> 0
h[6] = (h[6] + g) >>> 0
h[7] = (h[7] + innerH) >>> 0
}
const output = []
h.forEach(value => {
output.push((value >>> 24) & 0xff)
output.push((value >>> 16) & 0xff)
output.push((value >>> 8) & 0xff)
output.push(value & 0xff)
})
return output
}
function sha256Hex(text) {
return bytesToHex(sha256Bytes(utf8ToBytes(text)))
}
function hmacSha256Hex(secret, message) {
let keyBytes = utf8ToBytes(secret)
if (keyBytes.length > 64) {
keyBytes = sha256Bytes(keyBytes)
}
while (keyBytes.length < 64) {
keyBytes.push(0)
}
const outer = []
const inner = []
for (let index = 0; index < 64; index += 1) {
outer[index] = keyBytes[index] ^ 0x5c
inner[index] = keyBytes[index] ^ 0x36
}
const innerDigest = sha256Bytes(inner.concat(utf8ToBytes(message)))
return bytesToHex(sha256Bytes(outer.concat(innerDigest)))
}
function buildCanonicalParams(input) {
const source = input || {}
const keys = Object.keys(source)
.filter(key => source[key] !== undefined && source[key] !== null && source[key] !== '')
.sort()
return keys.map(key => {
const rawValue = source[key]
const values = Array.isArray(rawValue) ? rawValue.slice() : [rawValue]
const normalized = values
.map(item => String(item))
.sort()
.join(',')
return `${key}=${normalized}`
}).join('&')
}
function buildJsonPayload(data) {
if (data === undefined || data === null || data === '') {
return ''
}
if (typeof data === 'string') {
return data
}
return JSON.stringify(data)
}
function randomNonce() {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
module.exports = {
sha256Hex,
hmacSha256Hex,
buildCanonicalParams,
buildJsonPayload,
randomNonce
}
+20
View File
@@ -0,0 +1,20 @@
const { STORAGE_KEYS, getStorage, setStorage } = require('./storage')
function createDeviceId() {
const randomText = Math.random().toString(36).slice(2, 10)
return `mini-device-${Date.now()}-${randomText}`
}
function getDeviceId() {
let value = getStorage(STORAGE_KEYS.DEVICE_ID, '')
if (value) {
return value
}
value = createDeviceId()
setStorage(STORAGE_KEYS.DEVICE_ID, value)
return value
}
module.exports = {
getDeviceId
}
+24 -13
View File
@@ -1,5 +1,6 @@
const fileApi = require('../api/file')
const { DEFAULT_PRODUCT_IMAGE } = require('./config')
const { CACHE_TTL } = require('./config')
const { splitCsv } = require('./format')
const urlCache = {}
@@ -10,11 +11,17 @@ async function getSignedUrl(fileId) {
return ''
}
if (!urlCache[key]) {
urlCache[key] = await fileApi.getSignedUrl(key)
const cached = urlCache[key]
if (cached && cached.expireAt > Date.now()) {
return cached.value || ''
}
return urlCache[key] || ''
const value = await fileApi.getSignedUrl(key)
urlCache[key] = {
value: value || '',
expireAt: Date.now() + (CACHE_TTL.signedUrl || 50 * 60 * 1000)
}
return urlCache[key].value
}
function extractLegacyFileId(value) {
@@ -31,16 +38,13 @@ async function resolveImageList(fileIds, fallbackImage) {
return [fallbackImage || DEFAULT_PRODUCT_IMAGE]
}
const urls = []
for (let index = 0; index < ids.length; index += 1) {
const fileId = ids[index]
const urls = (await Promise.all(ids.map(async fileId => {
try {
const url = await getSignedUrl(fileId)
if (url) {
urls.push(url)
}
} catch (error) {}
}
return await getSignedUrl(fileId)
} catch (error) {
return ''
}
}))).filter(Boolean)
return urls.length ? urls : [fallbackImage || DEFAULT_PRODUCT_IMAGE]
}
@@ -63,5 +67,12 @@ module.exports = {
getSignedUrl,
extractLegacyFileId,
resolveImageList,
resolveLegacyImage
resolveLegacyImage,
clearSignedUrlCache(fileId) {
if (fileId === undefined || fileId === null || fileId === '') {
Object.keys(urlCache).forEach(key => delete urlCache[key])
return
}
delete urlCache[String(fileId)]
}
}
+73
View File
@@ -0,0 +1,73 @@
const DRAFT_PREFIX = 'miniDraft:'
function buildDraftKey(key) {
return `${DRAFT_PREFIX}${key}`
}
function loadDraft(key, defaultValue) {
if (!key) {
return defaultValue
}
try {
const value = wx.getStorageSync(buildDraftKey(key))
return value === undefined || value === '' ? defaultValue : value
} catch (error) {
return defaultValue
}
}
function saveDraft(key, value) {
if (!key) {
return
}
try {
wx.setStorageSync(buildDraftKey(key), {
savedAt: Date.now(),
value
})
} catch (error) {}
}
function clearDraft(key) {
if (!key) {
return
}
try {
wx.removeStorageSync(buildDraftKey(key))
} catch (error) {}
}
function getDraftValue(key, defaultValue) {
const record = loadDraft(key, null)
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
return defaultValue
}
return record.value
}
function scheduleDraftSave(context, key, buildValue, delay) {
if (!context) {
return
}
if (context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
}
context.__draftSaveTimer = setTimeout(() => {
saveDraft(key, buildValue())
}, delay || 300)
}
function clearDraftTimer(context) {
if (context && context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
context.__draftSaveTimer = null
}
}
module.exports = {
getDraftValue,
saveDraft,
clearDraft,
scheduleDraftSave,
clearDraftTimer
}
+165
View File
@@ -0,0 +1,165 @@
let options = null
let timer = null
let warningShown = false
let loggingOut = false
let hiddenAt = 0
let lastActiveAt = Date.now()
let pagePatched = false
function shouldTrackMethod(name) {
return ![
'onHide',
'onUnload',
'onShareAppMessage',
'onShareTimeline'
].includes(name)
}
function ensurePagePatched() {
if (pagePatched || typeof Page !== 'function') {
return
}
const originalPage = Page
Page = function wrappedPage(definition) {
const nextDefinition = {}
Object.keys(definition || {}).forEach(key => {
const value = definition[key]
if (typeof value !== 'function') {
nextDefinition[key] = value
return
}
nextDefinition[key] = function wrappedHandler(...args) {
if (shouldTrackMethod(key)) {
markActive()
}
return value.apply(this, args)
}
})
return originalPage(nextDefinition)
}
pagePatched = true
}
function start() {
stop()
if (!options) {
return
}
timer = setInterval(check, 15000)
}
function stop() {
if (timer) {
clearInterval(timer)
timer = null
}
}
function isLoggedIn() {
return options && typeof options.isLoggedIn === 'function' ? Boolean(options.isLoggedIn()) : false
}
function markActive() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
lastActiveAt = Date.now()
warningShown = false
}
function onAppShow() {
if (!options) {
return
}
if (hiddenAt > 0 && isLoggedIn()) {
const hiddenDuration = Date.now() - hiddenAt
if (hiddenDuration >= options.timeoutMs) {
forceLogout()
return
}
}
hiddenAt = 0
markActive()
start()
}
function onAppHide() {
hiddenAt = Date.now()
stop()
}
function check() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
const idleMs = Date.now() - lastActiveAt
if (idleMs >= options.timeoutMs) {
forceLogout()
return
}
if (idleMs >= options.timeoutMs - options.warningMs && !warningShown) {
showWarning()
}
}
function showWarning() {
if (!options || warningShown || loggingOut) {
return
}
warningShown = true
wx.showModal({
title: options.warningTitle || '登录即将过期',
content: options.warningContent || '长时间未操作,即将退出登录。',
confirmText: options.confirmText || '继续使用',
cancelText: options.cancelText || '退出登录',
success: result => {
warningShown = false
if (result.confirm) {
markActive()
if (typeof options.onContinue === 'function') {
options.onContinue()
}
return
}
forceLogout()
},
fail: () => {
warningShown = false
}
})
}
function forceLogout() {
if (!options || loggingOut) {
return
}
loggingOut = true
Promise.resolve()
.then(() => (typeof options.onLogout === 'function' ? options.onLogout() : undefined))
.catch(() => undefined)
.finally(() => {
loggingOut = false
warningShown = false
hiddenAt = 0
lastActiveAt = Date.now()
})
}
function init(nextOptions) {
options = nextOptions || null
lastActiveAt = Date.now()
warningShown = false
loggingOut = false
hiddenAt = 0
ensurePagePatched()
start()
}
module.exports = {
init,
start,
stop,
markActive,
onAppShow,
onAppHide
}
+2 -2
View File
@@ -18,12 +18,12 @@ async function buildProductCard(product) {
return {
...product,
displayTitle: getProductTitle(product),
priceText: `¥${formatPrice(product && product.price)}`,
priceText: `¥${formatPrice(product && product.price)}`,
metaText: (product && (product.approximateDuration || product.shopName)) || '支持预约',
coverUrl: images[0],
imageUrls: images,
tagsPreview: getProductTags(product),
statsText: `${Number(product && product.likeCount || 0)}赞 · ${Number(product && product.collectCount || 0)}藏`
statsText: `${Number((product && product.likeCount) || 0)}赞 · ${Number((product && product.collectCount) || 0)}藏`
}
}
+168 -21
View File
@@ -1,9 +1,20 @@
const auth = require('./auth')
const { API_BASE_URL, REQUEST_TIMEOUT } = require('./config')
const actionGuard = require('./action-guard')
const idleSession = require('./idle-session')
const { API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
const HEADER_TIMESTAMP = 'X-Timestamp'
const HEADER_NONCE = 'X-Nonce'
const HEADER_SIGNATURE = 'X-Signature'
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
const DEVICE_ID_HEADER = 'X-Device-Id'
let isRefreshing = false
let requestQueue = []
let redirectingToAuth = false
const inflightRequests = {}
function buildRequestUrl(url, params) {
const query = Object.keys(params || {})
@@ -36,13 +47,14 @@ function isWhitelistedPath(url) {
}
function normalizeError(message, statusCode, raw) {
const error = new Error(message || '请求失败')
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
error.statusCode = statusCode
error.raw = raw
return error
}
function rawRequest(options) {
idleSession.markActive()
return new Promise((resolve, reject) => {
wx.request({
...options,
@@ -71,7 +83,6 @@ function flushQueue(error) {
item.reject(error)
return
}
item.retry().then(item.resolve).catch(item.reject)
})
}
@@ -92,7 +103,7 @@ function redirectToAuth() {
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
wx.showToast({
title: '登录已过期,请重新登录',
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
icon: 'none'
})
@@ -106,10 +117,45 @@ function redirectToAuth() {
}, 300)
}
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isWhitelistedPath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isWhitelistedPath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return headers
}
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
const payload = contentType.includes('application/json')
? buildJsonPayload(options.data)
: buildCanonicalParams(options.formData || options.data || options.params)
const timestamp = String(Date.now())
const nonce = randomNonce()
const canonical = [
method,
options.url,
timestamp,
nonce,
sha256Hex(payload)
].join('\n')
headers[HEADER_TIMESTAMP] = timestamp
headers[HEADER_NONCE] = nonce
headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical)
headers[HEADER_SIGNATURE_VERSION] = 'v1'
return headers
}
async function refreshToken() {
const refreshTokenValue = auth.getRefreshToken()
if (!refreshTokenValue) {
throw normalizeError('缺少刷新令牌', 401)
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
}
const response = await rawRequest({
@@ -117,7 +163,8 @@ async function refreshToken() {
method: 'POST',
timeout: REQUEST_TIMEOUT,
header: {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
[DEVICE_ID_HEADER]: getDeviceId()
},
data: {
refreshToken: refreshTokenValue
@@ -134,7 +181,7 @@ async function refreshToken() {
}
throw normalizeError(
(response.data && response.data.message) || '刷新登录态失败',
(response.data && response.data.message) || '\u5237\u65b0\u767b\u5f55\u6001\u5931\u8d25',
response.statusCode,
response
)
@@ -148,7 +195,7 @@ async function handleUnauthorized(options) {
app.clearUserSession()
}
redirectToAuth()
throw normalizeError('登录已过期,请重新登录', 401)
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
}
if (isRefreshing) {
@@ -180,14 +227,16 @@ async function handleUnauthorized(options) {
}
}
function unwrapResponse(res, options) {
async function unwrapResponse(res, options) {
idleSession.markActive()
if (res.statusCode === 401) {
return handleUnauthorized(options)
}
if (res.statusCode >= 400) {
throw normalizeError(
(res.data && res.data.message) || '网络请求失败',
(res.data && res.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
res.statusCode,
res
)
@@ -198,32 +247,110 @@ function unwrapResponse(res, options) {
if (payload.code === 200) {
return payload.data
}
throw normalizeError(payload.message || '请求失败', payload.code, payload)
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
}
return payload
}
function buildDedupeKey(options, method) {
if (options.skipDedupe) {
return ''
}
if (options.dedupeKey) {
return `${method}:${options.dedupeKey}`
}
if (method === 'GET') {
return `${method}:${options.url}:${buildCanonicalParams(options.params)}`
}
return ''
}
function isSafeMethod(method) {
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
}
function buildActionFingerprint(options, method) {
const paramsText = buildCanonicalParams(options.params)
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
return sha256Hex([
options.url || '',
paramsText,
payloadText
].join('\n'))
}
function resolveRepeatMessage(url) {
const path = String(url || '')
if (
path.includes('/user/login')
|| path.includes('/user/phone-login')
|| path.includes('/user/register')
|| path.includes('/user/reset-password-by-phone')
|| path.includes('/user/wechat-mini/')
) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/send-verification-code')) {
return '\u9a8c\u8bc1\u7801\u53d1\u9001\u5904\u7406\u4e2d\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
}
if (path.includes('/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/order/create')) {
return '\u8ba2\u5355\u6b63\u5728\u63d0\u4ea4\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/cart/')) {
return '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
function buildActionGuardConfig(options, method) {
if (options.skipActionGuard || isSafeMethod(method)) {
return null
}
return {
scope: options.guardScope,
key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`,
message: options.repeatMessage || resolveRepeatMessage(options.url)
}
}
function request(options) {
const method = (options.method || 'GET').toUpperCase()
const method = String(options.method || 'GET').toUpperCase()
const dedupeKey = buildDedupeKey(options, method)
if (dedupeKey && inflightRequests[dedupeKey]) {
return inflightRequests[dedupeKey]
}
const signatureHeaders = buildSignatureHeaders({
url: options.url,
method,
data: options.data,
params: options.params,
header: options.header
})
const header = {
'Content-Type': 'application/json',
...signatureHeaders,
...(options.header || {})
}
const accessToken = auth.getAccessToken()
if (accessToken) {
header.Authorization = `Bearer ${accessToken}`
}
const requestOptions = {
...options,
method,
header
}
const actionGuardConfig = buildActionGuardConfig(options, method)
return new Promise((resolve, reject) => {
const executeRequest = () => new Promise((resolve, reject) => {
wx.request({
url: buildRequestUrl(options.url, method === 'GET' ? options.params : undefined),
method,
@@ -239,10 +366,30 @@ function request(options) {
}
},
fail: error => {
reject(normalizeError(error.errMsg || '网络异常,请稍后重试', 0, error))
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
}
})
})
const task = (actionGuardConfig
? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, {
message: actionGuardConfig.message
})
: executeRequest()
).finally(() => {
if (dedupeKey) {
delete inflightRequests[dedupeKey]
}
})
if (dedupeKey) {
inflightRequests[dedupeKey] = task
}
return task
}
request.buildSignatureHeaders = buildSignatureHeaders
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
module.exports = request
+2 -1
View File
@@ -3,7 +3,8 @@ const STORAGE_KEYS = {
REFRESH_TOKEN: 'refreshToken',
USER_INFO: 'userInfo',
NEED_SET_PASSWORD: 'needSetPassword',
PREFERRED_MINI_LOGIN_SHOP_ID: 'preferredMiniLoginShopId'
PREFERRED_MINI_LOGIN_SHOP_ID: 'preferredMiniLoginShopId',
DEVICE_ID: 'miniDeviceId'
}
function getStorage(key, defaultValue) {