From e26e86acf88412890fad9178cde29da473412dc4 Mon Sep 17 00:00:00 2001 From: linju-json Date: Tue, 25 Jan 2022 11:21:20 +0800 Subject: [PATCH] =?UTF-8?q?-=20=E4=BF=9D=E5=AD=98=E5=88=B0=E6=94=B9?= =?UTF-8?q?=E7=94=A8=E5=BC=82=E6=AD=A5=E6=96=B9=E6=B3=95=EF=BC=8C=E6=96=B9?= =?UTF-8?q?=E4=BE=BF=E9=80=9A=E8=BF=87=E6=8B=A6=E6=88=AA=E5=99=A8=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E6=9B=B4=E6=96=B0=E5=90=8E=E7=9A=84=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=20-=20=E6=96=B0=E5=A2=9E=E9=80=9A=E8=BF=87=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E5=99=A8=E7=9B=91=E5=90=AC=E6=9B=B4=E6=96=B0=EF=BC=8C=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E4=BA=91=E5=87=BD=E6=95=B0=E5=88=B7=E6=96=B0=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E8=AE=BE=E5=A4=87=E4=BF=A1=E6=81=AFtoken=E6=9C=89?= =?UTF-8?q?=E6=95=88=E6=9C=9F=E7=9A=84API=20=20-=20=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E7=95=99=E8=A8=80=E6=9D=BF=E7=A4=BA=E4=BE=8B=20-=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E5=9B=BE=E7=89=87=E9=AA=8C=E8=AF=81=E7=A0=81=E6=A0=B7?= =?UTF-8?q?=E5=BC=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - changelog.md | 5 + common/appInit.js | 172 +++++--- lang/en.js | 9 - lang/zh-Hans.js | 9 - package.json | 5 +- pages.json | 19 - pages/ucenter/guestbook/guestbook.vue | 223 ---------- .../login-page/pwd-login/pwd-login.vue | 2 +- pages/ucenter/ucenter.vue | 4 - store/modules/user.js | 15 +- uni-starter.config.js | 1 - ...6\345\272\223\347\256\241\347\220\206.jql" | 2 +- .../database/guestbook.schema.json | 57 --- .../common/uni-config-center/push/config.json | 12 +- .../uni-config-center/uni-push/config.json | 9 + uni_modules/uni-id-cf/changelog.md | 10 +- uni_modules/uni-id-cf/package.json | 4 +- .../cloudfunctions/uni-id-cf/index.js | 390 ++++++++++-------- uni_modules/uni-id/changelog.md | 3 + uni_modules/uni-id/package.json | 2 +- .../cloudfunctions/common/uni-id/index.js | 2 +- .../cloudfunctions/common/uni-id/package.json | 2 +- 23 files changed, 379 insertions(+), 579 deletions(-) delete mode 100644 pages/ucenter/guestbook/guestbook.vue delete mode 100644 uniCloud-aliyun/database/guestbook.schema.json create mode 100644 uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/uni-push/config.json diff --git a/README.md b/README.md index 591c1b1..1a8b116 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,6 @@ uni-starter服务端使用[uni-config-center](https://ext.dcloud.net.cn/plugin?i "/pages/common/webview/webview", "/pages/grid/grid", "/pages/ucenter/ucenter", - "/pages/ucenter/guestbook/guestbook", "/pages/ucenter/about/about", "/pages/ucenter/settings/settings" ] diff --git a/changelog.md b/changelog.md index e29b553..097cf58 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,8 @@ +## 1.1.29(2022-01-25) +- 保存`uni_id_token`到`storage`改用异步方法,方便通过拦截器执行`token`更新后的操作 +- 新增通过拦截器监听`uni_id_token`更新,调用云函数刷新刷新设备信息token有效期的API `renewDeviceTokenExpired` +- 删除留言板示例 +- 修复图片验证码样式问题 ## 1.1.28(2022-01-12) 删除list页第37行多了个`?`引起的报错 ## 1.1.27(2022-01-11) diff --git a/common/appInit.js b/common/appInit.js index 4dd648b..279adf5 100644 --- a/common/appInit.js +++ b/common/appInit.js @@ -88,8 +88,7 @@ export default async function() { 'TOKEN_INVALID', 'TOKEN_INVALID_TOKEN_EXPIRED', 'TOKEN_INVALID_WRONG_TOKEN', - 'TOKEN_INVALID_ANONYMOUS_USER', - + 'TOKEN_INVALID_ANONYMOUS_USER' ].includes(code)) { uni.navigateTo({ url: '/pages/ucenter/login-page/index/index' @@ -114,76 +113,44 @@ export default async function() { tokenExpired }) }) + + uni.addInterceptor('setStorage', { + invoke(args) { + if (args.data && args.key == 'uni_id_token') { + let oldToken = uni.getStorageSync('uni_id_token') + if(oldToken.length){ + console.log('监听到token更新,就刷新push_clientid的有效期'); + uniCloud.callFunction({ + name:'uni-id-cf', + data:{ + "action": "renewDeviceTokenExpiredxpired", + "params": {push_clientid} + }, + complete: (e) => { + console.log(e); + } + }) + } + } + // console.log('interceptor-complete', args) + }, + complete(e) { + // console.log(e); + } + }) const Debug = false; //拦截器封装callFunction let callFunctionOption; uniCloud.addInterceptor('callFunction', { async invoke(option) { - // #ifdef APP-PLUS // 判断如果是执行登录(无论是哪种登录方式),就记录用户的相关设备id + // 注意:注册可能不仅仅走register接口,还有登录并注册的接口 if (option.name == 'uni-id-cf' && (option.data.action == 'register' || option.data.action.slice(0, 5) == 'login') ) { - let oaid = await new Promise((callBack, fail) => { - if (uni.getSystemInfoSync().platform == "android") { - plus.device.getOAID({ - success: function(e) { - callBack(e.oaid) - // console.log('getOAID success: '+JSON.stringify(e)); - }, - fail: function(e) { - callBack() - console.log('getOAID failed: ' + JSON.stringify(e)); - } - }); - } else { - callBack() - } - }) - - let imei = await new Promise((callBack, fail) => { - if (uni.getSystemInfoSync().platform == "android") { - plus.device.getInfo({ - success: function(e) { - callBack(e.imei) - // console.log('getOAID success: '+JSON.stringify(e)); - }, - fail: function(e) { - callBack() - console.log('getOAID failed: ' + JSON.stringify(e)); - } - }); - } else { - callBack() - } - }) - - let push_clientid = '', - idfa = plus.storage.getItem('idfa') || ''; //idfa有需要的用户在应用首次启动时自己获取存储到storage中 - - try { - push_clientid = plus.push.getClientInfo().clientid - } catch (e) { - uni.showModal({ - content: '获取推送标识失败。如果你的应用不需要推送功能,请注释掉本代码块', - showCancel: false, - confirmText: "好的" - }); - console.log(e) - } - - let deviceInfo = { - push_clientid, // 获取匿名设备标识符 - imei, - oaid, - idfa - } - //console.log("重新登录/注册,获取设备id", deviceInfo); - option.data.deviceInfo = deviceInfo - - // #ifndef H5 - //注册可能不仅仅走register接口,还有登录并注册的接口 + option.data.deviceInfo = await getDeviceInfo() + console.log("重新登录/注册,获取设备id", option.data.deviceInfo); option.data.inviteCode = await new Promise((callBack) => { uni.getClipboardData({ success: function(res) { @@ -206,9 +173,7 @@ export default async function() { } }); }) - // #endif } - // #endif // console.log(JSON.stringify(option)); callFunctionOption = option }, @@ -261,7 +226,6 @@ export default async function() { }); }, success: (e) => { - // console.log(e); const { token, tokenExpired @@ -455,3 +419,81 @@ function initAppVersion() { // 检查更新 // #endif } + +async function getDeviceInfo() { + let deviceInfo = { + "uuid": '', + "vendor": '', + "push_clientid": '', + "imei": '', + "oaid": '', + "idfa": '', + "model": '', + "platform": '', + } + const { + model, + platform, + } = uni.getSystemInfoSync(); + Object.assign(deviceInfo, { + model, + platform + }); + + // #ifdef APP-PLUS + const oaid = await new Promise((callBack, fail) => { + if (deviceInfo.platform == "android") { + plus.device.getOAID({ + success: function(e) { + callBack(e.oaid) + // console.log('getOAID success: '+JSON.stringify(e)); + }, + fail: function(e) { + callBack() + console.log('getOAID failed: ' + JSON.stringify(e)); + } + }); + } else { + callBack() + } + }), + { + imei, + uuid + } = await new Promise((callBack, fail) => { + plus.device.getInfo({ + success: function(e) { + callBack(e) + // console.log('getOAID success: '+JSON.stringify(e)); + }, + fail: function(e) { + callBack() + console.log('getOAID failed: ' + JSON.stringify(e)); + } + }); + }), + idfa = plus.storage.getItem('idfa') || '', //idfa有需要的用户在应用首次启动时自己获取存储到storage中 + vendor = plus.device.vendor; + try { + deviceInfo.push_clientid = uni.getStorageSync('cid') //先都走在线 + // deviceInfo.push_clientid = plus.push.getClientInfo().clientid + } catch (e) { + uni.showModal({ + content: '获取推送标识失败。如果你的应用不需要推送功能,请注释掉本代码块', + showCancel: false, + confirmText: "好的" + }); + console.log(e) + } + Object.assign(deviceInfo, { + imei, + uuid, + idfa, + vendor + }); + // #endif + // #ifndef APP-PLUS + deviceInfo.push_clientid = uni.getStorageSync('cid') + // #endif + return deviceInfo +} \ No newline at end of file diff --git a/lang/en.js b/lang/en.js index ee111cf..7b040cd 100644 --- a/lang/en.js +++ b/lang/en.js @@ -58,7 +58,6 @@ export default { readArticles: "Read Articles", myScore: "My Score", invite: "Invite Friends", - guestBook: "Guest Book Example", feedback: "Problems And Feedback", settings: "Settings", about: "About", @@ -98,14 +97,6 @@ export default { toSet: "Go to settings", error: "error", }, - guestbook: { - navigationBarTitle:"Message board", - msgContent: "post message content", - notAvailable: "not available for visitors who are not logged in", - send: "send", - addSucceeded: "Successfully added", - noPermission: "You don't have permission for this operation", - }, uniFeedback: { navigationBarTitle: "Problems and feedback", msgTitle: "Message content", diff --git a/lang/zh-Hans.js b/lang/zh-Hans.js index 968c67b..7b9bb41 100644 --- a/lang/zh-Hans.js +++ b/lang/zh-Hans.js @@ -59,7 +59,6 @@ export default { readArticles: "阅读过的文章", myScore: "我的积分", invite: "分销推荐", - guestBook: "留言板示例", feedback: "问题与反馈", settings: "设置", checkUpdate: "检查更新", @@ -99,14 +98,6 @@ export default { toSet: "前往设置", error: "错误", }, - guestbook:{ - navigationBarTitle:"留言板", - msgContent: "发表留言内容", - notAvailable: "未登录游客不可用", - send: "发送", - addSucceeded: "新增成功", - noPermission: "你没有该操作权限", - }, uniFeedback:{ navigationBarTitle:"问题与反馈", msgTitle: "留言内容", diff --git a/package.json b/package.json index d5ae7f0..655ef93 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,14 @@ { "id": "uni-starter", "displayName": "uni-starter", - "version": "1.1.28", + "version": "1.1.29", "description": "云端一体应用快速开发基本项目模版", "keywords": [ "login", "登录", "搜索", "uni-id实例", - "留言板", - "" + "留言板" ], "repository": "https://codechina.csdn.net/dcloud/uni-starter.git", "engines": { diff --git a/pages.json b/pages.json index c937903..d4ed643 100644 --- a/pages.json +++ b/pages.json @@ -169,25 +169,6 @@ "navigationBarTitleText": "意见反馈", "enablePullDownRefresh": false } - }, { - "path": "pages/ucenter/guestbook/guestbook", - "style": { - "navigationBarTitleText": "留言板", - "enablePullDownRefresh": false, - "app-plus": { - "titleNView": { - "buttons": [{ - "text": "切换", - "fontSize": "12px" - }, - { - "text": "注销", - "fontSize": "12px" - } - ] - } - } - } } ], "globalStyle": { diff --git a/pages/ucenter/guestbook/guestbook.vue b/pages/ucenter/guestbook/guestbook.vue deleted file mode 100644 index e3bb82d..0000000 --- a/pages/ucenter/guestbook/guestbook.vue +++ /dev/null @@ -1,223 +0,0 @@ - - - - - \ No newline at end of file diff --git a/pages/ucenter/login-page/pwd-login/pwd-login.vue b/pages/ucenter/login-page/pwd-login/pwd-login.vue index 2ae1979..f90bb9a 100644 --- a/pages/ucenter/login-page/pwd-login/pwd-login.vue +++ b/pages/ucenter/login-page/pwd-login/pwd-login.vue @@ -155,7 +155,7 @@ justify-content: flex-end; } .captcha-img{ - margin:15px 15px 0 0; + margin: 0 15px 10px 0; width: 250rpx; } .captcha{ diff --git a/pages/ucenter/ucenter.vue b/pages/ucenter/ucenter.vue index eb6cba3..a11931a 100644 --- a/pages/ucenter/ucenter.vue +++ b/pages/ucenter/ucenter.vue @@ -113,10 +113,6 @@ // #endif ], [{ - "title": this.$t('mine.guestBook'), - "to": '/pages/ucenter/guestbook/guestbook', - "icon": "chat" - },{ "title": this.$t('mine.feedback'), "to": '/uni_modules/uni-feedback/pages/opendb-feedback/opendb-feedback', "icon": "help" diff --git a/store/modules/user.js b/store/modules/user.js index 22d12ba..f4a616b 100644 --- a/store/modules/user.js +++ b/store/modules/user.js @@ -24,15 +24,22 @@ let state = { console.log('state.info',state.info); //存储最新的用户数据到本地持久化存储 uni.setStorageSync('userInfo', state.info); - uni.setStorageSync('uni_id_token', state.info.token) - uni.setStorageSync('uni_id_token_expired', state.info.tokenExpired) - + if(info.token){ + uni.setStorage({ + key: 'uni_id_token', + data: state.info.token, + complete(e){ + // console.log('setStorage-------',e); + } + }); + uni.setStorageSync('uni_id_token_expired', state.info.tokenExpired) + } }, logout(state) { state.info = {}; state.hasLogin = false; uni.setStorageSync('userInfo', {}); - uni.setStorageSync('uni_id_token', ''); + uni.removeStorageSync('uni_id_token'); uni.setStorageSync('uni_id_token_expired', 0) } }, diff --git a/uni-starter.config.js b/uni-starter.config.js index 2b2fd22..0dbc136 100644 --- a/uni-starter.config.js +++ b/uni-starter.config.js @@ -40,7 +40,6 @@ export default { "/pages/common/webview/webview", "/pages/grid/grid", "/pages/ucenter/ucenter", - "/pages/ucenter/guestbook/guestbook", "/pages/ucenter/about/about", "/pages/ucenter/settings/settings" ], diff --git "a/uniCloud-aliyun/database/JQL\346\225\260\346\215\256\345\272\223\347\256\241\347\220\206.jql" "b/uniCloud-aliyun/database/JQL\346\225\260\346\215\256\345\272\223\347\256\241\347\220\206.jql" index 4903b47..5292b02 100644 --- "a/uniCloud-aliyun/database/JQL\346\225\260\346\215\256\345\272\223\347\256\241\347\220\206.jql" +++ "b/uniCloud-aliyun/database/JQL\346\225\260\346\215\256\345\272\223\347\256\241\347\220\206.jql" @@ -9,4 +9,4 @@ // 详细JQL语法,请参考 https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=jsquery // 下面示例查询uni-id-users表的所有数据 -db.collection('guestbook, uni-id-users').where('user_id._id=="610a6daa506cc7000100c07f"').get(); +db.collection('uni-id-users').where('user_id._id=="610a6daa506cc7000100c07f"').get(); diff --git a/uniCloud-aliyun/database/guestbook.schema.json b/uniCloud-aliyun/database/guestbook.schema.json deleted file mode 100644 index 8f8cbec..0000000 --- a/uniCloud-aliyun/database/guestbook.schema.json +++ /dev/null @@ -1,57 +0,0 @@ -// 文档教程: https://uniapp.dcloud.net.cn/uniCloud/schema -{ - "bsonType": "object", - "required": [], - "permission": { - "read": "doc.state || auth.uid == doc.user_id || 'AUDITOR' in auth.role", - "create": "auth.uid != null", - "update": "'AUDITOR' in auth.role", - "delete": "auth.uid == doc.user_id" - }, - "properties": { - "_id": { - "description": "ID,系统自动生成", - "permission":{ - "write":false - } - }, - "text": { - "bsonType": "string", - "permission":{ - "write":false - } - }, - "user_id": { - "forceDefaultValue": { - "$env": "uid" - }, - "foreignKey": "uni-id-users._id", - "permission":{ - "write":false - } - }, - "ip": { - "forceDefaultValue": { - "$env": "clientIP" - }, - "permission":{ - "write":false - } - }, - "create_time": { - "forceDefaultValue": { - "$env": "now" - }, - "permission":{ - "write":false - } - }, - "state": { - "bsonType": "bool", - "forceDefaultValue":false, - "permission":{ - "write":true - } - } - } -} \ No newline at end of file diff --git a/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/push/config.json b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/push/config.json index 8bf55e9..de29608 100644 --- a/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/push/config.json +++ b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/push/config.json @@ -1,10 +1,10 @@ { "goEasy": { - "commonKey": "BC-01f554db12604b46ae8373907e28794d", - "clientKey": "PC-bfb6b6517e7f4c4f8b9285911fd3be27", - "subscribeKey": "BS-ac71890d8612459bb4b22429cf406be3", - "restKey": "PR-77f4630e731e4b5f8078aea77268cba4", - "secretKey": "4bfeca3985504b3d", - "restHost":"rest-hangzhou.goeasy.io" + "commonKey": "", + "clientKey": "", + "subscribeKey": "", + "restKey": "", + "secretKey": "", + "restHost":"" } } diff --git a/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/uni-push/config.json b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/uni-push/config.json new file mode 100644 index 0000000..f104390 --- /dev/null +++ b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/uni-push/config.json @@ -0,0 +1,9 @@ +{ + "getui": { + "appId": "dCgnx0otCL8rjloSyynDu7", + "appkey": "YGUYb5yPMN67rNyElDZv7A", + "appSecret": "b0zAa92FrG6HT9Hsqk2CR8", + "mastersecret": "nNXpI9MHkS8hZjdmQUD9H3", + "packageName": "io.dcloud.hellouniapp" + } +} diff --git a/uni_modules/uni-id-cf/changelog.md b/uni_modules/uni-id-cf/changelog.md index b0b2d44..c000b96 100644 --- a/uni_modules/uni-id-cf/changelog.md +++ b/uni_modules/uni-id-cf/changelog.md @@ -1,3 +1,9 @@ +## 1.0.12(2022-01-24) +- 优化设备信息存储逻辑 +- 新增刷新设备信息token有效期的API `renewDeviceTokenExpired` +## 1.0.11(2022-01-19) +- 新增 getNeedCaptcha 接口 +- 优化 调整 login 接口的代码结构 ## 1.0.10(2022-01-08) - 修复 限制只有 admin 用户可管理用户标签(不支持非 admin 用户操作managerMultiTag 接口) ## 1.0.9(2021-12-01) @@ -17,8 +23,8 @@ ## 1.0.3(2021-07-02) - 框架设定非 admin 不能创建用户, 用户可自定义 ## 1.0.2(2021-07-01) -1. 发送短信验证码api,默认注释掉:虚拟发送短信验证码的代码块。 -2. 统一action名称为驼峰法 +- 发送短信验证码api,默认注释掉:虚拟发送短信验证码的代码块。 +- 统一action名称为驼峰法 ## 1.0.1(2021-06-28) 修复resetPwdBySmsCode接口,未注册过的用户也能调用的问题 ## 1.0.0(2021-06-21) diff --git a/uni_modules/uni-id-cf/package.json b/uni_modules/uni-id-cf/package.json index f1aeaac..e3efa45 100644 --- a/uni_modules/uni-id-cf/package.json +++ b/uni_modules/uni-id-cf/package.json @@ -1,7 +1,7 @@ { "id": "uni-id-cf", "displayName": "uni-id-cf", - "version": "1.0.10", + "version": "1.0.12", "description": "封装uni-id常用接口的云函数,快速实现简单、统一、可扩展的用户管理功能", "keywords": [ "uni-id-cf", @@ -78,4 +78,4 @@ } } } -} \ No newline at end of file +} diff --git a/uni_modules/uni-id-cf/uniCloud/cloudfunctions/uni-id-cf/index.js b/uni_modules/uni-id-cf/uniCloud/cloudfunctions/uni-id-cf/index.js index 4040754..31a47ad 100644 --- a/uni_modules/uni-id-cf/uniCloud/cloudfunctions/uni-id-cf/index.js +++ b/uni_modules/uni-id-cf/uniCloud/cloudfunctions/uni-id-cf/index.js @@ -8,7 +8,11 @@ const uniIdConfig = createConfig({ const db = uniCloud.database() const dbCmd = db.command const usersDB = db.collection('uni-id-users') +const deviceDB = db.collection('uni-id-device') exports.main = async (event, context) => { + console.log({ + context + }); //UNI_WYQ:这里的uniID换成新的,保证多人访问不会冲突 uniID = uniID.createInstance({ context @@ -16,9 +20,9 @@ exports.main = async (event, context) => { console.log('event : ' + JSON.stringify(event)) /* 1.event为客户端 uniCloud.callFunction填写的data的值,这里介绍一下其中的属性 - action:表示要执行的任务名称、比如:登录login、退出登录 logout等 - params:业务数据内容 - uniIdToken:系统自动传递的token,数据来源客户端的 uni.getStorageSync('uni_id_token') + action:表示要执行的任务名称、比如:登录login、退出登录 logout等 + params:业务数据内容 + uniIdToken:系统自动传递的token,数据来源客户端的 uni.getStorageSync('uni_id_token') */ const { action, @@ -26,13 +30,13 @@ exports.main = async (event, context) => { inviteCode } = event; const deviceInfo = event.deviceInfo || {}; - let params = event.params || {}; + let params = event.params || {}, + tokenExpired; /* 2.在某些操作之前我们要对用户对身份进行校验(也就是要检查用户的token)再将得到的uid写入params.uid - 校验用到的方法是uniID.checkToken 详情:https://uniapp.dcloud.io/uniCloud/uni-id?id=checktoken - - 讨论,我们假设一个这样的场景,代码如下。 - 如: + 校验用到的方法是uniID.checkToken 详情:https://uniapp.dcloud.io/uniCloud/uni-id?id=checktoken + 讨论,我们假设一个这样的场景,代码如下。 + 如: uniCloud.callFunction({ name:"xxx", data:{ @@ -41,12 +45,12 @@ exports.main = async (event, context) => { } } }) - 用户就这样轻易地伪造了他人的uid传递给服务端,有一句话叫:前端传来的数据都是不可信任的 - 所以这里我们需要将uniID.checkToken返回的uid写入到params.uid + 用户就这样轻易地伪造了他人的uid传递给服务端,有一句话叫:前端传来的数据都是不可信任的 + 所以这里我们需要将uniID.checkToken返回的uid写入到params.uid */ - let noCheckAction = ['register', 'checkToken', 'login', 'logout', 'sendSmsCode', 'createCaptcha', - 'verifyCaptcha', 'refreshCaptcha', 'inviteLogin', 'loginByWeixin', 'loginByUniverify', - 'loginByApple', 'loginBySms', 'resetPwdBySmsCode', 'registerAdmin' + let noCheckAction = ['register', 'checkToken', 'login', 'logout', 'sendSmsCode', 'getNeedCaptcha', + 'createCaptcha', 'verifyCaptcha', 'refreshCaptcha', 'inviteLogin', 'loginByWeixin', + 'loginByUniverify', 'loginByApple', 'loginBySms', 'resetPwdBySmsCode', 'registerAdmin' ] if (!noCheckAction.includes(action)) { if (!uniIdToken) { @@ -60,6 +64,7 @@ exports.main = async (event, context) => { return payload } params.uid = payload.uid + tokenExpired = payload.tokenExpired } //禁止前台用户传递角色 @@ -73,7 +78,7 @@ exports.main = async (event, context) => { } // 3.注册成功后触发。 - async function registerSuccess(uid) { + async function registerSuccess(res) { //用户接受邀请 if (inviteCode) { await uniID.acceptInvite({ @@ -82,18 +87,15 @@ exports.main = async (event, context) => { }); } //添加当前用户设备信息 - await db.collection('uni-id-device').add({ - ...deviceInfo, - user_id: uid - }) + await addDeviceInfo(res) } //4.记录成功登录的日志方法 const loginLog = async (res = {}) => { const now = Date.now() const uniIdLogCollection = db.collection('uni-id-log') let logData = { - deviceId: params.deviceId || context.DEVICEID, - ip: params.ip || context.CLIENTIP, + deviceId: context.DEVICEID, + ip: context.CLIENTIP, type: res.type, ua: context.CLIENTUA, create_date: now @@ -106,17 +108,31 @@ exports.main = async (event, context) => { delete res.userInfo.password } if (res.type == 'register') { - await registerSuccess(res.uid) + await registerSuccess(res) } else { if (Object.keys(deviceInfo).length) { - // console.log(979797, { - // deviceInfo, - // user_id: res - // }); - //更新当前用户设备信息 - await db.collection('uni-id-device').where({ - user_id: res.uid - }).update(deviceInfo) + console.log(context.DEVICEID); + //避免重复新增设备信息,先判断是否已存在 + let getDeviceRes = await deviceDB.where({ + device_id: context.DEVICEID + }).get() + if (getDeviceRes.data.length == 0) { + await addDeviceInfo(res) + } else { + await deviceDB.where({ + device_id: context.DEVICEID, + }).update({ + ...deviceInfo, + tokenExpired: res.tokenExpired, + "user_id": res.uid, + "device_id": context.DEVICEID, + "ua": context.CLIENTUA, + "platform": context.PLATFORM, + "create_date": Date.now(), + "last_active_date": Date.now(), + "last_active_ip": context.CLIENTIP + }) + } } } } else { @@ -125,8 +141,55 @@ exports.main = async (event, context) => { return await uniIdLogCollection.add(logData) } + async function addDeviceInfo({ + uid, + tokenExpired + }) { + return await deviceDB.add({ + ...deviceInfo, + tokenExpired, + "user_id": uid, + "device_id": context.DEVICEID, + "ua": context.CLIENTUA, + "platform": context.PLATFORM, + "create_date": Date.now(), + "last_active_date": Date.now(), + "last_active_ip": context.CLIENTIP + }) + } + + //5.防止恶意破解登录,连续登录失败一定次数后,需要用户提供验证码 + const isNeedCaptcha = async () => { + //当用户最近“2小时内(recordDate)”登录失败达到2次(recordSize)时。要求用户提交验证码 + const now = Date.now(), + recordDate = 120 * 60 * 1000, + recordSize = 2; + const uniIdLogCollection = db.collection('uni-id-log') + let recentRecord = await uniIdLogCollection.where({ + deviceId: params.deviceId || context.DEVICEID, + create_date: dbCmd.gt(now - recordDate), + type: 'login' + }) + .orderBy('create_date', 'desc') + .limit(recordSize) + .get(); + return recentRecord.data.filter(item => item.state === 0).length === recordSize; + } + let res = {} switch (action) { //根据action的值执行对应的操作 + case 'renewDeviceTokenExpired': + let aa = await deviceDB.where({ + user_id: params.uid, + "device_id": context.DEVICEID + }).update({ + user_id: params.uid, + push_clientid: params.push_clientid, + tokenExpired + }) + console.log(aa); + return aa + break; case 'refreshSessionKey': let getSessionKey = await uniID.code2SessionWeixin({ code: params.code @@ -221,30 +284,19 @@ exports.main = async (event, context) => { inviteCode }); if (res.code === 0) { - await registerSuccess(res.uid) + await registerSuccess(res) } break; - case 'login': - //防止黑客恶意破解登录,连续登录失败一定次数后,需要用户提供验证码 - const getNeedCaptcha = async () => { - //当用户最近“2小时内(recordDate)”登录失败达到2次(recordSize)时。要求用户提交验证码 - const now = Date.now(), - recordDate = 120 * 60 * 1000, - recordSize = 2; - const uniIdLogCollection = db.collection('uni-id-log') - let recentRecord = await uniIdLogCollection.where({ - deviceId: params.deviceId || context.DEVICEID, - create_date: dbCmd.gt(now - recordDate), - type: 'login' - }) - .orderBy('create_date', 'desc') - .limit(recordSize) - .get(); - return recentRecord.data.filter(item => item.state === 0).length === recordSize; - } + case 'getNeedCaptcha': { + const needCaptcha = await isNeedCaptcha() + res.needCaptcha = needCaptcha + break; + } + + case 'login': let passed = false; - let needCaptcha = await getNeedCaptcha(); + let needCaptcha = await isNeedCaptcha(); console.log('needCaptcha', needCaptcha); if (needCaptcha) { res = await uniCaptcha.verify({ @@ -261,7 +313,7 @@ exports.main = async (event, context) => { }); res.type = 'login' await loginLog(res); - needCaptcha = await getNeedCaptcha(); + needCaptcha = await isNeedCaptcha(); } res.needCaptcha = needCaptcha; @@ -280,10 +332,10 @@ exports.main = async (event, context) => { } = uniIdConfig['app-plus'].oauth.weixin; let wxRes = await uniCloud.httpclient.request( `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&scope=snsapi_userinfo&appid=${appid}&secret=${secret}`, { - method: 'POST', - contentType: 'json', // 指定以application/json发送data内的数据 - dataType: 'json' // 指定返回值为json格式,自动进行parse - }) + method: 'POST', + contentType: 'json', // 指定以application/json发送data内的数据 + dataType: 'json' // 指定返回值为json格式,自动进行parse + }) if (wxRes.status == 200) { let { nickname, @@ -464,7 +516,7 @@ exports.main = async (event, context) => { }); break; - // =========================== admin api start ========================= + // =========================== admin api start ========================= case 'registerAdmin': { var { username, @@ -505,137 +557,137 @@ exports.main = async (event, context) => { } } - break; - case 'registerUser': - const { - userInfo - } = await uniID.getUserInfo({ - uid: params.uid - }) - if (userInfo.role.indexOf('admin') === -1) { - res = { - code: 403, - message: '非法访问, 无权限注册超级管理员', - } - } else { - // 过滤 dcloud_appid,注册用户成功后再提交 - const dcloudAppidList = params.dcloud_appid - delete params.dcloud_appid - res = await uniID.register({ - autoSetDcloudAppid: false, - ...params + break; + case 'registerUser': + const { + userInfo + } = await uniID.getUserInfo({ + uid: params.uid }) - if (res.code === 0) { - delete res.token - delete res.tokenExpired - await uniID.setAuthorizedAppLogin({ - uid: res.uid, - dcloudAppidList + if (userInfo.role.indexOf('admin') === -1) { + res = { + code: 403, + message: '非法访问, 无权限注册超级管理员', + } + } else { + // 过滤 dcloud_appid,注册用户成功后再提交 + const dcloudAppidList = params.dcloud_appid + delete params.dcloud_appid + res = await uniID.register({ + autoSetDcloudAppid: false, + ...params }) + if (res.code === 0) { + delete res.token + delete res.tokenExpired + await uniID.setAuthorizedAppLogin({ + uid: res.uid, + dcloudAppidList + }) + } } - } - break; - case 'updateUser': { - const { - userInfo - } = await uniID.getUserInfo({ - uid: params.uid - }) - if (userInfo.role.indexOf('admin') === -1) { - res = { - code: 403, - message: '非法访问, 无权限注册超级管理员', - } - } else { - // 过滤 dcloud_appid,注册用户成功后再提交 - const dcloudAppidList = params.dcloud_appid - delete params.dcloud_appid + break; + case 'updateUser': { + const { + userInfo + } = await uniID.getUserInfo({ + uid: params.uid + }) + if (userInfo.role.indexOf('admin') === -1) { + res = { + code: 403, + message: '非法访问, 无权限注册超级管理员', + } + } else { + // 过滤 dcloud_appid,注册用户成功后再提交 + const dcloudAppidList = params.dcloud_appid + delete params.dcloud_appid - // 过滤 password,注册用户成功后再提交 - const password = params.password - delete params.password + // 过滤 password,注册用户成功后再提交 + const password = params.password + delete params.password - // 过滤 uid、id - const id = params.id - delete params.id - delete params.uid + // 过滤 uid、id + const id = params.id + delete params.id + delete params.uid - res = await uniID.updateUser({ - uid: id, - ...params - }) - if (res.code === 0) { - if (password) { - await uniID.resetPwd({ + res = await uniID.updateUser({ + uid: id, + ...params + }) + if (res.code === 0) { + if (password) { + await uniID.resetPwd({ + uid: id, + password + }) + } + await uniID.setAuthorizedAppLogin({ uid: id, - password + dcloudAppidList }) } - await uniID.setAuthorizedAppLogin({ - uid: id, - dcloudAppidList - }) - } - } - break; - } - case 'getCurrentUserInfo': - res = await uniID.getUserInfo({ - uid: params.uid, - ...params - }) - break; - case 'managerMultiTag': { - const { - userInfo - } = await uniID.getUserInfo({ - uid: params.uid - }) - // 限制只有 admin 角色的用户可管理标签,如需非 admin 角色需自行实现 - if (userInfo.role.indexOf('admin') === -1) { - res = { - code: 403, - message: '非法访问, 无权限修改用户标签', } - return + break; } - let { - ids, - type, - value - } = params - if (type === 'add') { - res = await db.collection('uni-id-users').where({ - _id: dbCmd.in(ids) - }).update({ - tags: dbCmd.addToSet({ - $each: value - }) + case 'getCurrentUserInfo': + res = await uniID.getUserInfo({ + uid: params.uid, + ...params }) - } else if (type === 'del') { - res = await db.collection('uni-id-users').where({ - _id: dbCmd.in(ids) - }).update({ - tags: dbCmd.pull(dbCmd.in(value)) + break; + case 'managerMultiTag': { + const { + userInfo + } = await uniID.getUserInfo({ + uid: params.uid }) - } else { + // 限制只有 admin 角色的用户可管理标签,如需非 admin 角色需自行实现 + if (userInfo.role.indexOf('admin') === -1) { + res = { + code: 403, + message: '非法访问, 无权限修改用户标签', + } + return + } + let { + ids, + type, + value + } = params + if (type === 'add') { + res = await db.collection('uni-id-users').where({ + _id: dbCmd.in(ids) + }).update({ + tags: dbCmd.addToSet({ + $each: value + }) + }) + } else if (type === 'del') { + res = await db.collection('uni-id-users').where({ + _id: dbCmd.in(ids) + }).update({ + tags: dbCmd.pull(dbCmd.in(value)) + }) + } else { + res = { + code: 403, + msg: '无效操作' + } + return + } + break; + } + // =========================== admin api end ========================= + default: res = { code: 403, - msg: '无效操作' + msg: '非法访问' } - return - } - break; - } - // =========================== admin api end ========================= - default: - res = { - code: 403, - msg: '非法访问' - } - break; + break; } //返回数据给客户端 return res -} +} \ No newline at end of file diff --git a/uni_modules/uni-id/changelog.md b/uni_modules/uni-id/changelog.md index 136275b..24e9b40 100644 --- a/uni_modules/uni-id/changelog.md +++ b/uni_modules/uni-id/changelog.md @@ -1,3 +1,6 @@ +## 3.3.12(2022-01-15) +- 新增 preferedAppPlatform 配置用于解决uni-app vue2版本vue3版本获取platform不一致的问题 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=prefered-app-platform) +- 修复 checkToken 未返回自定义token内容的Bug ## 3.3.11(2022-01-11) - 修复用户名密码登录时多个应用出现重复用户名登录报错的Bug ## 3.3.10(2022-01-07) diff --git a/uni_modules/uni-id/package.json b/uni_modules/uni-id/package.json index 73c7d49..4c83e1b 100644 --- a/uni_modules/uni-id/package.json +++ b/uni_modules/uni-id/package.json @@ -1,7 +1,7 @@ { "id": "uni-id", "displayName": "uni-id", - "version": "3.3.11", + "version": "3.3.12", "description": "简单、统一、可扩展的用户中心", "keywords": [ "uniid", diff --git a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js index 47ab1dc..64a2178 100644 --- a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js +++ b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js @@ -1 +1 @@ -"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("fs")),r=e(require("path")),n=e(require("crypto")),i=e(require("buffer")),o=e(require("stream")),s=e(require("util"));const a={PARAM_ERROR:{errCode:"param-error"},PARAM_REQUIRED:{errCode:"param-required"},USER_NOT_EXIST:{errCode:"user-not-exist"},ROLE_NOT_EXIST:{errCode:"role-not-exist"},PERMISSION_NOT_EXIST:{errCode:"permission-not-exist"},MULTI_USER_MATCHED:{errCode:"multi-user-matched"},USER_INFO_ERROR:{errCode:"user-info-error"},USER_ACCOUNT_CONFLICT:{errCode:"user-account-conflict"},USER_ACCOUNT_CLOSED:{errCode:"user-account-closed"},ACCOUNT_ALREADY_REGISTED:{errCode:"account-already-registed"},ACCOUNT_NOT_REGISTED:{errCode:"account-not-registed"},ACCOUNT_already_BOUND:{errCode:"account-already-bound"},UNBIND_FAILED:{errCode:"unbind-failed"},INVALID_INVITE_CODE:{errCode:"invalid-invite-code"},SET_INVITE_CODE_FAILED:{errCode:"set-invite-code-failed"},GET_THIRD_PARTY_ACCOUNT_FAILED:{errCode:"get-third-party-account-failed"}},c={0:{errCode:0,errMsg:""},10001:{errCode:"account-banned"},10002:a.USER_NOT_EXIST,10003:a.MULTI_USER_MATCHED,10004:a.USER_INFO_ERROR,10005:a.USER_ACCOUNT_CONFLICT,10006:a.USER_ACCOUNT_CLOSED,10102:{errCode:"password-error"},10103:{errCode:"password-error-exceed-limit"},10201:a.ACCOUNT_ALREADY_REGISTED,10202:a.ACCOUNT_NOT_REGISTED,10203:a.INVALID_INVITE_CODE,10301:a.ACCOUNT_ALREADY_REGISTED,10302:a.ACCOUNT_NOT_REGISTED,10401:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10402:a.ACCOUNT_ALREADY_REGISTED,10403:a.ACCOUNT_NOT_REGISTED,10501:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10502:a.ACCOUNT_ALREADY_REGISTED,10503:a.ACCOUNT_NOT_REGISTED,10601:a.ACCOUNT_ALREADY_REGISTED,10602:a.ACCOUNT_NOT_REGISTED,10701:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10702:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10703:a.ACCOUNT_ALREADY_REGISTED,10704:a.ACCOUNT_NOT_REGISTED,10705:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10706:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10801:a.GET_THIRD_PARTY_ACCOUNT_FAILED,10802:a.ACCOUNT_ALREADY_REGISTED,10803:a.ACCOUNT_NOT_REGISTED,20101:a.PARAM_REQUIRED,20102:a.ACCOUNT_ALREADY_REGISTED,30101:a.PARAM_REQUIRED,30201:{errCode:"check-device-feature-failed"},30202:{errCode:"token-not-exist"},30203:{errCode:"token-expired"},30204:{errCode:"check-token-failed"},40201:a.USER_NOT_EXIST,40202:{errCode:"invalid-old-password"},50101:a.PARAM_REQUIRED,50102:a.PARAM_ERROR,50201:a.PARAM_REQUIRED,50203:a.PARAM_ERROR,50202:{errCode:"invalid-verify-code"},50301:{errCode:"send-sms-code-failed"},60101:a.ACCOUNT_already_BOUND,60201:a.ACCOUNT_already_BOUND,60301:a.GET_THIRD_PARTY_ACCOUNT_FAILED,60302:a.ACCOUNT_already_BOUND,60401:a.GET_THIRD_PARTY_ACCOUNT_FAILED,60402:a.ACCOUNT_already_BOUND,60501:a.GET_THIRD_PARTY_ACCOUNT_FAILED,60502:a.ACCOUNT_already_BOUND,70101:a.UNBIND_FAILED,70201:a.UNBIND_FAILED,70301:a.UNBIND_FAILED,70401:a.UNBIND_FAILED,70501:a.UNBIND_FAILED,80301:a.USER_NOT_EXIST,80401:a.SET_INVITE_CODE_FAILED,80402:a.SET_INVITE_CODE_FAILED,80501:a.INVALID_INVITE_CODE,80502:a.USER_NOT_EXIST,80503:{errCode:"modify-invite-code-is-not-allowed"},80601:a.GET_THIRD_PARTY_ACCOUNT_FAILED,80602:a.GET_THIRD_PARTY_ACCOUNT_FAILED,80701:a.GET_THIRD_PARTY_ACCOUNT_FAILED,80702:a.GET_THIRD_PARTY_ACCOUNT_FAILED,80801:{errCode:"decrypt-weixin-data-failed"},80802:{errCode:"decrypt-weixin-data-failed"},80803:{errCode:"invalid-weixin-appid"},80804:a.PARAM_REQUIRED,80805:a.PARAM_REQUIRED,80806:a.PARAM_REQUIRED,90001:{errCode:"database-operation-failed"},90002:a.PARAM_REQUIRED,90003:a.PARAM_ERROR,90004:a.USER_NOT_EXIST,90005:a.ROLE_NOT_EXIST,90006:a.PERMISSION_NOT_EXIST};class u extends Error{constructor(e){super(e.message),this.errMsg=e.message||"",Object.defineProperties(this,{message:{get(){return`errCode: ${e.code||""} | errMsg: `+this.errMsg},set(e){this.errMsg=e}}})}}const d=Object.prototype.toString,l=Object.prototype.hasOwnProperty;function f(e,t){return l.call(e,t)}function p(e){return"[object Object]"===d.call(e)}function h(e){return"function"==typeof e}function m(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function g(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}const y=/_(\w)/g,w=/[A-Z]/g;function v(e){return e.replace(y,(e,t)=>t?t.toUpperCase():"")}function _(e){return e.replace(w,e=>"_"+e.toLowerCase())}function b(e,t){let r,n;switch(t){case"snake2camel":n=v,r=y;break;case"camel2snake":n=_,r=w}for(const i in e)if(f(e,i)&&r.test(i)){const r=n(i);e[r]=e[i],delete e[i],p(e[r])?e[r]=b(e[r],t):Array.isArray(e[r])&&(e[r]=e[r].map(e=>b(e,t)))}return e}function E(e){return b(e,"snake2camel")}function C(e){return b(e,"camel2snake")}function T(e){return function(e,t="-"){e=e||new Date;const r=[];return r.push(e.getFullYear()),r.push(("00"+(e.getMonth()+1)).substr(-2)),r.push(("00"+e.getDate()).substr(-2)),r.join(t)}(e=e||new Date)+" "+function(e,t=":"){e=e||new Date;const r=[];return r.push(("00"+e.getHours()).substr(-2)),r.push(("00"+e.getMinutes()).substr(-2)),r.push(("00"+e.getSeconds()).substr(-2)),r.join(t)}(e)}function A(){"development"===process.env.NODE_ENV&&console.log(...arguments)}function x(e=6){let t="";for(let r=0;rN.call(e,t),U=new class{constructor(){this._caches=Object.create(null)}interpolate(e,t,r=P){if(!t)return[e];let n=this._caches[e];return n||(n=function(e,[t,r]){const n=[];let i=0,o="";for(;i-1?"zh-Hans":e.indexOf("-hant")>-1?"zh-Hant":(r=e,["-tw","-hk","-mo","-cht"].find(e=>-1!==r.indexOf(e))?"zh-Hant":"zh-Hans");var r;const n=function(e,t){return t.find(t=>0===e.indexOf(t))}(e,["en","fr","es"]);return n||void 0}class M{constructor({locale:e,fallbackLocale:t,messages:r,watcher:n,formater:i}){this.locale="en",this.fallbackLocale="en",this.message={},this.messages={},this.watchers=[],t&&(this.fallbackLocale=t),this.formater=i||U,this.messages=r||{},this.setLocale(e||"en"),n&&this.watchLocale(n)}setLocale(e){const t=this.locale;this.locale=V(e,this.messages)||this.fallbackLocale,this.messages[this.locale]||(this.messages[this.locale]={}),this.message=this.messages[this.locale],t!==this.locale&&this.watchers.forEach(e=>{e(this.locale,t)})}getLocale(){return this.locale}watchLocale(e){const t=this.watchers.push(e)-1;return()=>{this.watchers.splice(t,1)}}add(e,t,r=!0){const n=this.messages[e];n?r?Object.assign(n,t):Object.keys(t).forEach(e=>{L(n,e)||(n[e]=t[e])}):this.messages[e]=t}f(e,t,r){return this.formater.interpolate(e,t,r).join("")}t(e,t,r){let n=this.message;return"string"==typeof t?(t=V(t,this.messages))&&(n=this.messages[t]):r=t,L(n,e)?this.formater.interpolate(n[e],r).join(""):(console.warn(`Cannot translate the value of keypath ${e}. Use the value of keypath as default.`),e)}}var B={"zh-Hans":{alipay:"支付宝",wechat:"微信",user:"用户","user-id":"用户ID","dcloud-appid":"应用Appid","dcloud-appid-list":"应用列表",account:"账号",username:"用户名",email:"邮箱",mobile:"手机号","wechat-openid":"微信openid","wechat-account":"微信账号","alipay-account":"支付宝账号","qq-openid":"QQ openid","qq-account":"QQ账号","apple-account":"苹果账号",password:"密码","verify-code":"验证码","verify-code-type":"验证码类型","user-unique-param":"用户名、邮箱或手机号","role-id":"角色ID","permission-id":"权限ID",login:"登录","verify-mobile":"验证手机","context-param-required":"context内缺少{param},请使用uniID.createInstance传入客户端信息","config-param-require":"uni-id的配置内缺少{param}","uni-verify-config-required":"请在config.json中配置service.univerify下一键登录相关参数","login-with-invite-type-required":"强制使用邀请码注册时,需指明type为register还是login","type-array-required":"{param}应为数组形式","query-field-warning":"检测到当前使用queryField匹配多字段进行登录操作,需要注意:uni-id并未限制用户名不能是手机号或邮箱,需要开发者自行限制。否则可能出现用户输入abc@xx.com会同时匹配到邮箱为此值的用户和用户名为此值的用户,导致登录失败","add-role-admin-is-not-allowed":"不可新增roleID为admin的角色","password-secret-type-error":"config内passwordSecret类型错误,只可设置string类型和array类型","token-expires-config-warning":"tokenExpiresIn不可小于或等于tokenExpiresThreshold","type-function-required":"{param}应为function类型","dev-warning":"当前正在使用uniID.dev属性,注意此属性仅可用于开发调试","config-file-invalid":"请确保公用模块uni-id对应的配置文件(common/uni-config-center/uni-id/config.json)格式正确(不可包含注释)","config-file-not-found":"请在common/uni-config-center/uni-id/config.json内添加uni-id相关配置信息","hx-version-warning":"当前使用的HBuilderX版本过低,请升级HBuilderX到最新版本","account-banned":"账号已禁用","user-not-exist":"用户不存在","multi-user-matched":"匹配到多个账号","user-info-error":"用户信息不正确","user-account-conflict":"用户账号冲突","user-account-closed":"此账号已注销","password-error":"密码错误","password-error-exceed-limit":"密码错误次数过多,请稍后再试","account-already-registed":"此{type}已注册","account-not-registed":"此{type}尚未注册","invalid-invite-code":"邀请码无效","get-third-party-account-failed":"获取{account}失败","param-required":"{param}不可为空","check-device-feature-failed":"设备特征校验未通过","token-not-exist":"云端已不包含此token","token-expired":"token已过期","check-token-failed":"token校验未通过","invalid-old-password":"旧密码错误","param-error":"{param}参数错误,{reason}","invalid-verify-code":"验证码错误或已失效","send-sms-code-failed":"验证码发送失败","account-already-bound":"此{type}已绑定","unbind-failed":"解绑失败","set-invite-code-failed":"邀请码设置失败","modify-invite-code-is-not-allowed":"邀请码不可修改","decrypt-weixin-data-failed":"解密失败","invalid-weixin-appid":"appid不匹配","database-operation-failed":"数据库读写异常","role-not-exist":"角色不存在","permission-not-exist":"权限不存在","context-required":"uni-id无法获取context.{key},请使用uniID.createInstance方法传入"},en:{alipay:"alipay",wechat:"wechat",user:"user","user-id":"user id","dcloud-appid":"DCloud appid","dcloud-appid-list":"DCloud appid list",account:"account",username:"username",email:"email",mobile:"phone number","wechat-openid":"wechat openid","wechat-account":"wechat account","alipay-account":"alipay account","qq-openid":"QQ openid","qq-account":"QQ account","apple-account":"apple account",password:"password","verify-code":"verify code","verify-code-type":"verify code type","user-unique-param":"username, email or mobile phone number","role-id":"role id","permission-id":"permission id",login:"login","verify-mobile":"verify mobile phone number","context-param-required":"You should pass {param} in context using uniID.createInstance","config-param-require":"{param} is required in uni-id's config","uni-verify-config-required":"univerify config required: service.univerify","login-with-invite-type-required":"parameter type is required when forceInviteCode set to true","type-array-required":"type of {param} must be array","query-field-warning":"You are using multi query field to login, be aware that uni-id will not check username's fromat, eg: abc@xx.com is a valid username for uni-id. You should check username in your code.","add-role-admin-is-not-allowed":'add role with an id of "admin" is not allowed',"password-secret-type-error":"passwordSecret in config must be string or array","token-expires-config-warning":"tokenExpiresIn must be greater than tokenExpiresThreshold","type-function-required":"{param} must be a function","dev-warning":"warning: uniID.dev is only for development","config-file-invalid":"invalid config file (common/uni-config-center/uni-id/config.json), please note that comment is not allowed","config-file-not-found":"config file (common/uni-config-center/uni-id/config.json) not found","hx-version-warning":"The version of your HBuilderX is too lower, please upgrade to the latest version of HBuilderX","account-banned":"account is banned","user-not-exist":"user does not exist","multi-user-matched":"multiple users are matched","user-info-error":"user info error","user-account-conflict":"user account conflict","user-account-closed":"user account was closed","password-error":"password is incorrect","password-error-exceed-limit":"password error exceed limit","account-already-registed":"{type} is already registed","account-not-registed":"{type} is not registed","invalid-invite-code":"invalid invite code","get-third-party-account-failed":"get {account} failed","param-required":"{param} is required","check-device-feature-failed":"check device feature failed","token-not-exist":"token is not exist","token-expired":"token is expired","check-token-failed":"check token failed","invalid-old-password":"invalid old password","param-error":"{param} error, {reason}","invalid-verify-code":"invalid verify code","send-sms-code-failed":"send sms code failed","account-already-bound":"{type} is already bound","unbind-failed":"unbind failed","set-invite-code-failed":"set invite code failed","modify-invite-code-is-not-allowed":"invite code modification is not allowed","decrypt-weixin-data-failed":"decrypt weixin data failed","invalid-weixin-appid":"invalid weixin appid","database-operation-failed":"database operation failed","role-not-exist":"role does not exist","permission-not-exist":"permission does not exist","context-required":"context.{key} is required, you should pass context using uniID.createInstance"}};const F=uniCloud.database(),$=F.collection("uni-id-users"),H=F.collection("opendb-verify-codes"),K=F.collection("uni-id-roles"),G=F.collection("uni-id-permissions"),z={username:"username",mobile:"mobile",email:"email",wx_unionid:"wechat-account","wx_openid.app-plus":"wechat-account","wx_openid.mp-weixin":"wechat-account",qq_unionid:"qq-account","qq_openid.app-plus":"qq-account","qq_openid.mp-weixin":"qq-account",ali_openid:"alipay-account",apple_openid:"alipay-account"},Q=90002,Y=90003,J=90004,X=90005,W=0,Z=1,ee=4;async function te({uid:e,status:t}={}){return e?(await $.doc(e).update({status:t,status_update_date:Date.now()}),{code:0}):{code:Q,messageValues:{param:this.t("user-id")}}}async function re({name:e,url:t,data:r,options:n,defaultOptions:i}){let o={};const s=C(Object.assign({},r));s&&s.access_token&&delete s.access_token;try{n=Object.assign({},i,n,{data:s}),o=await uniCloud.httpclient.request(t,n)}catch(t){return function(e,t){throw new u({code:t.code||-2,message:t.message||e+" fail"})}(e,t)}let a=o.data;const c=o.headers["content-type"];if(!Buffer.isBuffer(a)||0!==c.indexOf("text/plain")&&0!==c.indexOf("application/json"))Buffer.isBuffer(a)&&(a={buffer:a,contentType:c});else try{a=JSON.parse(a.toString())}catch(e){a=a.toString()}return E(function(e,t){if(t.errcode)throw new u({code:t.errcode||-2,message:t.errmsg||e+" fail"});return delete t.errcode,delete t.errmsg,{...t,errMsg:e+" ok",errCode:0}}(e,a||{errCode:-2,errMsg:"Request failed"}))}function ne(e,t){let r="";if(t&&t.accessToken){r=`${e.indexOf("?")>-1?"&":"?"}access_token=${t.accessToken}`}return`${e}${r}`}class ie{constructor(e){this.options=Object.assign({baseUrl:"https://api.weixin.qq.com",timeout:5e3},e)}async _requestWxOpenapi({name:e,url:t,data:r,options:n}){const i={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};return await re({name:"auth."+e,url:`${this.options.baseUrl}${ne(t,r)}`,data:r,options:n,defaultOptions:i})}async code2Session(e){return await this._requestWxOpenapi({name:"code2Session",url:"/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}async getOauthAccessToken(e){const t=await this._requestWxOpenapi({name:"getOauthAccessToken",url:"/sns/oauth2/access_token",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,code:e}});return t.expiresIn&&(t.expired=Date.now()+t.expiresIn),t}}async function oe({name:e,url:t,data:r,options:n,defaultOptions:i}){let o;n=Object.assign({},i,n,{data:C(Object.assign({},r))});try{o=await uniCloud.httpclient.request(t,n)}catch(t){return function(e,t){throw new u({code:t.code||-2,message:t.message||e+" fail"})}(e,t)}let s=o.data;const a=o.headers["content-type"];if(!Buffer.isBuffer(s)||0!==a.indexOf("text/plain")&&0!==a.indexOf("application/json"))Buffer.isBuffer(s)&&(s={buffer:s,contentType:a});else try{s=JSON.parse(s.toString())}catch(e){s=s.toString()}return E(function(e,t){if(t.ret||t.error){const r=t.ret||t.error||t.errcode||-2,n=t.msg||t.error_description||t.errmsg||e+" fail";throw new u({code:r,message:n})}return delete t.ret,delete t.msg,delete t.error,delete t.error_description,delete t.errcode,delete t.errmsg,{...t,errMsg:e+" ok",errCode:0}}(e,s||{errCode:-2,errMsg:"Request failed"}))}class se{constructor(e){this.options=Object.assign({baseUrl:"https://graph.qq.com",timeout:5e3},e)}async _requestQQOpenapi({name:e,url:t,data:r,options:n}){const i={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};return await oe({name:"auth."+e,url:I(this.options.baseUrl,t),data:r,options:n,defaultOptions:i})}async getOpenidByToken({accessToken:e}={}){const t=await this._requestQQOpenapi({name:"getOpenidByToken",url:"/oauth2.0/me",data:{accessToken:e,unionid:1,fmt:"json"}});if(t.clientId!==this.options.appId)throw new u({code:"APPID_NOT_MATCH",message:"appid not match"});return{openid:t.openid,unionid:t.unionid}}async code2Session({code:e}={}){return await this._requestQQOpenapi({name:"getOpenidByToken",url:"https://api.q.qq.com/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}}const ae={RSA:"RSA-SHA1",RSA2:"RSA-SHA256"};var ce={code2Session:{returnValue:{openid:"userId"}}};class ue extends class{constructor(e={}){if(!e.appId)throw new Error("appId required");if(!e.privateKey)throw new Error("privateKey required");const t={gateway:"https://openapi.alipay.com/gateway.do",timeout:5e3,charset:"utf-8",version:"1.0",signType:"RSA2",timeOffset:-(new Date).getTimezoneOffset()/60,keyType:"PKCS8"};e.sandbox&&(e.gateway="https://openapi.alipaydev.com/gateway.do"),this.options=Object.assign({},t,e);const r="PKCS8"===this.options.keyType?"PRIVATE KEY":"RSA PRIVATE KEY";this.options.privateKey=this._formatKey(this.options.privateKey,r),this.options.alipayPublicKey&&(this.options.alipayPublicKey=this._formatKey(this.options.alipayPublicKey,"PUBLIC KEY"))}_formatKey(e,t){return`-----BEGIN ${t}-----\n${e}\n-----END ${t}-----`}_formatUrl(e,t){let r=e;const n=["app_id","method","format","charset","sign_type","sign","timestamp","version","notify_url","return_url","auth_token","app_auth_token"];for(const e in t)if(n.indexOf(e)>-1){const n=encodeURIComponent(t[e]);r=`${r}${r.includes("?")?"&":"?"}${e}=${n}`,delete t[e]}return{execParams:t,url:r}}_getSign(e,t){const r=t.bizContent||null;delete t.bizContent;const i=Object.assign({method:e,appId:this.options.appId,charset:this.options.charset,version:this.options.version,signType:this.options.signType,timestamp:T((o=this.options.timeOffset,new Date(Date.now()+6e4*((new Date).getTimezoneOffset()+60*(o||0)))))},t);var o;r&&(i.bizContent=JSON.stringify(C(r)));const s=C(i),a=Object.keys(s).sort().map(e=>{let t=s[e];return"[object String]"!==Array.prototype.toString.call(t)&&(t=JSON.stringify(t)),`${e}=${t}`}).join("&"),c=n.createSign(ae[this.options.signType]).update(a,"utf8").sign(this.options.privateKey,"base64");return Object.assign(s,{sign:c})}async _exec(e,t={},r={}){const n=this._getSign(e,t),{url:i,execParams:o}=this._formatUrl(this.options.gateway,n),{status:s,data:a}=await uniCloud.httpclient.request(i,{method:"POST",data:o,dataType:"text",timeout:this.options.timeout});if(200!==s)throw new Error("request fail");const c=JSON.parse(a),u=e.replace(/\./g,"_")+"_response",d=c[u],l=c.error_response;if(d){if(!r.validateSign||this._checkResponseSign(a,u)){if(!d.code||"10000"===d.code){return{errCode:0,errMsg:d.msg||"",...E(d)}}const e=d.sub_code?`${d.sub_code} ${d.sub_msg}`:""+(d.msg||"unkonwn error");throw new Error(e)}throw new Error("check sign error")}if(l)throw new Error(l.sub_msg||l.msg||"request fail");throw new Error("request fail")}_checkResponseSign(e,t){if(!this.options.alipayPublicKey||""===this.options.alipayPublicKey)return console.warn("options.alipayPublicKey is empty"),!0;if(!e)return!1;const r=this._getSignStr(e,t),i=JSON.parse(e).sign,o=n.createVerify(ae[this.options.signType]);return o.update(r,"utf8"),o.verify(this.options.alipayPublicKey,i,"base64")}_getSignStr(e,t){let r=e.trim();const n=e.indexOf(t+'"'),i=e.lastIndexOf('"sign"');return r=r.substr(n+t.length+1),r=r.substr(0,i),r=r.replace(/^[^{]*{/g,"{"),r=r.replace(/\}([^}]*)$/g,"}"),r}}{constructor(e){super(e),this._protocols=ce}async code2Session(e){return await this._exec("alipay.system.oauth.token",{grantType:"authorization_code",code:e})}}function de(e){var t=e[0];return t<"0"||t>"7"?"00"+e:e}function le(e){var t=e.toString(16);return t.length%2?"0"+t:t}function fe(e){if(e<=127)return le(e);var t=le(e);return le(128+t.length/2)+t}var pe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function he(e,t){return e(t={exports:{}},t.exports),t.exports}var me=he((function(e,t){var r=i.Buffer;function n(e,t){for(var r in e)t[r]=e[r]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=i:(n(i,t),t.Buffer=o),o.prototype=Object.create(r.prototype),n(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i.SlowBuffer(e)}})),ge=(me.Buffer,me.Buffer);function ye(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=ge.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=ge.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}s.inherits(ye,o),ye.prototype.write=function(e){this.buffer=ge.concat([this.buffer,ge.from(e)]),this.emit("data",e)},ye.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};var we=ye,ve=i.Buffer,_e=i.SlowBuffer,be=Ee;function Ee(e,t){if(!ve.isBuffer(e)||!ve.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(var r=0,n=0;n=128&&--n,n}var je={derToJose:function(e,t){e=Oe(e);var r=Se(t),n=r+1,i=e.length,o=0;if(48!==e[o++])throw new Error('Could not find expected "seq"');var s=e[o++];if(129===s&&(s=e[o++]),i-o0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*St;case"hours":case"hour":case"hrs":case"hr":case"h":return r*xt;case"minutes":case"minute":case"mins":case"min":case"m":return r*At;case"seconds":case"second":case"secs":case"sec":case"s":return r*Tt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=St)return Ot(e,t,St,"day");if(t>=xt)return Ot(e,t,xt,"hour");if(t>=At)return Ot(e,t,At,"minute");if(t>=Tt)return Ot(e,t,Tt,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=St)return Math.round(e/St)+"d";if(t>=xt)return Math.round(e/xt)+"h";if(t>=At)return Math.round(e/At)+"m";if(t>=Tt)return Math.round(e/Tt)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Ot(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var kt=function(e,t){var r=t||Math.floor(Date.now()/1e3);if("string"==typeof e){var n=It(e);if(void 0===n)return;return Math.floor(r+n/1e3)}return"number"==typeof e?r+e:void 0},jt=he((function(e,t){var r;t=e.exports=G,r="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var n=Number.MAX_SAFE_INTEGER||9007199254740991,i=t.re=[],o=t.src=[],s=0,a=s++;o[a]="0|[1-9]\\d*";var c=s++;o[c]="[0-9]+";var u=s++;o[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var d=s++;o[d]="("+o[a]+")\\.("+o[a]+")\\.("+o[a]+")";var l=s++;o[l]="("+o[c]+")\\.("+o[c]+")\\.("+o[c]+")";var f=s++;o[f]="(?:"+o[a]+"|"+o[u]+")";var p=s++;o[p]="(?:"+o[c]+"|"+o[u]+")";var h=s++;o[h]="(?:-("+o[f]+"(?:\\."+o[f]+")*))";var m=s++;o[m]="(?:-?("+o[p]+"(?:\\."+o[p]+")*))";var g=s++;o[g]="[0-9A-Za-z-]+";var y=s++;o[y]="(?:\\+("+o[g]+"(?:\\."+o[g]+")*))";var w=s++,v="v?"+o[d]+o[h]+"?"+o[y]+"?";o[w]="^"+v+"$";var _="[v=\\s]*"+o[l]+o[m]+"?"+o[y]+"?",b=s++;o[b]="^"+_+"$";var E=s++;o[E]="((?:<|>)?=?)";var C=s++;o[C]=o[c]+"|x|X|\\*";var T=s++;o[T]=o[a]+"|x|X|\\*";var A=s++;o[A]="[v=\\s]*("+o[T]+")(?:\\.("+o[T]+")(?:\\.("+o[T]+")(?:"+o[h]+")?"+o[y]+"?)?)?";var x=s++;o[x]="[v=\\s]*("+o[C]+")(?:\\.("+o[C]+")(?:\\.("+o[C]+")(?:"+o[m]+")?"+o[y]+"?)?)?";var S=s++;o[S]="^"+o[E]+"\\s*"+o[A]+"$";var I=s++;o[I]="^"+o[E]+"\\s*"+o[x]+"$";var O=s++;o[O]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var k=s++;o[k]="(?:~>?)";var j=s++;o[j]="(\\s*)"+o[k]+"\\s+",i[j]=new RegExp(o[j],"g");var R=s++;o[R]="^"+o[k]+o[A]+"$";var P=s++;o[P]="^"+o[k]+o[x]+"$";var D=s++;o[D]="(?:\\^)";var q=s++;o[q]="(\\s*)"+o[D]+"\\s+",i[q]=new RegExp(o[q],"g");var N=s++;o[N]="^"+o[D]+o[A]+"$";var L=s++;o[L]="^"+o[D]+o[x]+"$";var U=s++;o[U]="^"+o[E]+"\\s*("+_+")$|^$";var V=s++;o[V]="^"+o[E]+"\\s*("+v+")$|^$";var M=s++;o[M]="(\\s*)"+o[E]+"\\s*("+_+"|"+o[A]+")",i[M]=new RegExp(o[M],"g");var B=s++;o[B]="^\\s*("+o[A]+")\\s+-\\s+("+o[A]+")\\s*$";var F=s++;o[F]="^\\s*("+o[x]+")\\s+-\\s+("+o[x]+")\\s*$";var $=s++;o[$]="(<|>)?=?\\s*\\*";for(var H=0;H<35;H++)r(H,o[H]),i[H]||(i[H]=new RegExp(o[H]));function K(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof G)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?i[b]:i[w]).test(e))return null;try{return new G(e,t)}catch(e){return null}}function G(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof G){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof G))return new G(e,t);r("SemVer",e,t),this.options=t,this.loose=!!t.loose;var o=e.trim().match(t.loose?i[b]:i[w]);if(!o)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,r,n){"string"==typeof r&&(n=r,r=void 0);try{return new G(e,r).inc(t,n).version}catch(e){return null}},t.diff=function(e,t){if(W(e,t))return null;var r=K(e),n=K(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";var o="prerelease"}for(var s in r)if(("major"===s||"minor"===s||"patch"===s)&&r[s]!==n[s])return i+s;return o},t.compareIdentifiers=Q;var z=/^[0-9]+$/;function Q(e,t){var r=z.test(e),n=z.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e0}function X(e,t,r){return Y(e,t,r)<0}function W(e,t,r){return 0===Y(e,t,r)}function Z(e,t,r){return 0!==Y(e,t,r)}function ee(e,t,r){return Y(e,t,r)>=0}function te(e,t,r){return Y(e,t,r)<=0}function re(e,t,r,n){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return W(e,r,n);case"!=":return Z(e,r,n);case">":return J(e,r,n);case">=":return ee(e,r,n);case"<":return X(e,r,n);case"<=":return te(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}function ne(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof ne){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof ne))return new ne(e,t);r("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ie?this.value="":this.value=this.operator+this.semver.version,r("comp",this)}t.rcompareIdentifiers=function(e,t){return Q(t,e)},t.major=function(e,t){return new G(e,t).major},t.minor=function(e,t){return new G(e,t).minor},t.patch=function(e,t){return new G(e,t).patch},t.compare=Y,t.compareLoose=function(e,t){return Y(e,t,!0)},t.rcompare=function(e,t,r){return Y(t,e,r)},t.sort=function(e,r){return e.sort((function(e,n){return t.compare(e,n,r)}))},t.rsort=function(e,r){return e.sort((function(e,n){return t.rcompare(e,n,r)}))},t.gt=J,t.lt=X,t.eq=W,t.neq=Z,t.gte=ee,t.lte=te,t.cmp=re,t.Comparator=ne;var ie={};function oe(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof oe)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new oe(e.raw,t);if(e instanceof ne)return new oe(e.value,t);if(!(this instanceof oe))return new oe(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function se(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,r,n,i,o,s,a,c,u,d,l,f){return((t=se(r)?"":se(n)?">="+r+".0.0":se(i)?">="+r+"."+n+".0":">="+t)+" "+(a=se(c)?"":se(u)?"<"+(+c+1)+".0.0":se(d)?"<"+c+"."+(+u+1)+".0":l?"<="+c+"."+u+"."+d+"-"+l:"<="+a)).trim()}function ce(e,t,n){for(var i=0;i0){var o=e[i].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}function ue(e,t,r){try{t=new oe(t,r)}catch(e){return!1}return t.test(e)}function de(e,t,r,n){var i,o,s,a,c;switch(e=new G(e,n),t=new oe(t,n),r){case">":i=J,o=te,s=X,a=">",c=">=";break;case"<":i=X,o=ee,s=J,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,n))return!1;for(var u=0;u=0.0.0")),l=l||e,f=f||e,i(e.semver,l.semver,n)?l=e:s(e.semver,f.semver,n)&&(f=e)})),l.operator===a||l.operator===c)return!1;if((!f.operator||f.operator===a)&&o(e,f.semver))return!1;if(f.operator===c&&s(e,f.semver))return!1}return!0}ne.prototype.parse=function(e){var t=this.options.loose?i[U]:i[V],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],"="===this.operator&&(this.operator=""),r[2]?this.semver=new G(r[2],this.options.loose):this.semver=ie},ne.prototype.toString=function(){return this.value},ne.prototype.test=function(e){return r("Comparator.test",e,this.options.loose),this.semver===ie||("string"==typeof e&&(e=new G(e,this.options)),re(e,this.operator,this.semver,this.options))},ne.prototype.intersects=function(e,t){if(!(e instanceof ne))throw new TypeError("a Comparator is required");var r;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return r=new oe(e.value,t),ue(this.value,r,t);if(""===e.operator)return r=new oe(this.value,t),ue(e.semver,r,t);var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),i=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),o=this.semver.version===e.semver.version,s=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=re(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=re(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||i||o&&s||a||c},t.Range=oe,oe.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},oe.prototype.toString=function(){return this.range},oe.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var n=t?i[F]:i[B];e=e.replace(n,ae),r("hyphen replace",e),e=e.replace(i[M],"$1$2$3"),r("comparator trim",e,i[M]),e=(e=(e=e.replace(i[j],"$1~")).replace(i[q],"$1^")).split(/\s+/).join(" ");var o=t?i[U]:i[V],s=e.split(" ").map((function(e){return function(e,t){return r("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){r("caret",e,t);var n=t.loose?i[L]:i[N];return e.replace(n,(function(t,n,i,o,s){var a;return r("caret",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a="0"===n?">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":">="+n+"."+i+".0 <"+(+n+1)+".0.0":s?(r("replaceCaret pr",s),a="0"===n?"0"===i?">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+"-"+s+" <"+(+n+1)+".0.0"):(r("no pr"),a="0"===n?"0"===i?">="+n+"."+i+"."+o+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+" <"+(+n+1)+".0.0"),r("caret return",a),a}))}(e,t)})).join(" ")}(e,t),r("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var n=t.loose?i[P]:i[R];return e.replace(n,(function(t,n,i,o,s){var a;return r("tilde",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":s?(r("replaceTilde pr",s),a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0"):a=">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0",r("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),r("tildes",e),e=function(e,t){return r("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var n=t.loose?i[I]:i[S];return e.replace(n,(function(t,n,i,o,s,a){r("xRange",e,t,n,i,o,s,a);var c=se(i),u=c||se(o),d=u||se(s);return"="===n&&d&&(n=""),c?t=">"===n||"<"===n?"<0.0.0":"*":n&&d?(u&&(o=0),s=0,">"===n?(n=">=",u?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",u?i=+i+1:o=+o+1),t=n+i+"."+o+"."+s):u?t=">="+i+".0.0 <"+(+i+1)+".0.0":d&&(t=">="+i+"."+o+".0 <"+i+"."+(+o+1)+".0"),r("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),r("xrange",e),e=function(e,t){return r("replaceStars",e,t),e.trim().replace(i[$],"")}(e,t),r("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(s=s.filter((function(e){return!!e.match(o)}))),s=s.map((function(e){return new ne(e,this.options)}),this)},oe.prototype.intersects=function(e,t){if(!(e instanceof oe))throw new TypeError("a Range is required");return this.set.some((function(r){return r.every((function(r){return e.set.some((function(e){return e.every((function(e){return r.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new oe(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},oe.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new G(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":r&&!J(r,t)||(r=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(r&&e.test(r))return r;return null},t.validRange=function(e,t){try{return new oe(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,r){return de(e,t,"<",r)},t.gtr=function(e,t,r){return de(e,t,">",r)},t.outside=de,t.prerelease=function(e,t){var r=K(e,t);return r&&r.prerelease.length?r.prerelease:null},t.intersects=function(e,t,r){return e=new oe(e,r),t=new oe(t,r),e.intersects(t)},t.coerce=function(e){if(e instanceof G)return e;if("string"!=typeof e)return null;var t=e.match(i[O]);if(null==t)return null;return K(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}})),Rt=(jt.SEMVER_SPEC_VERSION,jt.re,jt.src,jt.parse,jt.valid,jt.clean,jt.SemVer,jt.inc,jt.diff,jt.compareIdentifiers,jt.rcompareIdentifiers,jt.major,jt.minor,jt.patch,jt.compare,jt.compareLoose,jt.rcompare,jt.sort,jt.rsort,jt.gt,jt.lt,jt.eq,jt.neq,jt.gte,jt.lte,jt.cmp,jt.Comparator,jt.Range,jt.toComparators,jt.satisfies,jt.maxSatisfying,jt.minSatisfying,jt.minVersion,jt.validRange,jt.ltr,jt.gtr,jt.outside,jt.prerelease,jt.intersects,jt.coerce,jt.satisfies(process.version,"^6.12.0 || >=8.0.0")),Pt=["RS256","RS384","RS512","ES256","ES384","ES512"],Dt=["RS256","RS384","RS512"],qt=["HS256","HS384","HS512"];Rt&&(Pt.splice(3,0,"PS256","PS384","PS512"),Dt.splice(3,0,"PS256","PS384","PS512"));var Nt=/^\s+|\s+$/g,Lt=/^[-+]0x[0-9a-f]+$/i,Ut=/^0b[01]+$/i,Vt=/^0o[0-7]+$/i,Mt=/^(?:0|[1-9]\d*)$/,Bt=parseInt;function Ft(e){return e!=e}function $t(e,t){return function(e,t){for(var r=-1,n=e?e.length:0,i=Array(n);++r-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}(e.length)&&!function(e){var t=nr(e)?Qt.call(e):"";return"[object Function]"==t||"[object GeneratorFunction]"==t}(e)}function nr(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ir(e){return!!e&&"object"==typeof e}var or=function(e,t,r,n){var i;e=rr(e)?e:(i=e)?$t(i,function(e){return rr(e)?Wt(e):Zt(e)}(i)):[],r=r&&!n?function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||ir(e)&&"[object Symbol]"==Qt.call(e)}(e))return NaN;if(nr(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=nr(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Nt,"");var r=Ut.test(e);return r||Vt.test(e)?Bt(e.slice(2),r?2:8):Lt.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(r):0;var o=e.length;return r<0&&(r=Xt(o+r,0)),function(e){return"string"==typeof e||!tr(e)&&ir(e)&&"[object String]"==Qt.call(e)}(e)?r<=o&&e.indexOf(t,r)>-1:!!o&&function(e,t,r){if(t!=t)return function(e,t,r,n){for(var i=e.length,o=r+(n?1:-1);n?o--:++o-1},sr=Object.prototype.toString;var ar=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Boolean]"==sr.call(e)},cr=/^\s+|\s+$/g,ur=/^[-+]0x[0-9a-f]+$/i,dr=/^0b[01]+$/i,lr=/^0o[0-7]+$/i,fr=parseInt,pr=Object.prototype.toString;function hr(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var mr=function(e){return"number"==typeof e&&e==function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==pr.call(e)}(e))return NaN;if(hr(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=hr(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(cr,"");var r=dr.test(e);return r||lr.test(e)?fr(e.slice(2),r?2:8):ur.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e)},gr=Object.prototype.toString;var yr=function(e){return"number"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Number]"==gr.call(e)};var wr=Function.prototype,vr=Object.prototype,_r=wr.toString,br=vr.hasOwnProperty,Er=_r.call(Object),Cr=vr.toString,Tr=function(e,t){return function(r){return e(t(r))}}(Object.getPrototypeOf,Object);var Ar=function(e){if(!function(e){return!!e&&"object"==typeof e}(e)||"[object Object]"!=Cr.call(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e))return!1;var t=Tr(e);if(null===t)return!0;var r=br.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&_r.call(r)==Er},xr=Object.prototype.toString,Sr=Array.isArray;var Ir=function(e){return"string"==typeof e||!Sr(e)&&function(e){return!!e&&"object"==typeof e}(e)&&"[object String]"==xr.call(e)},Or=/^\s+|\s+$/g,kr=/^[-+]0x[0-9a-f]+$/i,jr=/^0b[01]+$/i,Rr=/^0o[0-7]+$/i,Pr=parseInt,Dr=Object.prototype.toString;function qr(e,t){var r;if("function"!=typeof t)throw new TypeError("Expected a function");return e=function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==Dr.call(e)}(e))return NaN;if(Nr(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Nr(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Or,"");var r=jr.test(e);return r||Rr.test(e)?Pr(e.slice(2),r?2:8):kr.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function Nr(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var Lr=function(e){return qr(2,e)},Ur=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];Rt&&Ur.splice(3,0,"PS256","PS384","PS512");var Vr={expiresIn:{isValid:function(e){return mr(e)||Ir(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){return mr(e)||Ir(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){return Ir(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:or.bind(null,Ur),message:'"algorithm" must be a valid string enum value'},header:{isValid:Ar,message:'"header" must be an object'},encoding:{isValid:Ir,message:'"encoding" must be a string'},issuer:{isValid:Ir,message:'"issuer" must be a string'},subject:{isValid:Ir,message:'"subject" must be a string'},jwtid:{isValid:Ir,message:'"jwtid" must be a string'},noTimestamp:{isValid:ar,message:'"noTimestamp" must be a boolean'},keyid:{isValid:Ir,message:'"keyid" must be a string'},mutatePayload:{isValid:ar,message:'"mutatePayload" must be a boolean'}},Mr={iat:{isValid:yr,message:'"iat" should be a number of seconds'},exp:{isValid:yr,message:'"exp" should be a number of seconds'},nbf:{isValid:yr,message:'"nbf" should be a number of seconds'}};function Br(e,t,r,n){if(!Ar(r))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach((function(i){var o=e[i];if(o){if(!o.isValid(r[i]))throw new Error(o.message)}else if(!t)throw new Error('"'+i+'" is not allowed in "'+n+'"')}))}var Fr={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},$r=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"],Hr=function(e,t,r,n){var i;if("function"!=typeof r||n||(n=r,r={}),r||(r={}),r=Object.assign({},r),i=n||function(e,t){if(e)throw e;return t},r.clockTimestamp&&"number"!=typeof r.clockTimestamp)return i(new vt("clockTimestamp must be a number"));if(void 0!==r.nonce&&("string"!=typeof r.nonce||""===r.nonce.trim()))return i(new vt("nonce must be a non-empty string"));var o=r.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return i(new vt("jwt must be provided"));if("string"!=typeof e)return i(new vt("jwt must be a string"));var s,a=e.split(".");if(3!==a.length)return i(new vt("jwt malformed"));try{s=yt(e,{complete:!0})}catch(e){return i(e)}if(!s)return i(new vt("invalid token"));var c,u=s.header;if("function"==typeof t){if(!n)return i(new vt("verify must be called asynchronous if secret or public key is provided as a callback"));c=t}else c=function(e,r){return r(null,t)};return c(u,(function(t,n){if(t)return i(new vt("error in secret or public key callback: "+t.message));var c,d=""!==a[2].trim();if(!d&&n)return i(new vt("jwt signature is required"));if(d&&!n)return i(new vt("secret or public key must be provided"));if(d||r.algorithms||(r.algorithms=["none"]),r.algorithms||(r.algorithms=~n.toString().indexOf("BEGIN CERTIFICATE")||~n.toString().indexOf("BEGIN PUBLIC KEY")?Pt:~n.toString().indexOf("BEGIN RSA PUBLIC KEY")?Dt:qt),!~r.algorithms.indexOf(s.header.alg))return i(new vt("invalid algorithm"));try{c=gt.verify(e,s.header.alg,n)}catch(e){return i(e)}if(!c)return i(new vt("invalid signature"));var l=s.payload;if(void 0!==l.nbf&&!r.ignoreNotBefore){if("number"!=typeof l.nbf)return i(new vt("invalid nbf value"));if(l.nbf>o+(r.clockTolerance||0))return i(new bt("jwt not active",new Date(1e3*l.nbf)))}if(void 0!==l.exp&&!r.ignoreExpiration){if("number"!=typeof l.exp)return i(new vt("invalid exp value"));if(o>=l.exp+(r.clockTolerance||0))return i(new Ct("jwt expired",new Date(1e3*l.exp)))}if(r.audience){var f=Array.isArray(r.audience)?r.audience:[r.audience];if(!(Array.isArray(l.aud)?l.aud:[l.aud]).some((function(e){return f.some((function(t){return t instanceof RegExp?t.test(e):t===e}))})))return i(new vt("jwt audience invalid. expected: "+f.join(" or ")))}if(r.issuer&&("string"==typeof r.issuer&&l.iss!==r.issuer||Array.isArray(r.issuer)&&-1===r.issuer.indexOf(l.iss)))return i(new vt("jwt issuer invalid. expected: "+r.issuer));if(r.subject&&l.sub!==r.subject)return i(new vt("jwt subject invalid. expected: "+r.subject));if(r.jwtid&&l.jti!==r.jwtid)return i(new vt("jwt jwtid invalid. expected: "+r.jwtid));if(r.nonce&&l.nonce!==r.nonce)return i(new vt("jwt nonce invalid. expected: "+r.nonce));if(r.maxAge){if("number"!=typeof l.iat)return i(new vt("iat required when maxAge is specified"));var p=kt(r.maxAge,l.iat);if(void 0===p)return i(new vt('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=p+(r.clockTolerance||0))return i(new Ct("maxAge exceeded",new Date(1e3*p)))}if(!0===r.complete){var h=s.signature;return i(null,{header:u,payload:l,signature:h})}return i(null,l)}))},Kr=function(e,t,r,n){"function"==typeof r?(n=r,r={}):r=r||{};var i="object"==typeof e&&!Buffer.isBuffer(e),o=Object.assign({alg:r.algorithm||"HS256",typ:i?"JWT":void 0,kid:r.keyid},r.header);function s(e){if(n)return n(e);throw e}if(!t&&"none"!==r.algorithm)return s(new Error("secretOrPrivateKey must have a value"));if(void 0===e)return s(new Error("payload is required"));if(i){try{!function(e){Br(Mr,!0,e,"payload")}(e)}catch(e){return s(e)}r.mutatePayload||(e=Object.assign({},e))}else{var a=$r.filter((function(e){return void 0!==r[e]}));if(a.length>0)return s(new Error("invalid "+a.join(",")+" option for "+typeof e+" payload"))}if(void 0!==e.exp&&void 0!==r.expiresIn)return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void 0!==e.nbf&&void 0!==r.notBefore)return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){Br(Vr,!1,e,"options")}(r)}catch(e){return s(e)}var c=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:i&&(e.iat=c),void 0!==r.notBefore){try{e.nbf=kt(r.notBefore,c)}catch(e){return s(e)}if(void 0===e.nbf)return s(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void 0!==r.expiresIn&&"object"==typeof e){try{e.exp=kt(r.expiresIn,c)}catch(e){return s(e)}if(void 0===e.exp)return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(Fr).forEach((function(t){var n=Fr[t];if(void 0!==r[t]){if(void 0!==e[n])return s(new Error('Bad "options.'+t+'" option. The payload already has an "'+n+'" property.'));e[n]=r[t]}}));var u=r.encoding||"utf8";if("function"!=typeof n)return gt.sign({header:o,payload:e,secret:t,encoding:u});n=n&&Lr(n),gt.createSign({header:o,privateKey:t,payload:e,encoding:u}).once("error",n).once("done",(function(e){n(null,e)}))};let Gr=[];class zr{constructor(e){this.options=Object.assign({baseUrl:"https://appleid.apple.com",timeout:1e4},e)}async _fetch(e,t){const{baseUrl:r}=this.options;return uniCloud.httpclient.request(r+e,t)}async verifyIdentityToken(e){const t=e.split(".")[0],{kid:r}=JSON.parse(Buffer.from(t,"base64").toString());if(!Gr.length)try{Gr=await this.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}const n=this.getUsedKey(Gr,r);if(!Object.keys(n).length&&!this.fetched)try{Gr=await this.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}let i=null;try{i=Hr(e,function(e,t){var r=Buffer.from(e,"base64"),n=Buffer.from(t,"base64"),i=r.toString("hex"),o=n.toString("hex");i=de(i),o=de(o);var s=i.length/2,a=o.length/2,c=fe(s),u=fe(a),d="30"+fe(s+a+c.length/2+u.length/2+2)+"02"+c+i+"02"+u+o;return"-----BEGIN RSA PUBLIC KEY-----\n"+Buffer.from(d,"hex").toString("base64").match(/.{1,64}/g).join("\n")+"\n-----END RSA PUBLIC KEY-----\n"}(n.n,n.e),{algorithms:n.alg})}catch(e){return{code:10705,msg:e.message}}return{code:0,msg:i}}async getAuthKeys(){const{status:e,data:t}=await this._fetch("/auth/keys",{method:"GET",dataType:"json",timeout:this.options.timeout});if(200!==e)throw new Error("request https://appleid.apple.com/auth/keys fail");return t.keys}getUsedKey(e,t){let r={};for(let n=0;nvoid 0===e))return{code:Q,messageValues:{param:this.t("dcloud-appid")}};const r=await $.doc(e).get(),n=r&&r.data&&r.data[0];if(!n)return{code:10002};const i=Object.keys(z).reduce((e,t)=>{const r=t,i=function(e,t){return t.split(".").reduce((e,t)=>e&&e[t],e)}(n,t);return i&&e.push({[r]:i}),e},[]);let o;const s={dcloud_appid:Zr.in(t),_id:Zr.neq(n._id)},a={dcloud_appid:Zr.exists(!1),_id:Zr.neq(n._id)};switch(i.length){case 0:return{code:10004};case 1:o=Zr.or([Zr.and([i[0],s]),Zr.and([i[0],a])]);break;default:o=Zr.or([Zr.and([Zr.or(i),s]),Zr.and([Zr.or(i),a])])}const c=await $.where(o).limit(1).get();return c&&c.data&&c.data[0]?{code:10005}:{code:0}}const tn=uniCloud.database().command;const rn=uniCloud.database();const nn=uniCloud.database();const on=uniCloud.database();async function sn(e){const t=["apiKey","apiSecret"];for(let r=0,n=t.length;r0){if(0===this._checkPwd(t.data[0],e.oldPassword).code){const{passwordHash:r,version:n}=this.encryptPwd(e.newPassword),i={password:r,token:[]};n&&(i.password_secret_version=n);return A("upRes",await $.doc(t.data[0]._id).update(i)),{code:0,msg:""}}return{code:40202}}return{code:40201}},updateUser:async function(e){const t=e.uid;if(!t)return{code:Q,messageValues:{param:this.t("user-id")}};delete e.uid;const{username:r,email:n}=e,{usernameToLowerCase:i,emailToLowerCase:o}=this._getConfig();let s=r&&r.trim(),a=n&&n.trim();return s&&(i&&(s=s.toLowerCase()),e.username=s),a&&(o&&(a=a.toLowerCase()),e.email=a),A("update -> upRes",await $.doc(t).update(e)),{code:0,msg:""}},banAccount:async function({uid:e}={}){return te.call(this,{uid:e,status:Z})},unbanAccount:async function({uid:e}={}){return te.call(this,{uid:e,status:W})},closeAccount:async function({uid:e}={}){return te.call(this,{uid:e,status:ee})},openAccount:async function({uid:e}={}){return te.call(this,{uid:e,status:W})},_getAlipayApi:function({platform:e}={}){const t=e||this.context.PLATFORM;if(!t)throw new Error(this.t("context-param-required",{param:"PLATFORM"}));const r=this._getConfig(t);if(!r.oauth||!r.oauth.alipay)throw new Error(this.t("config-param-require",{param:t+".alipay"}));return["appid","privateKey"].forEach(e=>{if(!r.oauth.alipay[e])throw new Error(this.t("config-param-require",{param:`${t}.alipay.${e}`}))}),Jr({...r.oauth.alipay,clientType:t})},_getValidInviteCode:async function({inviteCode:e}){let t,r=10;e?(r=1,t=e):t=Wr();let n=!1;try{for(;r>0&&!n;){r--;if(0===(await $.where({my_invite_code:t}).get()).data.length){n=!0;break}t=Wr()}t=Wr()}catch(e){}return n?{code:0,inviteCode:t}:e?{code:80401}:{code:80402}},_addUser:async function(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const n=this._getConfig(),i={...e,dcloud_appid:r?[this.context.APPID]:[],register_date:Date.now(),register_ip:this.context.CLIENTIP},o=(await $.add(i)).id;let s;if(n.removePermissionAndRoleFromToken)s=await this.createToken({uid:o,needPermission:t});else{const t=e.role||[];let r;r=0===t.length||t.includes("admin")?[]:await this._getPermissionListByRoleList(t),s=await this.createToken({uid:o,role:t,permission:r})}const{token:a,tokenExpired:c}=s;return await $.doc(o).update({token:[a]}),{token:a,tokenExpired:c,uid:o,type:"register",userInfo:Object.assign({},i,{token:a})}},_loginExec:async function(e,t={}){if(e.status===Z)return{code:10001};if(e.status===ee)return{code:10006};const r=this._getConfig();let n=e.token||[];"string"==typeof n&&(n=[n]);const i=this._getExpiredToken(n);let o;if(n=n.filter(e=>-1===i.indexOf(e)),r.removePermissionAndRoleFromToken){const r=t.needPermission;o=await this.createToken({uid:e._id,needPermission:r})}else{const t=e.role||[];let r;r=0===t.length||t.includes("admin")?[]:await this._getPermissionListByRoleList(t),o=await this.createToken({uid:e._id,role:t,permission:r})}const{token:s,tokenExpired:a}=o;n.push(s),e.token=n;const c={last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP,token:n,...t.extraData};await $.doc(e._id).update(c);const u=Object.assign({},e,c);return{code:0,msg:"",token:s,uid:u._id,username:u.username,type:"login",userInfo:u,tokenExpired:a}},_registerExec:async function(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const{my_invite_code:n}=e;if(this._getConfig().autoSetInviteCode||n){const t=await this._getValidInviteCode({inviteCode:n});if(t.code)return t;e.my_invite_code=t.inviteCode}return{code:0,msg:"",...await this._addUser(e,{needPermission:t,autoSetDcloudAppid:r})}},_getWeixinApi:function({platform:e}={}){const t=e||this.context.PLATFORM;if(!t)throw new Error(this.t("context-param-required",{param:"PLATFORM"}));const r=this._getConfig(t);if(!r.oauth||!r.oauth.weixin)throw new Error(this.t("config-param-require",{param:t+".weixin"}));return["appid","appsecret"].forEach(e=>{if(!r.oauth.weixin[e])throw new Error(this.t("config-param-require",{param:`${t}.weixin.${e}`}))}),Qr({...r.oauth.weixin,clientType:t})},_getQQApi:function(){const e=this.context.PLATFORM;if(!e)throw new Error(this.t("context-param-required",{param:"PLATFORM"}));const t=this._getConfig(e);if(!t.oauth||!t.oauth.qq)throw new Error(this.t("config-param-require",{param:e+".qq"}));return["appid","appsecret"].forEach(r=>{if(!t.oauth.qq[r])throw new Error(this.t("config-param-require",{param:`${e}.qq.${r}`}))}),Yr({...t.oauth.qq,clientType:e})},_getMatchedUser:function(e,t){if(0===e.length)return{code:10002};let r;const n={},i={};for(let r=e.length-1;r>=0;r--){const o=e[r];for(let s=0;s0?{code:10003,messageValues:{target:"用户"}}:{code:0,msg:"",userMatched:r,fieldMatched:s,isFallbackValueMatched:!!s&&i[s]}},_getCurrentAppUser:function(e){const t=this.context.APPID;return e.filter(e=>void 0===e.dcloud_appid||null===e.dcloud_appid||e.dcloud_appid.indexOf(t)>-1||e.dcloud_appid.indexOf(null)>-1)},_checkLoginUserList:function(e){if(e&&1!==e.length)return e[0].status===ee?{code:10006}:{code:10005}},setAuthorizedAppLogin:async function({uid:e,dcloudAppidList:t}={}){if("array"!==g(t))return{code:Y,messageValues:{param:"dcloudAppidList",reason:this.t("type-array-required",{param:this.t("dcloud-appid-list")})}};if(t&&0!==t.length){const r=await en.bind(this)({uid:e,dcloudAppidList:t});if(r.code)return r}return await $.doc(e).update({dcloud_appid:Zr.set(t)}),{code:0}},authorizeAppLogin:async function({uid:e,dcloudAppid:t}={}){const r=await en.bind(this)({uid:e,dcloudAppidList:[t]});return r.code?r:(await $.doc(e).update({dcloud_appid:Zr.push(t)}),{code:0})},forbidAppLogin:async function({uid:e,dcloudAppid:t}={}){return e?(await $.doc(e).update({dcloud_appid:Zr.pull(t)}),{code:0}):{code:Q,messageValues:{param:this.t("user-id")}}},acceptInvite:async function({uid:e,inviteCode:t}){const r=await $.where({_id:tn.neq(e),inviter_uid:tn.not(tn.all([e])),my_invite_code:t}).get();if(1!==r.data.length)return{code:80501,msg:"邀请码无效"};const n=[r.data[0]._id].concat(r.data[0].inviter_uid||[]),i=await $.doc(e).field({my_invite_code:!0,inviter_uid:!0}).get();if(0===i.data.length)return{code:80502};if(i.data[0].inviter_uid&&i.data[0].inviter_uid.length>0)return{code:80503,msg:"邀请码不可修改"};const o=Date.now();return await $.doc(e).update({inviter_uid:n,invite_time:o}),await $.where({inviter_uid:e}).update({inviter_uid:tn.push(n)}),{code:0,msg:""}},getInvitedUser:async function({uid:e,level:t=1,limit:r=20,offset:n=0,needTotal:i=!1}){const o={code:0,msg:"",invitedUser:(await $.where({["inviter_uid."+(t-1)]:e}).field({_id:!0,username:!0,mobile:!0,invite_time:!0}).orderBy("invite_time","desc").skip(n).limit(r).get()).data};if(i){const r=await $.where({["inviter_uid."+(t-1)]:e}).count();o.total=r.total}return o},setUserInviteCode:async function({uid:e,myInviteCode:t}){const r=await this._getValidInviteCode({inviteCode:t});return r.code?r:(await $.doc(e).update({my_invite_code:r.inviteCode}),{code:0,msg:"",myInviteCode:r.inviteCode})},loginByAlipay:async function(e){"string"==typeof e&&(e={code:e});const{needPermission:t,platform:r,code:n,myInviteCode:i,role:o,type:s}=e,a=r||this.context.PLATFORM,{openid:c}=await this._getAlipayApi({platform:a}).code2Session(n);if(!c)return{code:10501,messageValues:{account:this.t("alipay-account")}};let u=await $.where({ali_openid:c}).get();if(u=this._getCurrentAppUser(u.data),u&&u.length>0){if("register"===s)return{code:10502,messageValues:{type:this.t("alipay-account")}};if(1!==u.length)return{code:10005};const e=u[0],r=await this._loginExec(e,{needPermission:t});if(0!==r.code)return r;const{userInfo:n}=r;return{...r,openid:c,mobileConfirmed:1===n.mobile_confirmed,emailConfirmed:1===n.email_confirmed}}{if("login"===s)return{code:10503,messageValues:{type:this.t("alipay-account")}};const e={ali_openid:c};e.my_invite_code=i,e.role=o;const r=await this._registerExec(e,{needPermission:t});return 0!==r.code?r:{...r,openid:c,mobileConfirmed:!1,emailConfirmed:!1}}},loginByEmail:async function({email:e,code:t,password:r,myInviteCode:n,type:i,needPermission:o,role:s}){if(!(e=e&&e.trim()))return{code:Q,messageValues:{param:"邮箱"}};const{emailToLowerCase:a}=this._getConfig();let c=e;a&&(c=e.toLowerCase());const u=await this.verifyCode({email:c,code:t,type:i||"login"});if(0!==u.code)return u;let d={email:e,email_confirmed:1};const l={field:"email",value:e},f=rn.command;c!==e&&(d=f.or(d,{email:c,email_confirmed:1}),l.fallbackValue=c);let p=await $.where(d).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0){if("register"===i)return{code:10301,messageValues:{type:"邮箱"}};const e=this._getMatchedUser(p,[l]);if(e.code)return e;const{userMatched:t}=e,r=await this._loginExec(t,{needPermission:o});return 0!==r.code?r:{...r,email:c}}{if("login"===i)return{code:10302,messageValues:{type:"邮箱"}};const e={email:c,email_confirmed:1},t=r&&r.trim();if(t){const{passwordHash:r,version:n}=this.encryptPwd(t);e.password=r,n&&(e.password_secret_version=n)}e.my_invite_code=n,e.role=s;const a=await this._registerExec(e,{needPermission:o});return 0!==a.code?a:{...a,email:c}}},loginBySms:async function({mobile:e,code:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){if(!(e=e&&e.trim()))return{code:Q,messageValues:{param:this.t("mobile")}};const c=this._getConfig();if(c.forceInviteCode&&!o)throw new Error(this.t("login-with-invite-type-required"));const u=await this.verifyCode({mobile:e,code:t,type:o||"login"});if(0!==u.code)return u;const d={mobile:e,mobile_confirmed:1};let l=await $.where(d).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0){if("register"===o)return{code:10201,messageValues:{type:this.t("mobile")}};if(1!==l.length)return{code:10005};const t=l[0],r=await this._loginExec(t,{needPermission:s});return 0!==r.code?r:{...r,mobile:e}}{const t=Date.now();if("login"===o)return{code:10202,messageValues:{type:this.t("mobile")}};const u={mobile:e,mobile_confirmed:1,register_ip:this.context.CLIENTIP,register_date:t},d=r&&r.trim();if(d){const{passwordHash:e,version:t}=this.encryptPwd(d);u.password=e,t&&(u.password_secret_version=t)}if(n){const e=await $.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};u.inviter_uid=[e.data[0]._id].concat(e.data[0].inviter_uid||[]),u.invite_time=t}else if(c.forceInviteCode)return{code:10203};u.my_invite_code=i,u.role=a;const l=await this._registerExec(u,{needPermission:s});return 0!==l.code?l:{...l,mobile:e}}},loginByWeixin:async function(e){"string"==typeof e&&(e={code:e});const{needPermission:t,platform:r,code:n,myInviteCode:i,role:o,type:s}=e,a=r||this.context.PLATFORM,c="mp-weixin"===a,{openid:u,unionid:d,sessionKey:l,accessToken:f,refreshToken:p,expired:h}=await this._getWeixinApi({platform:a})[c?"code2Session":"getOauthAccessToken"](n);if(!u)return{code:10401,messageValues:{account:"微信openid"}};let m;m=c?{sessionKey:l}:{accessToken:f,refreshToken:p,accessTokenExpired:h};const g=nn.command,y=[{wx_openid:{[a]:u}}];d&&y.push({wx_unionid:d});let w=await $.where(g.or(...y)).get();if(w=this._getCurrentAppUser(w.data),w&&w.length>0){if("register"===s)return{code:10402,messageValues:{type:this.t("wechat-account")}};if(1!==w.length)return{code:10005};const e=w[0],r={wx_openid:{[a]:u}};d&&(r.wx_unionid=d);const n=await this._loginExec(e,{needPermission:t,extraData:r});if(0!==n.code)return n;const{userInfo:i}=n;return{...n,openid:u,unionid:d,...m,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===s)return{code:10403,messageValues:{type:this.t("wechat-account")}};const e={wx_openid:{[a]:u},wx_unionid:d};e.my_invite_code=i,e.role=o;const r=await this._registerExec(e,{needPermission:t});return 0!==r.code?r:{...r,openid:u,unionid:d,...m,mobileConfirmed:!1,emailConfirmed:!1}}},loginByQQ:async function({code:e,accessToken:t,myInviteCode:r,needPermission:n,role:i,type:o}={}){const s=this.context.PLATFORM,a="mp-qq"===s,{openid:c,unionid:u,sessionKey:d}=await this._getQQApi()[a?"code2Session":"getOpenidByToken"]({code:e,accessToken:t});if(!c)return{code:10801,messageValues:{account:"qq openid"}};const l={accessToken:t,sessionKey:d},f=on.command,p=[{qq_openid:{[s]:c}}];u&&p.push({qq_unionid:u});let h=await $.where(f.or(...p)).get();if(h=this._getCurrentAppUser(h.data),h&&h.length>0){if("register"===o)return{code:10802,messageValues:{type:this.t("qq-account")}};if(1!==h.length)return{code:10005};const e=h[0],t={qq_openid:{[s]:c}};u&&(t.qq_unionid=u);const r=await this._loginExec(e,{needPermission:n,extraData:t});if(0!==r.code)return r;const{userInfo:i}=r;return{...r,openid:c,unionid:u,...l,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===o)return{code:10803,messageValues:{type:this.t("qq-account")}};const e={qq_openid:{[s]:c},qq_unionid:u};e.my_invite_code=r,e.role=i;const t=await this._registerExec(e);return 0!==t.code?t:{...t,openid:c,unionid:u,...l,mobileConfirmed:!1,emailConfirmed:!1}}},loginByUniverify:async function({openid:e,access_token:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){const c=this._getConfig(),u=c&&c.service&&c.service.univerify;if(!u)throw new Error(this.t("uni-verify-config-required"));if(c.forceInviteCode&&!o)throw new Error(this.t("login-with-invite-type-required"));const d=await sn.bind(this)({...u,openid:e,access_token:t});if(0!==d.code)return d;const l=String(d.phoneNumber);let f=await $.where({mobile:l,mobile_confirmed:1}).get();if(f=this._getCurrentAppUser(f.data),f&&f.length>0){if("register"===o)return{code:10601,messageValues:{type:this.t("mobile")}};if(1!==f.length)return{code:10005};const e=f[0],t=await this._loginExec(e,{needPermission:s});return 0!==t.code?t:{...t,mobile:l}}if("login"===o)return{code:10602,messageValues:{type:this.t("mobile")}};const p=Date.now(),h={mobile:l,my_invite_code:i,mobile_confirmed:1,role:a},m=r&&r.trim();if(m){const{passwordHash:e,version:t}=this.encryptPwd(m);h.password=e,t&&(h.password_secret_version=t)}if(n){let e=await $.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};e=e.data[0],h.inviter_uid=[e._id].concat(e.inviter_uid||[]),h.invite_time=p}else if(c.forceInviteCode)return{code:10203};h.my_invite_code=i;const g=await this._registerExec(h,{needPermission:s});return 0!==g.code?g:{...g,mobile:l}},loginByApple:async function({nickName:e,fullName:t,identityToken:r,myInviteCode:n,type:i,needPermission:o,platform:s,role:a}){const c=this._getConfig(),u=c&&c["app-plus"]&&c["app-plus"].oauth&&c["app-plus"].oauth.apple,d=u&&u.bundleId;if(!d)throw new Error(this.t("config-param-require",{param:"app-plus.alipay.bundleId"}));if(!r)return{code:Q,messageValues:{param:"identityToken"}};const l=s||this.context.PLATFORM;t=e||(t&&Object.keys(t).length>0?t.familyName+t.givenName:"");const{code:f,msg:p}=await Xr({clientType:l}).verifyIdentityToken(r);if(0!==f)return{code:f,msg:p,messageValues:{account:this.t("apple-account")}};const{iss:h,sub:m,aud:g,email:y}=p;if("https://appleid.apple.com"!==h)return{code:10706,messageValues:{account:this.t("apple-account")}};if(!m)return{code:10701,messageValues:{account:this.t("apple-account")}};if(d!==g)return{code:10702,messageValues:{account:this.t("apple-account")}};const w=t||"User-"+(y?y.split("@")[0]:Math.random().toString(32).slice(2));let v=await $.where({apple_openid:m}).get();if(v=this._getCurrentAppUser(v.data),v&&v.length>0){if("register"===i)return{code:10703,messageValues:{type:this.t("apple-account")}};if(1!==v.length)return{code:10005};const e=v[0],t=await this._loginExec(e,{needPermission:o});return 0!==t.code?t:{...t,openid:m}}if("login"===i)return{code:10704,messageValues:{type:this.t("apple-account")}};const _={nickname:w,apple_openid:m,my_invite_code:n,role:a},b=await this._registerExec(_,{needPermission:o});return 0!==b.code?b:{...b,openid:m}},login:async function({username:e,password:t,queryField:r=[],needPermission:n}){const i=an.command,o=[];r&&r.length||(r=["username"]),r.length>1&&console.warn(this.t("query-field-warning"));const{usernameToLowerCase:s,emailToLowerCase:a,passwordErrorLimit:c,passwordErrorRetryTime:u}=this._getConfig(),d={email:{email_confirmed:1},mobile:{mobile_confirmed:1}},l={},f=e&&e.trim();if(!f)return{code:Q,messageValues:{param:this.t("username")}};s&&(l.username=f.toLowerCase()),a&&(l.email=f.toLowerCase());const p=[];r.forEach(t=>{o.push({[t]:e,...d[t]});const r={field:t,value:e};"username"===t&&l.username!==e?(o.push({[t]:l.username,...d[t]}),r.fallbackValue=l.username):"email"===t&&l.email!==e&&(o.push({[t]:l.email,...d[t]}),r.fallbackValue=l.email),p.push(r)});let h=await $.where(i.or(...o)).get();h=this._getCurrentAppUser(h.data);const m=this.context.CLIENTIP,g=this._getMatchedUser(h,p);if(g.code)return g;const{userMatched:y}=g;let w=y.login_ip_limit||[];w=w.filter(e=>e.last_error_time>Date.now()-1e3*u);let v=w.find(e=>e.ip===m);if(v&&v.error_times>=c)return{code:10103};const _=t&&t.trim();if(!_)return{code:Q,messageValues:{param:"密码"}};const b=this._checkPwd(y,_);if(0===b.code){const e=w.indexOf(v);e>-1&&w.splice(e,1);const t={login_ip_limit:w},{passwordHash:r,passwordVersion:i}=b;r&&i&&(t.password=r,t.password_secret_version=i);const o=await this._loginExec(y,{needPermission:n,extraData:t});return o.code,o}return v?(v.error_times++,v.last_error_time=Date.now()):(v={ip:m,error_times:1,last_error_time:Date.now()},w.push(v)),await $.doc(y._id).update({login_ip_limit:w}),{code:10102,msg:"密码错误"}},register:async function(e){const t=[],r=[{name:"username",desc:this.t("username")},{name:"email",desc:this.t("email"),extraCond:{email_confirmed:1}},{name:"mobile",desc:this.t("mobile"),extraCond:{mobile_confirmed:1}}],{usernameToLowerCase:n,emailToLowerCase:i}=this._getConfig();r.forEach(r=>{const o=r.name;let s=e[o]&&e[o].trim();s?(("username"===r.name&&n||"email"===r.name&&i)&&(s=s.toLowerCase()),e[o]=s,t.push({[o]:s,...r.extraCond})):delete e[o]});const{username:o,email:s,mobile:a,myInviteCode:c,needPermission:u,autoSetDcloudAppid:d=!0}=e;if("needPermission"in e&&delete e.needPermission,"autoSetDcloudAppid"in e&&delete e.autoSetDcloudAppid,0===t.length)return{code:20101,messageValues:{param:this.t("user-unique-param")}};const l=cn.command;let f=await $.where(l.or(...t)).get();if(f=this._getCurrentAppUser(f.data),f&&f.length>0){const t=f[0];if(t.status===ee)return{code:10006};for(let n=0;nt[e]===i.extraCond[e])),t[i.name]===e[i.name]&&o)return{code:20102,messageValues:{type:i.desc}}}}const p=e.password&&e.password.trim();if(!p)return{code:Q,messageValues:{param:this.t("password")}};const{passwordHash:h,version:m}=this.encryptPwd(p);e.password=h,m&&(e.password_secret_version=m),e.my_invite_code=c,delete e.myInviteCode;const g=await this._registerExec(e,{needPermission:u,autoSetDcloudAppid:d});return 0!==g.code?g:{...g,username:o,email:s,mobile:a}},logout:async function(e){const t=await this.checkToken(e);if(t.code)return t;const r=un.command;return await $.doc(t.uid).update({token:r.pull(e)}),{code:0,msg:""}},getRoleByUid:async function({uid:e}){if(!e)return{code:Q,messageValues:{param:this.t("user-id")}};const t=await $.doc(e).get();return 0===t.data.length?{code:J}:{code:0,msg:"",role:t.data[0].role||[]}},getPermissionByRole:async function({roleID:e}){if(!e)return{code:Q,messageValues:{param:"roleID"}};if("admin"===e){return{code:0,msg:"",permission:(await G.limit(1e3).get()).data.map(e=>e.permission_id)}}const t=await K.where({role_id:e}).get();return 0===t.data.length?{code:X}:{code:0,msg:"",permission:t.data[0].permission||[]}},getPermissionByUid:async function({uid:e}){const t=await $.aggregate().match({_id:e}).project({role:!0}).unwind("$role").lookup({from:"uni-id-roles",localField:"role",foreignField:"role_id",as:"roleDetail"}).unwind("$roleDetail").replaceRoot({newRoot:"$roleDetail"}).end(),r=[];return t.data.forEach(e=>{Array.prototype.push.apply(r,e.permission)}),{code:0,msg:"",permission:S(r)}},bindRole:async function({uid:e,roleList:t,reset:r=!1}){const n={};return"string"==typeof t&&(t=[t]),n.role=r?t:dn.push(t),await $.doc(e).update(n),{code:0,msg:""}},bindPermission:async function({roleID:e,permissionList:t,reset:r=!1}){const n={};return"string"==typeof t&&(t=[t]),n.permission=r?t:dn.push(t),await K.where({role_id:e}).update(n),{code:0,msg:""}},unbindRole:async function({uid:e,roleList:t}){return"string"==typeof t&&(t=[t]),await $.doc(e).update({role:dn.pull(dn.in(t))}),{code:0,msg:""}},unbindPermission:async function({roleID:e,permissionList:t}){return"string"==typeof t&&(t=[t]),await K.where({role_id:e}).update({permission:dn.pull(dn.in(t))}),{code:0,msg:""}},addRole:async function({roleID:e,roleName:t,comment:r,permission:n=[]}){return e?"admin"===e?{code:Y,messageValues:{param:"roleID",reason:this.t("add-role-admin-is-not-allowed")}}:(await K.add({role_id:e,role_name:t,comment:r,permission:n,create_date:Date.now()}),{code:0,msg:""}):{code:Q,messageValues:{param:this.t("role-id")}}},addPermission:async function({permissionID:e,permissionName:t,comment:r}){return e?(await G.add({permission_id:e,permission_name:t,comment:r,create_date:Date.now()}),{code:0,msg:""}):{code:Q,messageValues:{param:this.t("permission-id")}}},getRoleList:async function({limit:e=20,offset:t=0,needTotal:r=!0}){const n={code:0,msg:"",roleList:(await K.skip(t).limit(e).get()).data};if(r){const{total:e}=await K.where({_id:dn.exists(!0)}).count();n.total=e}return n},getRoleInfo:async function(e){const t=await K.where({role_id:e}).get();return 0===t.data.length?{code:X}:{code:0,...t.data[0]}},updateRole:async function({roleID:e,roleName:t,comment:r,permission:n}){return e?(await K.where({role_id:e}).update({role_name:t,comment:r,permission:n}),{code:0,msg:""}):{code:Q,messageValues:{param:this.t("role-id")}}},deleteRole:async function({roleID:e}){const t=g(e);if("string"===t)e=[e];else if("array"!==t)throw new Error("typeof roleID must be array or string");return await K.where({role_id:dn.in(e)}).remove(),await $.where({role:dn.elemMatch(dn.in(e))}).update({role:dn.pullAll(e)}),{code:0,msg:""}},getPermissionList:async function({limit:e=20,offset:t=0,needTotal:r=!0}){const n={code:0,msg:"",permissionList:(await G.skip(t).limit(e).get()).data};if(r){const{total:e}=await G.where({_id:dn.exists(!0)}).count();n.total=e}return n},getPermissionInfo:async function(e){const t=await G.where({permission_id:e}).get();return 0===t.data.length?{code:Q,messageValues:{param:this.t("permission-id")}}:{code:0,...t.data[0]}},updatePermission:async function({permissionID:e,permissionName:t,comment:r}){return e?(await G.where({permission_id:e}).update({permission_name:t,comment:r}),{code:0,msg:""}):{code:Q,messageValues:{param:this.t("permission-id")}}},deletePermission:async function({permissionID:e}){const t=g(e);if("string"===t)e=[e];else if("array"!==t)throw new Error("typeof permissionID must be array or string");return await G.where({permission_id:dn.in(e)}).remove(),await K.where({permission:dn.elemMatch(dn.in(e))}).update({permission:dn.pullAll(e)}),{code:0,msg:""}},bindAlipay:async function({uid:e,code:t,platform:r}){const n=r||this.context.PLATFORM,{openid:i}=await this._getAlipayApi({platform:n}).code2Session(t);if(!i)return{code:60401,messageValues:{account:this.t("alipay-account")}};let o=await $.where({ali_openid:i}).get();return o=this._getCurrentAppUser(o.data),o&&o.length>0?{code:60402,messageValues:{type:this.t("alipay-account")}}:(await $.doc(e).update({ali_openid:i}),{code:0,openid:i,msg:""})},bindEmail:async function({uid:e,email:t,code:r}){if(!(t=t&&t.trim()))return{code:Q,messageValues:{param:"邮箱"}};if(!r)return{code:Q,messageValues:{param:"验证码"}};const{emailToLowerCase:n}=this._getConfig();n&&(t=t.toLowerCase());let i=await $.where({email:t,email_confirmed:1}).get();if(i=this._getCurrentAppUser(i.data),i&&i.length>0)return{code:60201,messageValues:{type:"邮箱"}};if(r){const e=await this.verifyCode({email:t,code:r,type:"bind"});if(0!==e.code)return e}return await $.doc(e).update({email:t,email_confirmed:1}),{code:0,msg:"",email:t}},bindMobile:async function({uid:e,mobile:t,code:r,openid:n,access_token:i,type:o="sms"}){if("univerify"===o){const e=this._getConfig(),r=e&&e.service&&e.service.univerify;if(!r)throw new Error("请在config.json中配置service.univerify下一键登录相关参数");const o=await sn.bind(this)({...r,openid:n,access_token:i});if(0!==o.code)return o;t=""+o.phoneNumber}let s=await $.where({mobile:t,mobile_confirmed:1}).get();if(s=this._getCurrentAppUser(s.data),s&&s.length>0)return{code:60101,messageValues:{type:"手机号"}};if("sms"===o&&r){if(!t)return{code:Q,messageValues:{param:this.t("mobile")}};if(!r)return{code:Q,messageValues:{param:this.t("verify-code")}};const e=await this.verifyCode({mobile:t,code:r,type:"bind"});if(0!==e.code)return e}return await $.doc(e).update({mobile:t,mobile_confirmed:1}),{code:0,msg:"",mobile:t}},bindWeixin:async function({uid:e,code:t,platform:r}){const n=r||this.context.PLATFORM,i="mp-weixin"===n,{openid:o,unionid:s,sessionKey:a,accessToken:c,refreshToken:u,expired:d}=await this._getWeixinApi({platform:n})[i?"code2Session":"getOauthAccessToken"](t);if(!o)return{code:60301,messageValues:{account:"微信openid"}};const l=ln.command,f=[{wx_openid:{[n]:o}}];s&&f.push({wx_unionid:s});let p=await $.where(l.or(...f)).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0)return{code:60302,messageValues:{type:this.t("wechat-account")}};const h={wx_openid:{[n]:o}};let m;return s&&(h.wx_unionid=s),await $.doc(e).update(h),m=i?{sessionKey:a}:{accessToken:c,refreshToken:u,accessTokenExpired:d},{code:0,msg:"",openid:o,unionid:s,...m}},bindQQ:async function({uid:e,code:t,accessToken:r,platform:n}={}){const i=n||this.context.PLATFORM,o="mp-qq"===i,{openid:s,unionid:a,sessionKey:c}=await this._getQQApi()[o?"code2Session":"getOpenidByToken"]({code:t,accessToken:r});if(!s)return{code:60501,messageValues:{account:"qq openid"}};const u=fn.command,d=[{qq_openid:{[i]:s}}];a&&d.push({qq_unionid:a});let l=await $.where(u.or(...d)).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0)return{code:60502,messageValues:{type:this.t("qq-account")}};const f={qq_openid:{[i]:s}};return a&&(f.qq_unionid=a),await $.doc(e).update(f),{code:0,msg:"",openid:s,unionid:a,...{accessToken:r,sessionKey:c}}},unbindAlipay:async function(e){const t=pn.command,r=await $.doc(e).update({ali_openid:t.remove()});return A("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70401}},unbindEmail:async function({uid:e,email:t,code:r}){if(t=t&&t.trim(),!e||!t)return{code:Q,messageValues:{param:e?this.t("email"):this.t("user-id")}};const{emailToLowerCase:n}=this._getConfig();if(r){const e=await this.verifyCode({email:t,code:r,type:"unbind"});if(0!==e.code)return e}const i=hn.command;let o={_id:e,email:t};if(n){const r=t.toLowerCase();r!==t&&(o=i.or(o,{_id:e,email:r}))}return 1===(await $.where(o).update({email:i.remove(),email_confirmed:i.remove()})).updated?{code:0,msg:""}:{code:70201}},unbindMobile:async function({uid:e,mobile:t,code:r}){if(r){const e=await this.verifyCode({mobile:t,code:r,type:"unbind"});if(0!==e.code)return e}const n=mn.command;return 1===(await $.where({_id:e,mobile:t}).update({mobile:n.remove(),mobile_confirmed:n.remove()})).updated?{code:0,msg:""}:{code:70101}},unbindWeixin:async function(e){const t=gn.command,r=await $.doc(e).update({wx_openid:t.remove(),wx_unionid:t.remove()});return A("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70301}},unbindQQ:async function(e){const t=yn.command,r=await $.doc(e).update({qq_openid:t.remove(),qq_unionid:t.remove()});return A("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70501}},code2SessionAlipay:async function(e){let t=e;"string"==typeof e&&(t={code:e});try{const e=t.platform||this.context.PLATFORM,r=await this._getAlipayApi({platform:e}).code2Session(t.code);return r.openid?{code:0,msg:"",...r}:{code:80701,messageValues:{account:this.t("alipay-account")}}}catch(e){return{code:80702,messageValues:{account:this.t("alipay-account")}}}},code2SessionWeixin:async function(e){let t=e;"string"==typeof e&&(t={code:e});try{const e=t.platform||this.context.PLATFORM,r=await this._getWeixinApi({platform:e})["mp-weixin"===e?"code2Session":"getOauthAccessToken"](t.code);return r.openid?{code:0,msg:"",...r}:{code:80601,messageValues:{account:"微信openid"}}}catch(e){return{code:80602,messageValues:{account:"微信openid"}}}},verifyAppleIdentityToken:async function({identityToken:e,platform:t}){const r=t||this.context.PLATFORM,{code:n,msg:i}=await Xr({clientType:r}).verifyIdentityToken(e);return 0!==n?{code:n,msg:i}:{code:n,msg:"验证通过",...i}},wxBizDataCrypt:async function({code:e,sessionKey:t,encryptedData:r,iv:i}){if(!r)return{code:Q,messageValues:{param:"encryptedData"}};if(!i)return{code:Q,messageValues:{param:"iv"}};if(!e&&!t)return{code:Q,messageValues:{param:"sessionKey"}};const o=this._getWeixinApi();if(!t){const r=await o.code2Session(e);if(!r.sessionKey)return{code:80801};t=r.sessionKey}t=Buffer.from(t,"base64"),r=Buffer.from(r,"base64"),i=Buffer.from(i,"base64");try{var s=n.createDecipheriv("aes-128-cbc",t,i);s.setAutoPadding(!0);var a=s.update(r,"binary","utf8");a+=s.final("utf8"),a=JSON.parse(a)}catch(e){return console.error(e),{code:80802}}return a.watermark.appid!==o.options.appId?{code:80803}:{code:0,msg:"",...a}},encryptPwd:function(e,{value:t,version:r}={}){if(!(e=e&&e.trim()))throw new Error(this.t("param-required",{param:this.t("password")}));if(!t){const e=this._getConfig(),{passwordSecret:n}=e;if("array"===g(n)){const e=n.sort((e,t)=>e.version-t.version);t=e[e.length-1].value,r=e[e.length-1].version}else t=n}if(!t)throw new Error(this.t("param-error",{param:"passwordSecret",reason:"invalid passwordSecret"}));const i=n.createHmac("sha1",t.toString("ascii"));return i.update(e),{passwordHash:i.digest("hex"),version:r}},checkToken:async function(e,{needPermission:t,needUserInfo:r=!0}={}){const n=this._getConfig(),i=this._verifyToken(e);if(i.code)return i;const{uid:o,needPermission:s,role:a,permission:c,exp:u}=i,d=a&&c;t=void 0===t?s:t;const l=n.removePermissionAndRoleFromToken||!d||r,f=!n.removePermissionAndRoleFromToken&&!d||n.removePermissionAndRoleFromToken&&d||n.tokenExpiresThreshold&&u-Date.now()/1e3-1===r.indexOf(e)),t.push(e.token),await $.doc(o).update({token:t,last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP}),{...h,...e}}return h},createToken:function({uid:e,needPermission:t,role:r,permission:n}){if(!e)return{code:30101,messageValues:{param:this.t("user-id")}};const i={uid:e,needPermission:t,role:r,permission:n},o=this._getConfig();if(!this.interceptorMap.has("customToken")){const e={...i};return this._createTokenInternal({signContent:e,config:o})}const s=this.interceptorMap.get("customToken");if("function"!=typeof s)throw new Error(this.t("type-function-required","custumToken"));const a=s(i);return a instanceof Promise?a.then(e=>this._createTokenInternal({signContent:e,config:o})):this._createTokenInternal({signContent:a,config:o})},_checkPwd:function(e,t){if(!t)return{code:1};const{password:r,password_secret_version:n}=e,i=this._getConfig(),{passwordSecret:o}=i,s=g(o);if("string"===s){const{passwordHash:e}=this.encryptPwd(t,{value:o});return e===r?{code:0,message:""}:{code:2}}if("array"!==s)throw new Error(this.t("password-secret-type-error"));const a=o.sort((e,t)=>e.version-t.version);let c;if(c=n?a.find(e=>e.version===n):a[0],!c)return{code:3};const u=a[a.length-1],{passwordHash:d}=this.encryptPwd(t,c);if(d===r){const e={code:0};if(c!==u){const{passwordHash:r,version:n}=this.encryptPwd(t,u);e.passwordHash=r,e.passwordVersion=n}return e}return{code:4,message:""}},_verifyToken:function(e){const t=this._getConfig();let r;try{r=Hr(e,t.tokenSecret)}catch(e){return"TokenExpiredError"===e.name?{code:30203,err:e}:{code:30204,err:e}}return t.bindTokenToDevice&&r.clientId&&r.clientId!==this._getClientUaHash()?{code:30201}:{code:0,message:"",...r}},_getExpiredToken:function(e){const t=this._getConfig(),r=[];return e.forEach(e=>{try{Hr(e,t.tokenSecret)}catch(t){r.push(e)}}),r},_getPermissionListByRoleList:async function(e){if(!Array.isArray(e))return[];if(0===e.length)return[];if(e.includes("admin")){return(await G.limit(500).get()).data.map(e=>e.permission_id)}const t=await K.where({role_id:wn.in(e)}).get(),r=[];return t.data.forEach(e=>{Array.prototype.push.apply(r,e.permission)}),S(r)},_getClientUaHash:function(){const e=n.createHash("md5"),t=/MicroMessenger/i.test(this.context.CLIENTUA)?this.context.CLIENTUA.replace(/(MicroMessenger\S+).*/i,"$1"):this.context.CLIENTUA;return e.update(t),e.digest("hex")},_createTokenInternal:function({signContent:e,config:t}){if(t.tokenExpiresIn&&t.tokenExpiresThreshold&&t.tokenExpiresIn<=t.tokenExpiresThreshold)throw new Error(this.t("token-expires-config-warning"));return"object"===g(e)&&e.uid?(t.bindTokenToDevice&&(e.clientId=this._getClientUaHash()),{token:Kr(e,t.tokenSecret,{expiresIn:t.tokenExpiresIn}),tokenExpired:Date.now()+1e3*t.tokenExpiresIn}):{code:30101,messageValues:{param:this.t("user-id")}}},setVerifyCode:async function({mobile:e,email:t,code:r,expiresIn:n,type:i}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50101,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50102,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};r||(r=x()),n||(n=180);const o=Date.now(),s={mobile:e,email:t,type:i,code:r,state:0,ip:this.context.CLIENTIP,created_at:o,expired_at:o+1e3*n};return A("addRes",await H.add(s)),{code:0,mobile:e,email:t}},verifyCode:async function({mobile:e,email:t,code:r,type:n}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50201,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50203,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};const i=vn.command,o=Date.now(),s={mobile:e,email:t,type:n,code:r,state:0,expired_at:i.gt(o)},a=await H.where(s).orderBy("created_at","desc").limit(1).get();if(A("verifyRecord:",a),a&&a.data&&a.data.length>0){const e=a.data[0];return A("upRes",await H.doc(e._id).update({state:1})),{code:0,msg:"验证通过"}}return{code:50202,msg:"验证码错误或已失效"}},sendSmsCode:async function({mobile:e,code:t,type:r,templateId:n}){if(!e)return{code:Q,messageValues:{param:this.t("mobile")}};if(t||(t=x()),!r)return{code:Q,messageValues:{param:this.t("verify-code-type")}};const i=this._getConfig();let o=i&&i.service&&i.service.sms;if(!o)throw new Error(this.t("config-param-required",{param:"service.sms"}));o=Object.assign({codeExpiresIn:300},o);const s=["smsKey","smsSecret"];for(let e=0,t=s.length;e=0?o:{code:0,msg:""}}catch(e){return{code:50301}}}}),bn=he((function(e,t){var r=/^\[object .+?Constructor\]$/,n=/^(?:0|[1-9]\d*)$/,i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1;var o="object"==typeof pe&&pe&&pe.Object===Object&&pe,s="object"==typeof self&&self&&self.Object===Object&&self,a=o||s||Function("return this")(),c=t&&!t.nodeType&&t,u=c&&e&&!e.nodeType&&e,d=u&&u.exports===c,l=d&&o.process,f=function(){try{var e=u&&u.require&&u.require("util").types;return e||l&&l.binding&&l.binding("util")}catch(e){}}(),p=f&&f.isTypedArray;function h(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var m,g=Array.prototype,y=Function.prototype,w=Object.prototype,v=a["__core-js_shared__"],_=y.toString,b=w.hasOwnProperty,E=(m=/[^.]+$/.exec(v&&v.keys&&v.keys.IE_PROTO||""))?"Symbol(src)_1."+m:"",C=w.toString,T=_.call(Object),A=RegExp("^"+_.call(b).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),x=d?a.Buffer:void 0,S=a.Symbol,I=a.Uint8Array,O=x?x.allocUnsafe:void 0,k=function(e,t){return function(r){return e(t(r))}}(Object.getPrototypeOf,Object),j=Object.create,R=w.propertyIsEnumerable,P=g.splice,D=S?S.toStringTag:void 0,q=function(){try{var e=se(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),N=x?x.isBuffer:void 0,L=Math.max,U=Date.now,V=se(a,"Map"),M=se(Object,"create"),B=function(){function e(){}return function(t){if(!ve(t))return{};if(j)return j(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();function F(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},$.prototype.set=function(e,t){var r=this.__data__,n=Y(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},H.prototype.clear=function(){this.size=0,this.__data__={hash:new F,map:new(V||$),string:new F}},H.prototype.delete=function(e){var t=oe(this,e).delete(e);return this.size-=t?1:0,t},H.prototype.get=function(e){return oe(this,e).get(e)},H.prototype.has=function(e){return oe(this,e).has(e)},H.prototype.set=function(e,t){var r=oe(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},K.prototype.clear=function(){this.__data__=new $,this.size=0},K.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},K.prototype.get=function(e){return this.__data__.get(e)},K.prototype.has=function(e){return this.__data__.has(e)},K.prototype.set=function(e,t){var r=this.__data__;if(r instanceof $){var n=r.__data__;if(!V||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new H(n)}return r.set(e,t),this.size=r.size,this};var X,W=function(e,t,r){for(var n=-1,i=Object(e),o=r(e),s=o.length;s--;){var a=o[X?s:++n];if(!1===t(i[a],a,i))break}return e};function Z(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":D&&D in Object(e)?function(e){var t=b.call(e,D),r=e[D];try{e[D]=void 0;var n=!0}catch(e){}var i=C.call(e);n&&(t?e[D]=r:delete e[D]);return i}(e):function(e){return C.call(e)}(e)}function ee(e){return _e(e)&&"[object Arguments]"==Z(e)}function te(e){return!(!ve(e)||function(e){return!!E&&E in e}(e))&&(ye(e)?A:r).test(function(e){if(null!=e){try{return _.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function re(e){if(!ve(e))return function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}(e);var t=ce(e),r=[];for(var n in e)("constructor"!=n||!t&&b.call(e,n))&&r.push(n);return r}function ne(e,t,r,n,i){e!==t&&W(t,(function(o,s){if(i||(i=new K),ve(o))!function(e,t,r,n,i,o,s){var a=ue(e,r),c=ue(t,r),u=s.get(c);if(u)return void z(e,r,u);var d=o?o(a,c,r+"",e,t,s):void 0,l=void 0===d;if(l){var f=he(c),p=!f&&ge(c),h=!f&&!p&&be(c);d=c,f||p||h?he(a)?d=a:_e(m=a)&&me(m)?d=function(e,t){var r=-1,n=e.length;t||(t=Array(n));for(;++r-1&&e%1==0&&e0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(q?function(e,t){return q(e,"toString",{configurable:!0,enumerable:!1,value:(r=t,function(){return r}),writable:!0});var r}:Ae);function le(e,t){return e===t||e!=e&&t!=t}var fe=ee(function(){return arguments}())?ee:function(e){return _e(e)&&b.call(e,"callee")&&!R.call(e,"callee")},he=Array.isArray;function me(e){return null!=e&&we(e.length)&&!ye(e)}var ge=N||function(){return!1};function ye(e){if(!ve(e))return!1;var t=Z(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}function we(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}function ve(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function _e(e){return null!=e&&"object"==typeof e}var be=p?function(e){return function(t){return e(t)}}(p):function(e){return _e(e)&&we(e.length)&&!!i[Z(e)]};function Ee(e){return me(e)?G(e,!0):re(e)}var Ce,Te=(Ce=function(e,t,r){ne(e,t,r)},ie((function(e,t){var r=-1,n=t.length,i=n>1?t[n-1]:void 0,o=n>2?t[2]:void 0;for(i=Ce.length>3&&"function"==typeof i?(n--,i):void 0,o&&function(e,t,r){if(!ve(r))return!1;var n=typeof t;return!!("number"==n?me(r)&&ae(t,r.length):"string"==n&&t in r)&&le(r[t],e)}(t[0],t[1],o)&&(i=n<3?void 0:i,n=1),e=Object(e);++rt||this._getConfigContent()}),Object.defineProperty(this,"context",{get(){const t=e||global.__ctx__||{},r=["CLIENTIP","PLATFORM","APPID","LOCALE"];for(let e=0;ee.dcloudAppid===this.context.APPID)||e.find(e=>e.isDefaultConfig)}_getConfigContent(){if(this.pluginConfig&&this.pluginConfig.hasFile("config.json")){this._hasConfigFile=!0;try{return this._parseConfig(this.pluginConfig.config())}catch(e){return}}const e=r.resolve(__dirname,"config.json");this._hasConfigFile=t.existsSync(e);try{return this._parseConfig(require(e))}catch(e){}}init(e){console.warn("uniID.init has been deprecated, use uniID.createInstance instead"),this.config=e}setInterceptor(e,t){this.interceptorMap.set(e,t)}_getConfig(e){const t=this.config&&0!==Object.keys(this.config).length;if(this._hasConfigFile&&!t)throw new Error(this.t("config-file-invalid"));if(!t)throw new Error(this.t("config-file-not-found"));const r=this._getCurrentAppConfig(this.config),n=Object.assign(r,r[e||this.context.PLATFORM])||{},i=Object.assign({bindTokenToDevice:!1,tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600,usernameToLowerCase:!0,emailToLowerCase:!0},n);return["passwordSecret","tokenSecret","tokenExpiresIn","passwordErrorLimit","passwordErrorRetryTime"].forEach(e=>{if(!i||!i[e])throw new Error(this.t("config-param-required",{param:e}))}),i}}for(const e in _n)Cn.prototype[e]=_n[e];function Tn({context:e,config:t}={}){const r=new Cn({context:e,config:t});return new Proxy(r,{get(e,t){if(t in e&&0!==t.indexOf("_")){if("function"==typeof e[t])return(r=e[t],function(){const e=r.apply(this,arguments);return m(e)?e.then(e=>(j.bind(this)(e),e)):(j.bind(this)(e),e)}).bind(e);if("context"!==t&&"config"!==t)return e[t]}var r}})}Cn.prototype.createInstance=Tn;var An=Tn();module.exports=An; +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("crypto")),r=e(require("buffer")),n=e(require("stream")),i=e(require("util"));const o={PARAM_ERROR:{errCode:"param-error"},PARAM_REQUIRED:{errCode:"param-required"},USER_NOT_EXIST:{errCode:"user-not-exist"},ROLE_NOT_EXIST:{errCode:"role-not-exist"},PERMISSION_NOT_EXIST:{errCode:"permission-not-exist"},MULTI_USER_MATCHED:{errCode:"multi-user-matched"},USER_INFO_ERROR:{errCode:"user-info-error"},USER_ACCOUNT_CONFLICT:{errCode:"user-account-conflict"},USER_ACCOUNT_CLOSED:{errCode:"user-account-closed"},ACCOUNT_ALREADY_REGISTED:{errCode:"account-already-registed"},ACCOUNT_NOT_REGISTED:{errCode:"account-not-registed"},ACCOUNT_already_BOUND:{errCode:"account-already-bound"},UNBIND_FAILED:{errCode:"unbind-failed"},INVALID_INVITE_CODE:{errCode:"invalid-invite-code"},SET_INVITE_CODE_FAILED:{errCode:"set-invite-code-failed"},GET_THIRD_PARTY_ACCOUNT_FAILED:{errCode:"get-third-party-account-failed"}},s={0:{errCode:0,errMsg:""},10001:{errCode:"account-banned"},10002:o.USER_NOT_EXIST,10003:o.MULTI_USER_MATCHED,10004:o.USER_INFO_ERROR,10005:o.USER_ACCOUNT_CONFLICT,10006:o.USER_ACCOUNT_CLOSED,10102:{errCode:"password-error"},10103:{errCode:"password-error-exceed-limit"},10201:o.ACCOUNT_ALREADY_REGISTED,10202:o.ACCOUNT_NOT_REGISTED,10203:o.INVALID_INVITE_CODE,10301:o.ACCOUNT_ALREADY_REGISTED,10302:o.ACCOUNT_NOT_REGISTED,10401:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10402:o.ACCOUNT_ALREADY_REGISTED,10403:o.ACCOUNT_NOT_REGISTED,10501:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10502:o.ACCOUNT_ALREADY_REGISTED,10503:o.ACCOUNT_NOT_REGISTED,10601:o.ACCOUNT_ALREADY_REGISTED,10602:o.ACCOUNT_NOT_REGISTED,10701:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10702:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10703:o.ACCOUNT_ALREADY_REGISTED,10704:o.ACCOUNT_NOT_REGISTED,10705:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10706:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10801:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10802:o.ACCOUNT_ALREADY_REGISTED,10803:o.ACCOUNT_NOT_REGISTED,20101:o.PARAM_REQUIRED,20102:o.ACCOUNT_ALREADY_REGISTED,30101:o.PARAM_REQUIRED,30201:{errCode:"check-device-feature-failed"},30202:{errCode:"token-not-exist"},30203:{errCode:"token-expired"},30204:{errCode:"check-token-failed"},40201:o.USER_NOT_EXIST,40202:{errCode:"invalid-old-password"},50101:o.PARAM_REQUIRED,50102:o.PARAM_ERROR,50201:o.PARAM_REQUIRED,50203:o.PARAM_ERROR,50202:{errCode:"invalid-verify-code"},50301:{errCode:"send-sms-code-failed"},60101:o.ACCOUNT_already_BOUND,60201:o.ACCOUNT_already_BOUND,60301:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60302:o.ACCOUNT_already_BOUND,60401:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60402:o.ACCOUNT_already_BOUND,60501:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60502:o.ACCOUNT_already_BOUND,70101:o.UNBIND_FAILED,70201:o.UNBIND_FAILED,70301:o.UNBIND_FAILED,70401:o.UNBIND_FAILED,70501:o.UNBIND_FAILED,80301:o.USER_NOT_EXIST,80401:o.SET_INVITE_CODE_FAILED,80402:o.SET_INVITE_CODE_FAILED,80501:o.INVALID_INVITE_CODE,80502:o.USER_NOT_EXIST,80503:{errCode:"modify-invite-code-is-not-allowed"},80601:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80602:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80701:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80702:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80801:{errCode:"decrypt-weixin-data-failed"},80802:{errCode:"decrypt-weixin-data-failed"},80803:{errCode:"invalid-weixin-appid"},80804:o.PARAM_REQUIRED,80805:o.PARAM_REQUIRED,80806:o.PARAM_REQUIRED,90001:{errCode:"database-operation-failed"},90002:o.PARAM_REQUIRED,90003:o.PARAM_ERROR,90004:o.USER_NOT_EXIST,90005:o.ROLE_NOT_EXIST,90006:o.PERMISSION_NOT_EXIST};class a extends Error{constructor(e){super(e.message),this.errMsg=e.message||"",Object.defineProperties(this,{message:{get(){return`errCode: ${e.code||""} | errMsg: `+this.errMsg},set(e){this.errMsg=e}}})}}const c=Object.prototype.toString,u=Object.prototype.hasOwnProperty;function d(e,t){return u.call(e,t)}function l(e){return"[object Object]"===c.call(e)}function p(e){return"function"==typeof e}function f(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function h(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}const m=/_(\w)/g,g=/[A-Z]/g;function y(e){return e.replace(m,(e,t)=>t?t.toUpperCase():"")}function w(e){return e.replace(g,e=>"_"+e.toLowerCase())}function v(e,t){let r,n;switch(t){case"snake2camel":n=y,r=m;break;case"camel2snake":n=w,r=g}for(const i in e)if(d(e,i)&&r.test(i)){const r=n(i);e[r]=e[i],delete e[i],l(e[r])?e[r]=v(e[r],t):Array.isArray(e[r])&&(e[r]=e[r].map(e=>v(e,t)))}return e}function _(e){return v(e,"snake2camel")}function b(e){return v(e,"camel2snake")}function E(e){return function(e,t="-"){e=e||new Date;const r=[];return r.push(e.getFullYear()),r.push(("00"+(e.getMonth()+1)).substr(-2)),r.push(("00"+e.getDate()).substr(-2)),r.join(t)}(e=e||new Date)+" "+function(e,t=":"){e=e||new Date;const r=[];return r.push(("00"+e.getHours()).substr(-2)),r.push(("00"+e.getMinutes()).substr(-2)),r.push(("00"+e.getSeconds()).substr(-2)),r.join(t)}(e)}function C(){"development"===process.env.NODE_ENV&&console.log(...arguments)}function T(e=6){let t="";for(let r=0;r-1?"&":"?"}access_token=${t.accessToken}`}return`${e}${r}`}class G{constructor(e){this.options=Object.assign({baseUrl:"https://api.weixin.qq.com",timeout:5e3},e)}async _requestWxOpenapi({name:e,url:t,data:r,options:n}){const i={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};return await H({name:"auth."+e,url:`${this.options.baseUrl}${K(t,r)}`,data:r,options:n,defaultOptions:i})}async code2Session(e){return await this._requestWxOpenapi({name:"code2Session",url:"/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}async getOauthAccessToken(e){const t=await this._requestWxOpenapi({name:"getOauthAccessToken",url:"/sns/oauth2/access_token",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,code:e}});return t.expiresIn&&(t.expired=Date.now()+t.expiresIn),t}}async function z({name:e,url:t,data:r,options:n,defaultOptions:i}){let o;n=Object.assign({},i,n,{data:b(Object.assign({},r))});try{o=await uniCloud.httpclient.request(t,n)}catch(t){return function(e,t){throw new a({code:t.code||-2,message:t.message||e+" fail"})}(e,t)}let s=o.data;const c=o.headers["content-type"];if(!Buffer.isBuffer(s)||0!==c.indexOf("text/plain")&&0!==c.indexOf("application/json"))Buffer.isBuffer(s)&&(s={buffer:s,contentType:c});else try{s=JSON.parse(s.toString())}catch(e){s=s.toString()}return _(function(e,t){if(t.ret||t.error){const r=t.ret||t.error||t.errcode||-2,n=t.msg||t.error_description||t.errmsg||e+" fail";throw new a({code:r,message:n})}return delete t.ret,delete t.msg,delete t.error,delete t.error_description,delete t.errcode,delete t.errmsg,{...t,errMsg:e+" ok",errCode:0}}(e,s||{errCode:-2,errMsg:"Request failed"}))}class Q{constructor(e){this.options=Object.assign({baseUrl:"https://graph.qq.com",timeout:5e3},e)}async _requestQQOpenapi({name:e,url:t,data:r,options:n}){const i={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};var o,s;return await z({name:"auth."+e,url:(o=this.options.baseUrl,s=t,/^https?:/.test(s)?s:o+s),data:r,options:n,defaultOptions:i})}async getOpenidByToken({accessToken:e}={}){const t=await this._requestQQOpenapi({name:"getOpenidByToken",url:"/oauth2.0/me",data:{accessToken:e,unionid:1,fmt:"json"}});if(t.clientId!==this.options.appId)throw new a({code:"APPID_NOT_MATCH",message:"appid not match"});return{openid:t.openid,unionid:t.unionid}}async code2Session({code:e}={}){return await this._requestQQOpenapi({name:"getOpenidByToken",url:"https://api.q.qq.com/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}}const Y={RSA:"RSA-SHA1",RSA2:"RSA-SHA256"};var J={code2Session:{returnValue:{openid:"userId"}}};class X extends class{constructor(e={}){if(!e.appId)throw new Error("appId required");if(!e.privateKey)throw new Error("privateKey required");const t={gateway:"https://openapi.alipay.com/gateway.do",timeout:5e3,charset:"utf-8",version:"1.0",signType:"RSA2",timeOffset:-(new Date).getTimezoneOffset()/60,keyType:"PKCS8"};e.sandbox&&(e.gateway="https://openapi.alipaydev.com/gateway.do"),this.options=Object.assign({},t,e);const r="PKCS8"===this.options.keyType?"PRIVATE KEY":"RSA PRIVATE KEY";this.options.privateKey=this._formatKey(this.options.privateKey,r),this.options.alipayPublicKey&&(this.options.alipayPublicKey=this._formatKey(this.options.alipayPublicKey,"PUBLIC KEY"))}_formatKey(e,t){return`-----BEGIN ${t}-----\n${e}\n-----END ${t}-----`}_formatUrl(e,t){let r=e;const n=["app_id","method","format","charset","sign_type","sign","timestamp","version","notify_url","return_url","auth_token","app_auth_token"];for(const e in t)if(n.indexOf(e)>-1){const n=encodeURIComponent(t[e]);r=`${r}${r.includes("?")?"&":"?"}${e}=${n}`,delete t[e]}return{execParams:t,url:r}}_getSign(e,r){const n=r.bizContent||null;delete r.bizContent;const i=Object.assign({method:e,appId:this.options.appId,charset:this.options.charset,version:this.options.version,signType:this.options.signType,timestamp:E((o=this.options.timeOffset,new Date(Date.now()+6e4*((new Date).getTimezoneOffset()+60*(o||0)))))},r);var o;n&&(i.bizContent=JSON.stringify(b(n)));const s=b(i),a=Object.keys(s).sort().map(e=>{let t=s[e];return"[object String]"!==Array.prototype.toString.call(t)&&(t=JSON.stringify(t)),`${e}=${t}`}).join("&"),c=t.createSign(Y[this.options.signType]).update(a,"utf8").sign(this.options.privateKey,"base64");return Object.assign(s,{sign:c})}async _exec(e,t={},r={}){const n=this._getSign(e,t),{url:i,execParams:o}=this._formatUrl(this.options.gateway,n),{status:s,data:a}=await uniCloud.httpclient.request(i,{method:"POST",data:o,dataType:"text",timeout:this.options.timeout});if(200!==s)throw new Error("request fail");const c=JSON.parse(a),u=e.replace(/\./g,"_")+"_response",d=c[u],l=c.error_response;if(d){if(!r.validateSign||this._checkResponseSign(a,u)){if(!d.code||"10000"===d.code){return{errCode:0,errMsg:d.msg||"",..._(d)}}const e=d.sub_code?`${d.sub_code} ${d.sub_msg}`:""+(d.msg||"unkonwn error");throw new Error(e)}throw new Error("check sign error")}if(l)throw new Error(l.sub_msg||l.msg||"request fail");throw new Error("request fail")}_checkResponseSign(e,r){if(!this.options.alipayPublicKey||""===this.options.alipayPublicKey)return console.warn("options.alipayPublicKey is empty"),!0;if(!e)return!1;const n=this._getSignStr(e,r),i=JSON.parse(e).sign,o=t.createVerify(Y[this.options.signType]);return o.update(n,"utf8"),o.verify(this.options.alipayPublicKey,i,"base64")}_getSignStr(e,t){let r=e.trim();const n=e.indexOf(t+'"'),i=e.lastIndexOf('"sign"');return r=r.substr(n+t.length+1),r=r.substr(0,i),r=r.replace(/^[^{]*{/g,"{"),r=r.replace(/\}([^}]*)$/g,"}"),r}}{constructor(e){super(e),this._protocols=J}async code2Session(e){return await this._exec("alipay.system.oauth.token",{grantType:"authorization_code",code:e})}}function W(e){var t=e[0];return t<"0"||t>"7"?"00"+e:e}function Z(e){var t=e.toString(16);return t.length%2?"0"+t:t}function ee(e){if(e<=127)return Z(e);var t=Z(e);return Z(128+t.length/2)+t}var te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function re(e,t){return e(t={exports:{}},t.exports),t.exports}var ne=re((function(e,t){var n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}})),ie=(ne.Buffer,ne.Buffer);function oe(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=ie.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=ie.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}i.inherits(oe,n),oe.prototype.write=function(e){this.buffer=ie.concat([this.buffer,ie.from(e)]),this.emit("data",e)},oe.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};var se=oe,ae=r.Buffer,ce=r.SlowBuffer,ue=de;function de(e,t){if(!ae.isBuffer(e)||!ae.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(var r=0,n=0;n=128&&--n,n}var ve={derToJose:function(e,t){e=ye(e);var r=me(t),n=r+1,i=e.length,o=0;if(48!==e[o++])throw new Error('Could not find expected "seq"');var s=e[o++];if(129===s&&(s=e[o++]),i-o0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*mt;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ht;case"minutes":case"minute":case"mins":case"min":case"m":return r*ft;case"seconds":case"second":case"secs":case"sec":case"s":return r*pt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=mt)return yt(e,t,mt,"day");if(t>=ht)return yt(e,t,ht,"hour");if(t>=ft)return yt(e,t,ft,"minute");if(t>=pt)return yt(e,t,pt,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=mt)return Math.round(e/mt)+"d";if(t>=ht)return Math.round(e/ht)+"h";if(t>=ft)return Math.round(e/ft)+"m";if(t>=pt)return Math.round(e/pt)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function yt(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var wt=function(e,t){var r=t||Math.floor(Date.now()/1e3);if("string"==typeof e){var n=gt(e);if(void 0===n)return;return Math.floor(r+n/1e3)}return"number"==typeof e?r+e:void 0},vt=re((function(e,t){var r;t=e.exports=G,r="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var n=Number.MAX_SAFE_INTEGER||9007199254740991,i=t.re=[],o=t.src=[],s=0,a=s++;o[a]="0|[1-9]\\d*";var c=s++;o[c]="[0-9]+";var u=s++;o[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var d=s++;o[d]="("+o[a]+")\\.("+o[a]+")\\.("+o[a]+")";var l=s++;o[l]="("+o[c]+")\\.("+o[c]+")\\.("+o[c]+")";var p=s++;o[p]="(?:"+o[a]+"|"+o[u]+")";var f=s++;o[f]="(?:"+o[c]+"|"+o[u]+")";var h=s++;o[h]="(?:-("+o[p]+"(?:\\."+o[p]+")*))";var m=s++;o[m]="(?:-?("+o[f]+"(?:\\."+o[f]+")*))";var g=s++;o[g]="[0-9A-Za-z-]+";var y=s++;o[y]="(?:\\+("+o[g]+"(?:\\."+o[g]+")*))";var w=s++,v="v?"+o[d]+o[h]+"?"+o[y]+"?";o[w]="^"+v+"$";var _="[v=\\s]*"+o[l]+o[m]+"?"+o[y]+"?",b=s++;o[b]="^"+_+"$";var E=s++;o[E]="((?:<|>)?=?)";var C=s++;o[C]=o[c]+"|x|X|\\*";var T=s++;o[T]=o[a]+"|x|X|\\*";var A=s++;o[A]="[v=\\s]*("+o[T]+")(?:\\.("+o[T]+")(?:\\.("+o[T]+")(?:"+o[h]+")?"+o[y]+"?)?)?";var x=s++;o[x]="[v=\\s]*("+o[C]+")(?:\\.("+o[C]+")(?:\\.("+o[C]+")(?:"+o[m]+")?"+o[y]+"?)?)?";var S=s++;o[S]="^"+o[E]+"\\s*"+o[A]+"$";var I=s++;o[I]="^"+o[E]+"\\s*"+o[x]+"$";var O=s++;o[O]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var k=s++;o[k]="(?:~>?)";var j=s++;o[j]="(\\s*)"+o[k]+"\\s+",i[j]=new RegExp(o[j],"g");var R=s++;o[R]="^"+o[k]+o[A]+"$";var P=s++;o[P]="^"+o[k]+o[x]+"$";var D=s++;o[D]="(?:\\^)";var q=s++;o[q]="(\\s*)"+o[D]+"\\s+",i[q]=new RegExp(o[q],"g");var N=s++;o[N]="^"+o[D]+o[A]+"$";var L=s++;o[L]="^"+o[D]+o[x]+"$";var U=s++;o[U]="^"+o[E]+"\\s*("+_+")$|^$";var V=s++;o[V]="^"+o[E]+"\\s*("+v+")$|^$";var M=s++;o[M]="(\\s*)"+o[E]+"\\s*("+_+"|"+o[A]+")",i[M]=new RegExp(o[M],"g");var B=s++;o[B]="^\\s*("+o[A]+")\\s+-\\s+("+o[A]+")\\s*$";var $=s++;o[$]="^\\s*("+o[x]+")\\s+-\\s+("+o[x]+")\\s*$";var F=s++;o[F]="(<|>)?=?\\s*\\*";for(var H=0;H<35;H++)r(H,o[H]),i[H]||(i[H]=new RegExp(o[H]));function K(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof G)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?i[b]:i[w]).test(e))return null;try{return new G(e,t)}catch(e){return null}}function G(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof G){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof G))return new G(e,t);r("SemVer",e,t),this.options=t,this.loose=!!t.loose;var o=e.trim().match(t.loose?i[b]:i[w]);if(!o)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,r,n){"string"==typeof r&&(n=r,r=void 0);try{return new G(e,r).inc(t,n).version}catch(e){return null}},t.diff=function(e,t){if(W(e,t))return null;var r=K(e),n=K(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";var o="prerelease"}for(var s in r)if(("major"===s||"minor"===s||"patch"===s)&&r[s]!==n[s])return i+s;return o},t.compareIdentifiers=Q;var z=/^[0-9]+$/;function Q(e,t){var r=z.test(e),n=z.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e0}function X(e,t,r){return Y(e,t,r)<0}function W(e,t,r){return 0===Y(e,t,r)}function Z(e,t,r){return 0!==Y(e,t,r)}function ee(e,t,r){return Y(e,t,r)>=0}function te(e,t,r){return Y(e,t,r)<=0}function re(e,t,r,n){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return W(e,r,n);case"!=":return Z(e,r,n);case">":return J(e,r,n);case">=":return ee(e,r,n);case"<":return X(e,r,n);case"<=":return te(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}function ne(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof ne){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof ne))return new ne(e,t);r("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ie?this.value="":this.value=this.operator+this.semver.version,r("comp",this)}t.rcompareIdentifiers=function(e,t){return Q(t,e)},t.major=function(e,t){return new G(e,t).major},t.minor=function(e,t){return new G(e,t).minor},t.patch=function(e,t){return new G(e,t).patch},t.compare=Y,t.compareLoose=function(e,t){return Y(e,t,!0)},t.rcompare=function(e,t,r){return Y(t,e,r)},t.sort=function(e,r){return e.sort((function(e,n){return t.compare(e,n,r)}))},t.rsort=function(e,r){return e.sort((function(e,n){return t.rcompare(e,n,r)}))},t.gt=J,t.lt=X,t.eq=W,t.neq=Z,t.gte=ee,t.lte=te,t.cmp=re,t.Comparator=ne;var ie={};function oe(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof oe)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new oe(e.raw,t);if(e instanceof ne)return new oe(e.value,t);if(!(this instanceof oe))return new oe(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function se(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,r,n,i,o,s,a,c,u,d,l,p){return((t=se(r)?"":se(n)?">="+r+".0.0":se(i)?">="+r+"."+n+".0":">="+t)+" "+(a=se(c)?"":se(u)?"<"+(+c+1)+".0.0":se(d)?"<"+c+"."+(+u+1)+".0":l?"<="+c+"."+u+"."+d+"-"+l:"<="+a)).trim()}function ce(e,t,n){for(var i=0;i0){var o=e[i].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}function ue(e,t,r){try{t=new oe(t,r)}catch(e){return!1}return t.test(e)}function de(e,t,r,n){var i,o,s,a,c;switch(e=new G(e,n),t=new oe(t,n),r){case">":i=J,o=te,s=X,a=">",c=">=";break;case"<":i=X,o=ee,s=J,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,n))return!1;for(var u=0;u=0.0.0")),l=l||e,p=p||e,i(e.semver,l.semver,n)?l=e:s(e.semver,p.semver,n)&&(p=e)})),l.operator===a||l.operator===c)return!1;if((!p.operator||p.operator===a)&&o(e,p.semver))return!1;if(p.operator===c&&s(e,p.semver))return!1}return!0}ne.prototype.parse=function(e){var t=this.options.loose?i[U]:i[V],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],"="===this.operator&&(this.operator=""),r[2]?this.semver=new G(r[2],this.options.loose):this.semver=ie},ne.prototype.toString=function(){return this.value},ne.prototype.test=function(e){return r("Comparator.test",e,this.options.loose),this.semver===ie||("string"==typeof e&&(e=new G(e,this.options)),re(e,this.operator,this.semver,this.options))},ne.prototype.intersects=function(e,t){if(!(e instanceof ne))throw new TypeError("a Comparator is required");var r;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return r=new oe(e.value,t),ue(this.value,r,t);if(""===e.operator)return r=new oe(this.value,t),ue(e.semver,r,t);var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),i=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),o=this.semver.version===e.semver.version,s=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=re(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=re(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||i||o&&s||a||c},t.Range=oe,oe.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},oe.prototype.toString=function(){return this.range},oe.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var n=t?i[$]:i[B];e=e.replace(n,ae),r("hyphen replace",e),e=e.replace(i[M],"$1$2$3"),r("comparator trim",e,i[M]),e=(e=(e=e.replace(i[j],"$1~")).replace(i[q],"$1^")).split(/\s+/).join(" ");var o=t?i[U]:i[V],s=e.split(" ").map((function(e){return function(e,t){return r("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){r("caret",e,t);var n=t.loose?i[L]:i[N];return e.replace(n,(function(t,n,i,o,s){var a;return r("caret",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a="0"===n?">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":">="+n+"."+i+".0 <"+(+n+1)+".0.0":s?(r("replaceCaret pr",s),a="0"===n?"0"===i?">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+"-"+s+" <"+(+n+1)+".0.0"):(r("no pr"),a="0"===n?"0"===i?">="+n+"."+i+"."+o+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+" <"+(+n+1)+".0.0"),r("caret return",a),a}))}(e,t)})).join(" ")}(e,t),r("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var n=t.loose?i[P]:i[R];return e.replace(n,(function(t,n,i,o,s){var a;return r("tilde",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":s?(r("replaceTilde pr",s),a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0"):a=">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0",r("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),r("tildes",e),e=function(e,t){return r("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var n=t.loose?i[I]:i[S];return e.replace(n,(function(t,n,i,o,s,a){r("xRange",e,t,n,i,o,s,a);var c=se(i),u=c||se(o),d=u||se(s);return"="===n&&d&&(n=""),c?t=">"===n||"<"===n?"<0.0.0":"*":n&&d?(u&&(o=0),s=0,">"===n?(n=">=",u?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",u?i=+i+1:o=+o+1),t=n+i+"."+o+"."+s):u?t=">="+i+".0.0 <"+(+i+1)+".0.0":d&&(t=">="+i+"."+o+".0 <"+i+"."+(+o+1)+".0"),r("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),r("xrange",e),e=function(e,t){return r("replaceStars",e,t),e.trim().replace(i[F],"")}(e,t),r("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(s=s.filter((function(e){return!!e.match(o)}))),s=s.map((function(e){return new ne(e,this.options)}),this)},oe.prototype.intersects=function(e,t){if(!(e instanceof oe))throw new TypeError("a Range is required");return this.set.some((function(r){return r.every((function(r){return e.set.some((function(e){return e.every((function(e){return r.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new oe(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},oe.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new G(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":r&&!J(r,t)||(r=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(r&&e.test(r))return r;return null},t.validRange=function(e,t){try{return new oe(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,r){return de(e,t,"<",r)},t.gtr=function(e,t,r){return de(e,t,">",r)},t.outside=de,t.prerelease=function(e,t){var r=K(e,t);return r&&r.prerelease.length?r.prerelease:null},t.intersects=function(e,t,r){return e=new oe(e,r),t=new oe(t,r),e.intersects(t)},t.coerce=function(e){if(e instanceof G)return e;if("string"!=typeof e)return null;var t=e.match(i[O]);if(null==t)return null;return K(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}})),_t=(vt.SEMVER_SPEC_VERSION,vt.re,vt.src,vt.parse,vt.valid,vt.clean,vt.SemVer,vt.inc,vt.diff,vt.compareIdentifiers,vt.rcompareIdentifiers,vt.major,vt.minor,vt.patch,vt.compare,vt.compareLoose,vt.rcompare,vt.sort,vt.rsort,vt.gt,vt.lt,vt.eq,vt.neq,vt.gte,vt.lte,vt.cmp,vt.Comparator,vt.Range,vt.toComparators,vt.satisfies,vt.maxSatisfying,vt.minSatisfying,vt.minVersion,vt.validRange,vt.ltr,vt.gtr,vt.outside,vt.prerelease,vt.intersects,vt.coerce,vt.satisfies(process.version,"^6.12.0 || >=8.0.0")),bt=["RS256","RS384","RS512","ES256","ES384","ES512"],Et=["RS256","RS384","RS512"],Ct=["HS256","HS384","HS512"];_t&&(bt.splice(3,0,"PS256","PS384","PS512"),Et.splice(3,0,"PS256","PS384","PS512"));var Tt=/^\s+|\s+$/g,At=/^[-+]0x[0-9a-f]+$/i,xt=/^0b[01]+$/i,St=/^0o[0-7]+$/i,It=/^(?:0|[1-9]\d*)$/,Ot=parseInt;function kt(e){return e!=e}function jt(e,t){return function(e,t){for(var r=-1,n=e?e.length:0,i=Array(n);++r-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}(e.length)&&!function(e){var t=Kt(e)?Nt.call(e):"";return"[object Function]"==t||"[object GeneratorFunction]"==t}(e)}function Kt(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Gt(e){return!!e&&"object"==typeof e}var zt=function(e,t,r,n){var i;e=Ht(e)?e:(i=e)?jt(i,function(e){return Ht(e)?Mt(e):Bt(e)}(i)):[],r=r&&!n?function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||Gt(e)&&"[object Symbol]"==Nt.call(e)}(e))return NaN;if(Kt(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Kt(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Tt,"");var r=xt.test(e);return r||St.test(e)?Ot(e.slice(2),r?2:8):At.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(r):0;var o=e.length;return r<0&&(r=Vt(o+r,0)),function(e){return"string"==typeof e||!Ft(e)&&Gt(e)&&"[object String]"==Nt.call(e)}(e)?r<=o&&e.indexOf(t,r)>-1:!!o&&function(e,t,r){if(t!=t)return function(e,t,r,n){for(var i=e.length,o=r+(n?1:-1);n?o--:++o-1},Qt=Object.prototype.toString;var Yt=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Boolean]"==Qt.call(e)},Jt=/^\s+|\s+$/g,Xt=/^[-+]0x[0-9a-f]+$/i,Wt=/^0b[01]+$/i,Zt=/^0o[0-7]+$/i,er=parseInt,tr=Object.prototype.toString;function rr(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var nr=function(e){return"number"==typeof e&&e==function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==tr.call(e)}(e))return NaN;if(rr(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=rr(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Jt,"");var r=Wt.test(e);return r||Zt.test(e)?er(e.slice(2),r?2:8):Xt.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e)},ir=Object.prototype.toString;var or=function(e){return"number"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Number]"==ir.call(e)};var sr=Function.prototype,ar=Object.prototype,cr=sr.toString,ur=ar.hasOwnProperty,dr=cr.call(Object),lr=ar.toString,pr=function(e,t){return function(r){return e(t(r))}}(Object.getPrototypeOf,Object);var fr=function(e){if(!function(e){return!!e&&"object"==typeof e}(e)||"[object Object]"!=lr.call(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e))return!1;var t=pr(e);if(null===t)return!0;var r=ur.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&cr.call(r)==dr},hr=Object.prototype.toString,mr=Array.isArray;var gr=function(e){return"string"==typeof e||!mr(e)&&function(e){return!!e&&"object"==typeof e}(e)&&"[object String]"==hr.call(e)},yr=/^\s+|\s+$/g,wr=/^[-+]0x[0-9a-f]+$/i,vr=/^0b[01]+$/i,_r=/^0o[0-7]+$/i,br=parseInt,Er=Object.prototype.toString;function Cr(e,t){var r;if("function"!=typeof t)throw new TypeError("Expected a function");return e=function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==Er.call(e)}(e))return NaN;if(Tr(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Tr(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(yr,"");var r=vr.test(e);return r||_r.test(e)?br(e.slice(2),r?2:8):wr.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function Tr(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var Ar=function(e){return Cr(2,e)},xr=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];_t&&xr.splice(3,0,"PS256","PS384","PS512");var Sr={expiresIn:{isValid:function(e){return nr(e)||gr(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){return nr(e)||gr(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){return gr(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:zt.bind(null,xr),message:'"algorithm" must be a valid string enum value'},header:{isValid:fr,message:'"header" must be an object'},encoding:{isValid:gr,message:'"encoding" must be a string'},issuer:{isValid:gr,message:'"issuer" must be a string'},subject:{isValid:gr,message:'"subject" must be a string'},jwtid:{isValid:gr,message:'"jwtid" must be a string'},noTimestamp:{isValid:Yt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:gr,message:'"keyid" must be a string'},mutatePayload:{isValid:Yt,message:'"mutatePayload" must be a boolean'}},Ir={iat:{isValid:or,message:'"iat" should be a number of seconds'},exp:{isValid:or,message:'"exp" should be a number of seconds'},nbf:{isValid:or,message:'"nbf" should be a number of seconds'}};function Or(e,t,r,n){if(!fr(r))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach((function(i){var o=e[i];if(o){if(!o.isValid(r[i]))throw new Error(o.message)}else if(!t)throw new Error('"'+i+'" is not allowed in "'+n+'"')}))}var kr={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},jr=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"],Rr=function(e,t,r,n){var i;if("function"!=typeof r||n||(n=r,r={}),r||(r={}),r=Object.assign({},r),i=n||function(e,t){if(e)throw e;return t},r.clockTimestamp&&"number"!=typeof r.clockTimestamp)return i(new at("clockTimestamp must be a number"));if(void 0!==r.nonce&&("string"!=typeof r.nonce||""===r.nonce.trim()))return i(new at("nonce must be a non-empty string"));var o=r.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return i(new at("jwt must be provided"));if("string"!=typeof e)return i(new at("jwt must be a string"));var s,a=e.split(".");if(3!==a.length)return i(new at("jwt malformed"));try{s=ot(e,{complete:!0})}catch(e){return i(e)}if(!s)return i(new at("invalid token"));var c,u=s.header;if("function"==typeof t){if(!n)return i(new at("verify must be called asynchronous if secret or public key is provided as a callback"));c=t}else c=function(e,r){return r(null,t)};return c(u,(function(t,n){if(t)return i(new at("error in secret or public key callback: "+t.message));var c,d=""!==a[2].trim();if(!d&&n)return i(new at("jwt signature is required"));if(d&&!n)return i(new at("secret or public key must be provided"));if(d||r.algorithms||(r.algorithms=["none"]),r.algorithms||(r.algorithms=~n.toString().indexOf("BEGIN CERTIFICATE")||~n.toString().indexOf("BEGIN PUBLIC KEY")?bt:~n.toString().indexOf("BEGIN RSA PUBLIC KEY")?Et:Ct),!~r.algorithms.indexOf(s.header.alg))return i(new at("invalid algorithm"));try{c=it.verify(e,s.header.alg,n)}catch(e){return i(e)}if(!c)return i(new at("invalid signature"));var l=s.payload;if(void 0!==l.nbf&&!r.ignoreNotBefore){if("number"!=typeof l.nbf)return i(new at("invalid nbf value"));if(l.nbf>o+(r.clockTolerance||0))return i(new ut("jwt not active",new Date(1e3*l.nbf)))}if(void 0!==l.exp&&!r.ignoreExpiration){if("number"!=typeof l.exp)return i(new at("invalid exp value"));if(o>=l.exp+(r.clockTolerance||0))return i(new lt("jwt expired",new Date(1e3*l.exp)))}if(r.audience){var p=Array.isArray(r.audience)?r.audience:[r.audience];if(!(Array.isArray(l.aud)?l.aud:[l.aud]).some((function(e){return p.some((function(t){return t instanceof RegExp?t.test(e):t===e}))})))return i(new at("jwt audience invalid. expected: "+p.join(" or ")))}if(r.issuer&&("string"==typeof r.issuer&&l.iss!==r.issuer||Array.isArray(r.issuer)&&-1===r.issuer.indexOf(l.iss)))return i(new at("jwt issuer invalid. expected: "+r.issuer));if(r.subject&&l.sub!==r.subject)return i(new at("jwt subject invalid. expected: "+r.subject));if(r.jwtid&&l.jti!==r.jwtid)return i(new at("jwt jwtid invalid. expected: "+r.jwtid));if(r.nonce&&l.nonce!==r.nonce)return i(new at("jwt nonce invalid. expected: "+r.nonce));if(r.maxAge){if("number"!=typeof l.iat)return i(new at("iat required when maxAge is specified"));var f=wt(r.maxAge,l.iat);if(void 0===f)return i(new at('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=f+(r.clockTolerance||0))return i(new lt("maxAge exceeded",new Date(1e3*f)))}if(!0===r.complete){var h=s.signature;return i(null,{header:u,payload:l,signature:h})}return i(null,l)}))},Pr=function(e,t,r,n){"function"==typeof r?(n=r,r={}):r=r||{};var i="object"==typeof e&&!Buffer.isBuffer(e),o=Object.assign({alg:r.algorithm||"HS256",typ:i?"JWT":void 0,kid:r.keyid},r.header);function s(e){if(n)return n(e);throw e}if(!t&&"none"!==r.algorithm)return s(new Error("secretOrPrivateKey must have a value"));if(void 0===e)return s(new Error("payload is required"));if(i){try{!function(e){Or(Ir,!0,e,"payload")}(e)}catch(e){return s(e)}r.mutatePayload||(e=Object.assign({},e))}else{var a=jr.filter((function(e){return void 0!==r[e]}));if(a.length>0)return s(new Error("invalid "+a.join(",")+" option for "+typeof e+" payload"))}if(void 0!==e.exp&&void 0!==r.expiresIn)return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void 0!==e.nbf&&void 0!==r.notBefore)return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){Or(Sr,!1,e,"options")}(r)}catch(e){return s(e)}var c=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:i&&(e.iat=c),void 0!==r.notBefore){try{e.nbf=wt(r.notBefore,c)}catch(e){return s(e)}if(void 0===e.nbf)return s(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void 0!==r.expiresIn&&"object"==typeof e){try{e.exp=wt(r.expiresIn,c)}catch(e){return s(e)}if(void 0===e.exp)return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(kr).forEach((function(t){var n=kr[t];if(void 0!==r[t]){if(void 0!==e[n])return s(new Error('Bad "options.'+t+'" option. The payload already has an "'+n+'" property.'));e[n]=r[t]}}));var u=r.encoding||"utf8";if("function"!=typeof n)return it.sign({header:o,payload:e,secret:t,encoding:u});n=n&&Ar(n),it.createSign({header:o,privateKey:t,payload:e,encoding:u}).once("error",n).once("done",(function(e){n(null,e)}))};let Dr=[];class qr{constructor(e){this.options=Object.assign({baseUrl:"https://appleid.apple.com",timeout:1e4},e)}async _fetch(e,t){const{baseUrl:r}=this.options;return uniCloud.httpclient.request(r+e,t)}async verifyIdentityToken(e){const t=e.split(".")[0],{kid:r}=JSON.parse(Buffer.from(t,"base64").toString());if(!Dr.length)try{Dr=await this.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}const n=this.getUsedKey(Dr,r);if(!Object.keys(n).length&&!this.fetched)try{Dr=await this.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}let i=null;try{i=Rr(e,function(e,t){var r=Buffer.from(e,"base64"),n=Buffer.from(t,"base64"),i=r.toString("hex"),o=n.toString("hex");i=W(i),o=W(o);var s=i.length/2,a=o.length/2,c=ee(s),u=ee(a),d="30"+ee(s+a+c.length/2+u.length/2+2)+"02"+c+i+"02"+u+o;return"-----BEGIN RSA PUBLIC KEY-----\n"+Buffer.from(d,"hex").toString("base64").match(/.{1,64}/g).join("\n")+"\n-----END RSA PUBLIC KEY-----\n"}(n.n,n.e),{algorithms:n.alg})}catch(e){return{code:10705,msg:e.message}}return{code:0,msg:i}}async getAuthKeys(){const{status:e,data:t}=await this._fetch("/auth/keys",{method:"GET",dataType:"json",timeout:this.options.timeout});if(200!==e)throw new Error("request https://appleid.apple.com/auth/keys fail");return t.keys}getUsedKey(e,t){let r={};for(let n=0;nvoid 0===e))return{code:N,messageValues:{param:this.t("dcloud-appid")}};const r=await j.doc(e).get(),n=r&&r.data&&r.data[0];if(!n)return{code:10002};const i=Object.keys(q).reduce((e,t)=>{const r=t,i=function(e,t){return t.split(".").reduce((e,t)=>e&&e[t],e)}(n,t);return i&&e.push({[r]:i}),e},[]);let o;const s={dcloud_appid:Br.in(t),_id:Br.neq(n._id)},a={dcloud_appid:Br.exists(!1),_id:Br.neq(n._id)};switch(i.length){case 0:return{code:10004};case 1:o=Br.or([Br.and([i[0],s]),Br.and([i[0],a])]);break;default:o=Br.or([Br.and([Br.or(i),s]),Br.and([Br.or(i),a])])}const c=await j.where(o).limit(1).get();return c&&c.data&&c.data[0]?{code:10005}:{code:0}}const Fr=uniCloud.database().command;const Hr=uniCloud.database();const Kr=uniCloud.database();const Gr=uniCloud.database();async function zr(e){const t=["apiKey","apiSecret"];for(let r=0,n=t.length;r0){if(0===this._checkPwd(t.data[0],e.oldPassword).code){const{passwordHash:r,version:n}=this.encryptPwd(e.newPassword),i={password:r,token:[]};n&&(i.password_secret_version=n);return C("upRes",await j.doc(t.data[0]._id).update(i)),{code:0,msg:""}}return{code:40202}}return{code:40201}},updateUser:async function(e){const t=e.uid;if(!t)return{code:N,messageValues:{param:this.t("user-id")}};delete e.uid;const{username:r,email:n}=e,{usernameToLowerCase:i,emailToLowerCase:o}=this._getConfig();let s=r&&r.trim(),a=n&&n.trim();return s&&(i&&(s=s.toLowerCase()),e.username=s),a&&(o&&(a=a.toLowerCase()),e.email=a),C("update -> upRes",await j.doc(t).update(e)),{code:0,msg:""}},banAccount:async function({uid:e}={}){return F.call(this,{uid:e,status:B})},unbanAccount:async function({uid:e}={}){return F.call(this,{uid:e,status:M})},closeAccount:async function({uid:e}={}){return F.call(this,{uid:e,status:$})},openAccount:async function({uid:e}={}){return F.call(this,{uid:e,status:M})},_getAlipayApi:function(){const e=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.alipay)throw new Error(this.t("config-param-require",{param:e+".alipay"}));return["appid","privateKey"].forEach(r=>{if(!t.oauth.alipay[r])throw new Error(this.t("config-param-require",{param:`${e}.alipay.${r}`}))}),Ur({...t.oauth.alipay})},_getValidInviteCode:async function({inviteCode:e}){let t,r=10;e?(r=1,t=e):t=Mr();let n=!1;try{for(;r>0&&!n;){r--;if(0===(await j.where({my_invite_code:t}).get()).data.length){n=!0;break}t=Mr()}t=Mr()}catch(e){}return n?{code:0,inviteCode:t}:e?{code:80401}:{code:80402}},_addUser:async function(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const n=this._getConfig(),i={...e,dcloud_appid:r?[this.context.APPID]:[],register_date:Date.now(),register_ip:this.context.CLIENTIP},o=(await j.add(i)).id;let s;if(n.removePermissionAndRoleFromToken)s=await this.createToken({uid:o,needPermission:t});else{const t=e.role||[];let r;r=0===t.length||t.includes("admin")?[]:await this._getPermissionListByRoleList(t),s=await this.createToken({uid:o,role:t,permission:r})}const{token:a,tokenExpired:c}=s;return await j.doc(o).update({token:[a]}),{token:a,tokenExpired:c,uid:o,type:"register",userInfo:Object.assign({},i,{token:a})}},_loginExec:async function(e,t={}){if(e.status===B)return{code:10001};if(e.status===$)return{code:10006};const r=this._getConfig();let n=e.token||[];"string"==typeof n&&(n=[n]);const i=this._getExpiredToken(n);let o;if(n=n.filter(e=>-1===i.indexOf(e)),r.removePermissionAndRoleFromToken){const r=t.needPermission;o=await this.createToken({uid:e._id,needPermission:r})}else{const t=e.role||[];let r;r=0===t.length||t.includes("admin")?[]:await this._getPermissionListByRoleList(t),o=await this.createToken({uid:e._id,role:t,permission:r})}const{token:s,tokenExpired:a}=o;n.push(s),e.token=n;const c={last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP,token:n,...t.extraData};await j.doc(e._id).update(c);const u=Object.assign({},e,c);return{code:0,msg:"",token:s,uid:u._id,username:u.username,type:"login",userInfo:u,tokenExpired:a}},_registerExec:async function(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const{my_invite_code:n}=e;if(this._getConfig().autoSetInviteCode||n){const t=await this._getValidInviteCode({inviteCode:n});if(t.code)return t;e.my_invite_code=t.inviteCode}return{code:0,msg:"",...await this._addUser(e,{needPermission:t,autoSetDcloudAppid:r})}},_getWeixinApi:function({platform:e}={}){const t=this.context.PLATFORM,r=this._getConfig();if(!r.oauth||!r.oauth.weixin)throw new Error(this.t("config-param-require",{param:t+".weixin"}));return["appid","appsecret"].forEach(e=>{if(!r.oauth.weixin[e])throw new Error(this.t("config-param-require",{param:`${t}.weixin.${e}`}))}),Nr({...r.oauth.weixin})},_getQQApi:function(){const e=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.qq)throw new Error(this.t("config-param-require",{param:e+".qq"}));return["appid","appsecret"].forEach(r=>{if(!t.oauth.qq[r])throw new Error(this.t("config-param-require",{param:`${e}.qq.${r}`}))}),Lr({...t.oauth.qq})},_getMatchedUser:function(e,t){if(0===e.length)return{code:10002};let r;const n={},i={};for(let r=e.length-1;r>=0;r--){const o=e[r];for(let s=0;s0?{code:10003,messageValues:{target:"用户"}}:{code:0,msg:"",userMatched:r,fieldMatched:s,isFallbackValueMatched:!!s&&i[s]}},_getCurrentAppUser:function(e){const t=this.context.APPID;return e.filter(e=>void 0===e.dcloud_appid||null===e.dcloud_appid||e.dcloud_appid.indexOf(t)>-1||e.dcloud_appid.indexOf(null)>-1)},_checkLoginUserList:function(e){if(e&&1!==e.length)return e[0].status===$?{code:10006}:{code:10005}},setAuthorizedAppLogin:async function({uid:e,dcloudAppidList:t}={}){if("array"!==h(t))return{code:L,messageValues:{param:"dcloudAppidList",reason:this.t("type-array-required",{param:this.t("dcloud-appid-list")})}};if(t&&0!==t.length){const r=await $r.bind(this)({uid:e,dcloudAppidList:t});if(r.code)return r}return await j.doc(e).update({dcloud_appid:Br.set(t)}),{code:0}},authorizeAppLogin:async function({uid:e,dcloudAppid:t}={}){const r=await $r.bind(this)({uid:e,dcloudAppidList:[t]});return r.code?r:(await j.doc(e).update({dcloud_appid:Br.push(t)}),{code:0})},forbidAppLogin:async function({uid:e,dcloudAppid:t}={}){return e?(await j.doc(e).update({dcloud_appid:Br.pull(t)}),{code:0}):{code:N,messageValues:{param:this.t("user-id")}}},acceptInvite:async function({uid:e,inviteCode:t}){const r=await j.where({_id:Fr.neq(e),inviter_uid:Fr.not(Fr.all([e])),my_invite_code:t}).get();if(1!==r.data.length)return{code:80501,msg:"邀请码无效"};const n=[r.data[0]._id].concat(r.data[0].inviter_uid||[]),i=await j.doc(e).field({my_invite_code:!0,inviter_uid:!0}).get();if(0===i.data.length)return{code:80502};if(i.data[0].inviter_uid&&i.data[0].inviter_uid.length>0)return{code:80503,msg:"邀请码不可修改"};const o=Date.now();return await j.doc(e).update({inviter_uid:n,invite_time:o}),await j.where({inviter_uid:e}).update({inviter_uid:Fr.push(n)}),{code:0,msg:""}},getInvitedUser:async function({uid:e,level:t=1,limit:r=20,offset:n=0,needTotal:i=!1}){const o={code:0,msg:"",invitedUser:(await j.where({["inviter_uid."+(t-1)]:e}).field({_id:!0,username:!0,mobile:!0,invite_time:!0}).orderBy("invite_time","desc").skip(n).limit(r).get()).data};if(i){const r=await j.where({["inviter_uid."+(t-1)]:e}).count();o.total=r.total}return o},setUserInviteCode:async function({uid:e,myInviteCode:t}){const r=await this._getValidInviteCode({inviteCode:t});return r.code?r:(await j.doc(e).update({my_invite_code:r.inviteCode}),{code:0,msg:"",myInviteCode:r.inviteCode})},loginByAlipay:async function(e){"string"==typeof e&&(e={code:e});const{needPermission:t,code:r,myInviteCode:n,role:i,type:o}=e,{openid:s}=await this._getAlipayApi().code2Session(r);if(!s)return{code:10501,messageValues:{account:this.t("alipay-account")}};let a=await j.where({ali_openid:s}).get();if(a=this._getCurrentAppUser(a.data),a&&a.length>0){if("register"===o)return{code:10502,messageValues:{type:this.t("alipay-account")}};if(1!==a.length)return{code:10005};const e=a[0],r=await this._loginExec(e,{needPermission:t});if(0!==r.code)return r;const{userInfo:n}=r;return{...r,openid:s,mobileConfirmed:1===n.mobile_confirmed,emailConfirmed:1===n.email_confirmed}}{if("login"===o)return{code:10503,messageValues:{type:this.t("alipay-account")}};const e={ali_openid:s};e.my_invite_code=n,e.role=i;const r=await this._registerExec(e,{needPermission:t});return 0!==r.code?r:{...r,openid:s,mobileConfirmed:!1,emailConfirmed:!1}}},loginByEmail:async function({email:e,code:t,password:r,myInviteCode:n,type:i,needPermission:o,role:s}){if(!(e=e&&e.trim()))return{code:N,messageValues:{param:"邮箱"}};const{emailToLowerCase:a}=this._getConfig();let c=e;a&&(c=e.toLowerCase());const u=await this.verifyCode({email:c,code:t,type:i||"login"});if(0!==u.code)return u;let d={email:e,email_confirmed:1};const l={field:"email",value:e},p=Hr.command;c!==e&&(d=p.or(d,{email:c,email_confirmed:1}),l.fallbackValue=c);let f=await j.where(d).get();if(f=this._getCurrentAppUser(f.data),f&&f.length>0){if("register"===i)return{code:10301,messageValues:{type:"邮箱"}};const e=this._getMatchedUser(f,[l]);if(e.code)return e;const{userMatched:t}=e,r=await this._loginExec(t,{needPermission:o});return 0!==r.code?r:{...r,email:c}}{if("login"===i)return{code:10302,messageValues:{type:"邮箱"}};const e={email:c,email_confirmed:1},t=r&&r.trim();if(t){const{passwordHash:r,version:n}=this.encryptPwd(t);e.password=r,n&&(e.password_secret_version=n)}e.my_invite_code=n,e.role=s;const a=await this._registerExec(e,{needPermission:o});return 0!==a.code?a:{...a,email:c}}},loginBySms:async function({mobile:e,code:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){if(!(e=e&&e.trim()))return{code:N,messageValues:{param:this.t("mobile")}};const c=this._getConfig();if(c.forceInviteCode&&!o)throw new Error(this.t("login-with-invite-type-required"));const u=await this.verifyCode({mobile:e,code:t,type:o||"login"});if(0!==u.code)return u;const d={mobile:e,mobile_confirmed:1};let l=await j.where(d).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0){if("register"===o)return{code:10201,messageValues:{type:this.t("mobile")}};if(1!==l.length)return{code:10005};const t=l[0],r=await this._loginExec(t,{needPermission:s});return 0!==r.code?r:{...r,mobile:e}}{const t=Date.now();if("login"===o)return{code:10202,messageValues:{type:this.t("mobile")}};const u={mobile:e,mobile_confirmed:1,register_ip:this.context.CLIENTIP,register_date:t},d=r&&r.trim();if(d){const{passwordHash:e,version:t}=this.encryptPwd(d);u.password=e,t&&(u.password_secret_version=t)}if(n){const e=await j.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};u.inviter_uid=[e.data[0]._id].concat(e.data[0].inviter_uid||[]),u.invite_time=t}else if(c.forceInviteCode)return{code:10203};u.my_invite_code=i,u.role=a;const l=await this._registerExec(u,{needPermission:s});return 0!==l.code?l:{...l,mobile:e}}},loginByWeixin:async function(e){"string"==typeof e&&(e={code:e});const{needPermission:t,platform:r,code:n,myInviteCode:i,role:o,type:s}=e,a=r||this.context.PLATFORM,c="mp-weixin"===a,{openid:u,unionid:d,sessionKey:l,accessToken:p,refreshToken:f,expired:h}=await this._getWeixinApi()[c?"code2Session":"getOauthAccessToken"](n);if(!u)return{code:10401,messageValues:{account:"微信openid"}};let m;m=c?{sessionKey:l}:{accessToken:p,refreshToken:f,accessTokenExpired:h};const g=Kr.command,y=[{wx_openid:{[a]:u}}];d&&y.push({wx_unionid:d});let w=await j.where(g.or(...y)).get();if(w=this._getCurrentAppUser(w.data),w&&w.length>0){if("register"===s)return{code:10402,messageValues:{type:this.t("wechat-account")}};if(1!==w.length)return{code:10005};const e=w[0],r={wx_openid:{[a]:u}};d&&(r.wx_unionid=d);const n=await this._loginExec(e,{needPermission:t,extraData:r});if(0!==n.code)return n;const{userInfo:i}=n;return{...n,openid:u,unionid:d,...m,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===s)return{code:10403,messageValues:{type:this.t("wechat-account")}};const e={wx_openid:{[a]:u},wx_unionid:d};e.my_invite_code=i,e.role=o;const r=await this._registerExec(e,{needPermission:t});return 0!==r.code?r:{...r,openid:u,unionid:d,...m,mobileConfirmed:!1,emailConfirmed:!1}}},loginByQQ:async function({code:e,accessToken:t,myInviteCode:r,needPermission:n,role:i,type:o}={}){const s=this.context.PLATFORM,a="mp-qq"===s,{openid:c,unionid:u,sessionKey:d}=await this._getQQApi()[a?"code2Session":"getOpenidByToken"]({code:e,accessToken:t});if(!c)return{code:10801,messageValues:{account:"qq openid"}};const l={accessToken:t,sessionKey:d},p=Gr.command,f=[{qq_openid:{[s]:c}}];u&&f.push({qq_unionid:u});let h=await j.where(p.or(...f)).get();if(h=this._getCurrentAppUser(h.data),h&&h.length>0){if("register"===o)return{code:10802,messageValues:{type:this.t("qq-account")}};if(1!==h.length)return{code:10005};const e=h[0],t={qq_openid:{[s]:c}};u&&(t.qq_unionid=u);const r=await this._loginExec(e,{needPermission:n,extraData:t});if(0!==r.code)return r;const{userInfo:i}=r;return{...r,openid:c,unionid:u,...l,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===o)return{code:10803,messageValues:{type:this.t("qq-account")}};const e={qq_openid:{[s]:c},qq_unionid:u};e.my_invite_code=r,e.role=i;const t=await this._registerExec(e);return 0!==t.code?t:{...t,openid:c,unionid:u,...l,mobileConfirmed:!1,emailConfirmed:!1}}},loginByUniverify:async function({openid:e,access_token:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){const c=this._getConfig(),u=c&&c.service&&c.service.univerify;if(!u)throw new Error(this.t("uni-verify-config-required"));if(c.forceInviteCode&&!o)throw new Error(this.t("login-with-invite-type-required"));const d=await zr.bind(this)({...u,openid:e,access_token:t});if(0!==d.code)return d;const l=String(d.phoneNumber);let p=await j.where({mobile:l,mobile_confirmed:1}).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0){if("register"===o)return{code:10601,messageValues:{type:this.t("mobile")}};if(1!==p.length)return{code:10005};const e=p[0],t=await this._loginExec(e,{needPermission:s});return 0!==t.code?t:{...t,mobile:l}}if("login"===o)return{code:10602,messageValues:{type:this.t("mobile")}};const f=Date.now(),h={mobile:l,my_invite_code:i,mobile_confirmed:1,role:a},m=r&&r.trim();if(m){const{passwordHash:e,version:t}=this.encryptPwd(m);h.password=e,t&&(h.password_secret_version=t)}if(n){let e=await j.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};e=e.data[0],h.inviter_uid=[e._id].concat(e.inviter_uid||[]),h.invite_time=f}else if(c.forceInviteCode)return{code:10203};h.my_invite_code=i;const g=await this._registerExec(h,{needPermission:s});return 0!==g.code?g:{...g,mobile:l}},loginByApple:async function({nickName:e,fullName:t,identityToken:r,myInviteCode:n,type:i,needPermission:o,platform:s,role:a}){const c=this._getConfig(),u=c&&c.oauth&&c.oauth.apple,d=u&&u.bundleId;if(!d)throw new Error(this.t("config-param-require",{param:"(app || app-plus).apple.bundleId"}));if(!r)return{code:N,messageValues:{param:"identityToken"}};t=e||(t&&Object.keys(t).length>0?t.familyName+t.givenName:"");const{code:l,msg:p}=await Vr().verifyIdentityToken(r);if(0!==l)return{code:l,msg:p,messageValues:{account:this.t("apple-account")}};const{iss:f,sub:h,aud:m,email:g}=p;if("https://appleid.apple.com"!==f)return{code:10706,messageValues:{account:this.t("apple-account")}};if(!h)return{code:10701,messageValues:{account:this.t("apple-account")}};if(d!==m)return{code:10702,messageValues:{account:this.t("apple-account")}};const y=t||"User-"+(g?g.split("@")[0]:Math.random().toString(32).slice(2));let w=await j.where({apple_openid:h}).get();if(w=this._getCurrentAppUser(w.data),w&&w.length>0){if("register"===i)return{code:10703,messageValues:{type:this.t("apple-account")}};if(1!==w.length)return{code:10005};const e=w[0],t=await this._loginExec(e,{needPermission:o});return 0!==t.code?t:{...t,openid:h}}if("login"===i)return{code:10704,messageValues:{type:this.t("apple-account")}};const v={nickname:y,apple_openid:h,my_invite_code:n,role:a},_=await this._registerExec(v,{needPermission:o});return 0!==_.code?_:{..._,openid:h}},login:async function({username:e,password:t,queryField:r=[],needPermission:n}){const i=Qr.command,o=[];r&&r.length||(r=["username"]),r.length>1&&console.warn(this.t("query-field-warning"));const{usernameToLowerCase:s,emailToLowerCase:a,passwordErrorLimit:c,passwordErrorRetryTime:u}=this._getConfig(),d={email:{email_confirmed:1},mobile:{mobile_confirmed:1}},l={},p=e&&e.trim();if(!p)return{code:N,messageValues:{param:this.t("username")}};s&&(l.username=p.toLowerCase()),a&&(l.email=p.toLowerCase());const f=[];r.forEach(t=>{o.push({[t]:e,...d[t]});const r={field:t,value:e};"username"===t&&l.username!==e?(o.push({[t]:l.username,...d[t]}),r.fallbackValue=l.username):"email"===t&&l.email!==e&&(o.push({[t]:l.email,...d[t]}),r.fallbackValue=l.email),f.push(r)});let h=await j.where(i.or(...o)).get();h=this._getCurrentAppUser(h.data);const m=this.context.CLIENTIP,g=this._getMatchedUser(h,f);if(g.code)return g;const{userMatched:y}=g;let w=y.login_ip_limit||[];w=w.filter(e=>e.last_error_time>Date.now()-1e3*u);let v=w.find(e=>e.ip===m);if(v&&v.error_times>=c)return{code:10103};const _=t&&t.trim();if(!_)return{code:N,messageValues:{param:"密码"}};const b=this._checkPwd(y,_);if(0===b.code){const e=w.indexOf(v);e>-1&&w.splice(e,1);const t={login_ip_limit:w},{passwordHash:r,passwordVersion:i}=b;r&&i&&(t.password=r,t.password_secret_version=i);const o=await this._loginExec(y,{needPermission:n,extraData:t});return o.code,o}return v?(v.error_times++,v.last_error_time=Date.now()):(v={ip:m,error_times:1,last_error_time:Date.now()},w.push(v)),await j.doc(y._id).update({login_ip_limit:w}),{code:10102,msg:"密码错误"}},register:async function(e){const t=[],r=[{name:"username",desc:this.t("username")},{name:"email",desc:this.t("email"),extraCond:{email_confirmed:1}},{name:"mobile",desc:this.t("mobile"),extraCond:{mobile_confirmed:1}}],{usernameToLowerCase:n,emailToLowerCase:i}=this._getConfig();r.forEach(r=>{const o=r.name;let s=e[o]&&e[o].trim();s?(("username"===r.name&&n||"email"===r.name&&i)&&(s=s.toLowerCase()),e[o]=s,t.push({[o]:s,...r.extraCond})):delete e[o]});const{username:o,email:s,mobile:a,myInviteCode:c,needPermission:u,autoSetDcloudAppid:d=!0}=e;if("needPermission"in e&&delete e.needPermission,"autoSetDcloudAppid"in e&&delete e.autoSetDcloudAppid,0===t.length)return{code:20101,messageValues:{param:this.t("user-unique-param")}};const l=Yr.command;let p=await j.where(l.or(...t)).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0){const t=p[0];if(t.status===$)return{code:10006};for(let n=0;nt[e]===i.extraCond[e])),t[i.name]===e[i.name]&&o)return{code:20102,messageValues:{type:i.desc}}}}const f=e.password&&e.password.trim();if(!f)return{code:N,messageValues:{param:this.t("password")}};const{passwordHash:h,version:m}=this.encryptPwd(f);e.password=h,m&&(e.password_secret_version=m),e.my_invite_code=c,delete e.myInviteCode;const g=await this._registerExec(e,{needPermission:u,autoSetDcloudAppid:d});return 0!==g.code?g:{...g,username:o,email:s,mobile:a}},logout:async function(e){const t=await this.checkToken(e);if(t.code)return t;const r=Jr.command;return await j.doc(t.uid).update({token:r.pull(e)}),{code:0,msg:""}},getRoleByUid:async function({uid:e}){if(!e)return{code:N,messageValues:{param:this.t("user-id")}};const t=await j.doc(e).get();return 0===t.data.length?{code:U}:{code:0,msg:"",role:t.data[0].role||[]}},getPermissionByRole:async function({roleID:e}){if(!e)return{code:N,messageValues:{param:"roleID"}};if("admin"===e){return{code:0,msg:"",permission:(await D.limit(1e3).get()).data.map(e=>e.permission_id)}}const t=await P.where({role_id:e}).get();return 0===t.data.length?{code:V}:{code:0,msg:"",permission:t.data[0].permission||[]}},getPermissionByUid:async function({uid:e}){const t=await j.aggregate().match({_id:e}).project({role:!0}).unwind("$role").lookup({from:"uni-id-roles",localField:"role",foreignField:"role_id",as:"roleDetail"}).unwind("$roleDetail").replaceRoot({newRoot:"$roleDetail"}).end(),r=[];return t.data.forEach(e=>{Array.prototype.push.apply(r,e.permission)}),{code:0,msg:"",permission:A(r)}},bindRole:async function({uid:e,roleList:t,reset:r=!1}){const n={};return"string"==typeof t&&(t=[t]),n.role=r?t:Xr.push(t),await j.doc(e).update(n),{code:0,msg:""}},bindPermission:async function({roleID:e,permissionList:t,reset:r=!1}){const n={};return"string"==typeof t&&(t=[t]),n.permission=r?t:Xr.push(t),await P.where({role_id:e}).update(n),{code:0,msg:""}},unbindRole:async function({uid:e,roleList:t}){return"string"==typeof t&&(t=[t]),await j.doc(e).update({role:Xr.pull(Xr.in(t))}),{code:0,msg:""}},unbindPermission:async function({roleID:e,permissionList:t}){return"string"==typeof t&&(t=[t]),await P.where({role_id:e}).update({permission:Xr.pull(Xr.in(t))}),{code:0,msg:""}},addRole:async function({roleID:e,roleName:t,comment:r,permission:n=[]}){return e?"admin"===e?{code:L,messageValues:{param:"roleID",reason:this.t("add-role-admin-is-not-allowed")}}:(await P.add({role_id:e,role_name:t,comment:r,permission:n,create_date:Date.now()}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("role-id")}}},addPermission:async function({permissionID:e,permissionName:t,comment:r}){return e?(await D.add({permission_id:e,permission_name:t,comment:r,create_date:Date.now()}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("permission-id")}}},getRoleList:async function({limit:e=20,offset:t=0,needTotal:r=!0}){const n={code:0,msg:"",roleList:(await P.skip(t).limit(e).get()).data};if(r){const{total:e}=await P.where({_id:Xr.exists(!0)}).count();n.total=e}return n},getRoleInfo:async function(e){const t=await P.where({role_id:e}).get();return 0===t.data.length?{code:V}:{code:0,...t.data[0]}},updateRole:async function({roleID:e,roleName:t,comment:r,permission:n}){return e?(await P.where({role_id:e}).update({role_name:t,comment:r,permission:n}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("role-id")}}},deleteRole:async function({roleID:e}){const t=h(e);if("string"===t)e=[e];else if("array"!==t)throw new Error("typeof roleID must be array or string");return await P.where({role_id:Xr.in(e)}).remove(),await j.where({role:Xr.elemMatch(Xr.in(e))}).update({role:Xr.pullAll(e)}),{code:0,msg:""}},getPermissionList:async function({limit:e=20,offset:t=0,needTotal:r=!0}){const n={code:0,msg:"",permissionList:(await D.skip(t).limit(e).get()).data};if(r){const{total:e}=await D.where({_id:Xr.exists(!0)}).count();n.total=e}return n},getPermissionInfo:async function(e){const t=await D.where({permission_id:e}).get();return 0===t.data.length?{code:N,messageValues:{param:this.t("permission-id")}}:{code:0,...t.data[0]}},updatePermission:async function({permissionID:e,permissionName:t,comment:r}){return e?(await D.where({permission_id:e}).update({permission_name:t,comment:r}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("permission-id")}}},deletePermission:async function({permissionID:e}){const t=h(e);if("string"===t)e=[e];else if("array"!==t)throw new Error("typeof permissionID must be array or string");return await D.where({permission_id:Xr.in(e)}).remove(),await P.where({permission:Xr.elemMatch(Xr.in(e))}).update({permission:Xr.pullAll(e)}),{code:0,msg:""}},bindAlipay:async function({uid:e,code:t,platform:r}){const n=r||this.context.PLATFORM,{openid:i}=await this._getAlipayApi({platform:n}).code2Session(t);if(!i)return{code:60401,messageValues:{account:this.t("alipay-account")}};let o=await j.where({ali_openid:i}).get();return o=this._getCurrentAppUser(o.data),o&&o.length>0?{code:60402,messageValues:{type:this.t("alipay-account")}}:(await j.doc(e).update({ali_openid:i}),{code:0,openid:i,msg:""})},bindEmail:async function({uid:e,email:t,code:r}){if(!(t=t&&t.trim()))return{code:N,messageValues:{param:"邮箱"}};if(!r)return{code:N,messageValues:{param:"验证码"}};const{emailToLowerCase:n}=this._getConfig();n&&(t=t.toLowerCase());let i=await j.where({email:t,email_confirmed:1}).get();if(i=this._getCurrentAppUser(i.data),i&&i.length>0)return{code:60201,messageValues:{type:"邮箱"}};if(r){const e=await this.verifyCode({email:t,code:r,type:"bind"});if(0!==e.code)return e}return await j.doc(e).update({email:t,email_confirmed:1}),{code:0,msg:"",email:t}},bindMobile:async function({uid:e,mobile:t,code:r,openid:n,access_token:i,type:o="sms"}){if("univerify"===o){const e=this._getConfig(),r=e&&e.service&&e.service.univerify;if(!r)throw new Error("请在config.json中配置service.univerify下一键登录相关参数");const o=await zr.bind(this)({...r,openid:n,access_token:i});if(0!==o.code)return o;t=""+o.phoneNumber}let s=await j.where({mobile:t,mobile_confirmed:1}).get();if(s=this._getCurrentAppUser(s.data),s&&s.length>0)return{code:60101,messageValues:{type:"手机号"}};if("sms"===o&&r){if(!t)return{code:N,messageValues:{param:this.t("mobile")}};if(!r)return{code:N,messageValues:{param:this.t("verify-code")}};const e=await this.verifyCode({mobile:t,code:r,type:"bind"});if(0!==e.code)return e}return await j.doc(e).update({mobile:t,mobile_confirmed:1}),{code:0,msg:"",mobile:t}},bindWeixin:async function({uid:e,code:t,platform:r}){const n=r||this.context.PLATFORM,i="mp-weixin"===n,{openid:o,unionid:s,sessionKey:a,accessToken:c,refreshToken:u,expired:d}=await this._getWeixinApi({platform:n})[i?"code2Session":"getOauthAccessToken"](t);if(!o)return{code:60301,messageValues:{account:"微信openid"}};const l=Wr.command,p=[{wx_openid:{[n]:o}}];s&&p.push({wx_unionid:s});let f=await j.where(l.or(...p)).get();if(f=this._getCurrentAppUser(f.data),f&&f.length>0)return{code:60302,messageValues:{type:this.t("wechat-account")}};const h={wx_openid:{[n]:o}};let m;return s&&(h.wx_unionid=s),await j.doc(e).update(h),m=i?{sessionKey:a}:{accessToken:c,refreshToken:u,accessTokenExpired:d},{code:0,msg:"",openid:o,unionid:s,...m}},bindQQ:async function({uid:e,code:t,accessToken:r,platform:n}={}){const i=n||this.context.PLATFORM,o="mp-qq"===i,{openid:s,unionid:a,sessionKey:c}=await this._getQQApi()[o?"code2Session":"getOpenidByToken"]({code:t,accessToken:r});if(!s)return{code:60501,messageValues:{account:"qq openid"}};const u=Zr.command,d=[{qq_openid:{[i]:s}}];a&&d.push({qq_unionid:a});let l=await j.where(u.or(...d)).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0)return{code:60502,messageValues:{type:this.t("qq-account")}};const p={qq_openid:{[i]:s}};return a&&(p.qq_unionid=a),await j.doc(e).update(p),{code:0,msg:"",openid:s,unionid:a,...{accessToken:r,sessionKey:c}}},unbindAlipay:async function(e){const t=en.command,r=await j.doc(e).update({ali_openid:t.remove()});return C("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70401}},unbindEmail:async function({uid:e,email:t,code:r}){if(t=t&&t.trim(),!e||!t)return{code:N,messageValues:{param:e?this.t("email"):this.t("user-id")}};const{emailToLowerCase:n}=this._getConfig();if(r){const e=await this.verifyCode({email:t,code:r,type:"unbind"});if(0!==e.code)return e}const i=tn.command;let o={_id:e,email:t};if(n){const r=t.toLowerCase();r!==t&&(o=i.or(o,{_id:e,email:r}))}return 1===(await j.where(o).update({email:i.remove(),email_confirmed:i.remove()})).updated?{code:0,msg:""}:{code:70201}},unbindMobile:async function({uid:e,mobile:t,code:r}){if(r){const e=await this.verifyCode({mobile:t,code:r,type:"unbind"});if(0!==e.code)return e}const n=rn.command;return 1===(await j.where({_id:e,mobile:t}).update({mobile:n.remove(),mobile_confirmed:n.remove()})).updated?{code:0,msg:""}:{code:70101}},unbindWeixin:async function(e){const t=nn.command,r=await j.doc(e).update({wx_openid:t.remove(),wx_unionid:t.remove()});return C("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70301}},unbindQQ:async function(e){const t=on.command,r=await j.doc(e).update({qq_openid:t.remove(),qq_unionid:t.remove()});return C("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70501}},code2SessionAlipay:async function(e){let t=e;"string"==typeof e&&(t={code:e});try{const e=t.platform||this.context.PLATFORM,r=await this._getAlipayApi({platform:e}).code2Session(t.code);return r.openid?{code:0,msg:"",...r}:{code:80701,messageValues:{account:this.t("alipay-account")}}}catch(e){return{code:80702,messageValues:{account:this.t("alipay-account")}}}},code2SessionWeixin:async function(e){let t=e;"string"==typeof e&&(t={code:e});try{const e=t.platform||this.context.PLATFORM,r=await this._getWeixinApi({platform:e})["mp-weixin"===e?"code2Session":"getOauthAccessToken"](t.code);return r.openid?{code:0,msg:"",...r}:{code:80601,messageValues:{account:"微信openid"}}}catch(e){return{code:80602,messageValues:{account:"微信openid"}}}},verifyAppleIdentityToken:async function({identityToken:e,platform:t}){const r=t||this.context.PLATFORM,{code:n,msg:i}=await Vr({clientType:r}).verifyIdentityToken(e);return 0!==n?{code:n,msg:i}:{code:n,msg:"验证通过",...i}},wxBizDataCrypt:async function({code:e,sessionKey:r,encryptedData:n,iv:i}){if(!n)return{code:N,messageValues:{param:"encryptedData"}};if(!i)return{code:N,messageValues:{param:"iv"}};if(!e&&!r)return{code:N,messageValues:{param:"sessionKey"}};const o=this._getWeixinApi();if(!r){const t=await o.code2Session(e);if(!t.sessionKey)return{code:80801};r=t.sessionKey}r=Buffer.from(r,"base64"),n=Buffer.from(n,"base64"),i=Buffer.from(i,"base64");try{var s=t.createDecipheriv("aes-128-cbc",r,i);s.setAutoPadding(!0);var a=s.update(n,"binary","utf8");a+=s.final("utf8"),a=JSON.parse(a)}catch(e){return console.error(e),{code:80802}}return a.watermark.appid!==o.options.appId?{code:80803}:{code:0,msg:"",...a}},encryptPwd:function(e,{value:r,version:n}={}){if(!(e=e&&e.trim()))throw new Error(this.t("param-required",{param:this.t("password")}));if(!r){const e=this._getConfig(),{passwordSecret:t}=e;if("array"===h(t)){const e=t.sort((e,t)=>e.version-t.version);r=e[e.length-1].value,n=e[e.length-1].version}else r=t}if(!r)throw new Error(this.t("param-error",{param:"passwordSecret",reason:"invalid passwordSecret"}));const i=t.createHmac("sha1",r.toString("ascii"));return i.update(e),{passwordHash:i.digest("hex"),version:n}},checkToken:async function(e,{needPermission:t,needUserInfo:r=!0}={}){const n=this._getConfig(),i=this._verifyToken(e);if(i.code)return i;const{uid:o,needPermission:s,role:a,permission:c,exp:u,iat:d,...l}=i,p=a&&c;t=void 0===t?s:t;const f=n.removePermissionAndRoleFromToken||!p||r,h=!n.removePermissionAndRoleFromToken&&!p||n.removePermissionAndRoleFromToken&&p||n.tokenExpiresThreshold&&u-Date.now()/1e3-1===r.indexOf(e)),t.push(e.token),await j.doc(o).update({token:t,last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP}),{...g,...e}}return g},createToken:function({uid:e,needPermission:t,role:r,permission:n}){if(!e)return{code:30101,messageValues:{param:this.t("user-id")}};const i={uid:e,cid:this.context.CLIENTID||void 0,needPermission:t,role:r,permission:n},o=this._getConfig();if(!this.interceptorMap.has("customToken")){const e={...i};return this._createTokenInternal({signContent:e,config:o})}const s=this.interceptorMap.get("customToken");if("function"!=typeof s)throw new Error(this.t("type-function-required","customToken"));const a=s(i);return a instanceof Promise?a.then(e=>this._createTokenInternal({signContent:e,config:o})):this._createTokenInternal({signContent:a,config:o})},_checkPwd:function(e,t){if(!t)return{code:1};const{password:r,password_secret_version:n}=e,i=this._getConfig(),{passwordSecret:o}=i,s=h(o);if("string"===s){const{passwordHash:e}=this.encryptPwd(t,{value:o});return e===r?{code:0,message:""}:{code:2}}if("array"!==s)throw new Error(this.t("password-secret-type-error"));const a=o.sort((e,t)=>e.version-t.version);let c;if(c=n?a.find(e=>e.version===n):a[0],!c)return{code:3};const u=a[a.length-1],{passwordHash:d}=this.encryptPwd(t,c);if(d===r){const e={code:0};if(c!==u){const{passwordHash:r,version:n}=this.encryptPwd(t,u);e.passwordHash=r,e.passwordVersion=n}return e}return{code:4,message:""}},_verifyToken:function(e){const t=this._getConfig();let r;try{r=Rr(e,t.tokenSecret)}catch(e){return"TokenExpiredError"===e.name?{code:30203,err:e}:{code:30204,err:e}}return t.bindTokenToDevice&&r.clientId&&r.clientId!==this._getClientUaHash()?{code:30201}:{code:0,message:"",...r}},_getExpiredToken:function(e){const t=this._getConfig(),r=[];return e.forEach(e=>{try{Rr(e,t.tokenSecret)}catch(t){r.push(e)}}),r},_getPermissionListByRoleList:async function(e){if(!Array.isArray(e))return[];if(0===e.length)return[];if(e.includes("admin")){return(await D.limit(500).get()).data.map(e=>e.permission_id)}const t=await P.where({role_id:sn.in(e)}).get(),r=[];return t.data.forEach(e=>{Array.prototype.push.apply(r,e.permission)}),A(r)},_getClientUaHash:function(){const e=t.createHash("md5"),r=/MicroMessenger/i.test(this.context.CLIENTUA)?this.context.CLIENTUA.replace(/(MicroMessenger\S+).*/i,"$1"):this.context.CLIENTUA;return e.update(r),e.digest("hex")},_createTokenInternal:function({signContent:e,config:t}){if(t.tokenExpiresIn&&t.tokenExpiresThreshold&&t.tokenExpiresIn<=t.tokenExpiresThreshold)throw new Error(this.t("token-expires-config-warning"));return"object"===h(e)&&e.uid?(t.bindTokenToDevice&&(e.clientId=this._getClientUaHash()),{token:Pr(e,t.tokenSecret,{expiresIn:t.tokenExpiresIn}),tokenExpired:Date.now()+1e3*t.tokenExpiresIn}):{code:30101,messageValues:{param:this.t("user-id")}}},setVerifyCode:async function({mobile:e,email:t,code:r,expiresIn:n,type:i}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50101,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50102,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};r||(r=T()),n||(n=180);const o=Date.now(),s={mobile:e,email:t,type:i,code:r,state:0,ip:this.context.CLIENTIP,created_at:o,expired_at:o+1e3*n};return C("addRes",await R.add(s)),{code:0,mobile:e,email:t}},verifyCode:async function({mobile:e,email:t,code:r,type:n}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50201,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50203,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};const i=an.command,o=Date.now(),s={mobile:e,email:t,type:n,code:r,state:0,expired_at:i.gt(o)},a=await R.where(s).orderBy("created_at","desc").limit(1).get();if(C("verifyRecord:",a),a&&a.data&&a.data.length>0){const e=a.data[0];return C("upRes",await R.doc(e._id).update({state:1})),{code:0,msg:"验证通过"}}return{code:50202,msg:"验证码错误或已失效"}},sendSmsCode:async function({mobile:e,code:t,type:r,templateId:n}){if(!e)return{code:N,messageValues:{param:this.t("mobile")}};if(t||(t=T()),!r)return{code:N,messageValues:{param:this.t("verify-code-type")}};const i=this._getConfig();let o=i&&i.service&&i.service.sms;if(!o)throw new Error(this.t("config-param-required",{param:"service.sms"}));o=Object.assign({codeExpiresIn:300},o);const s=["smsKey","smsSecret"];for(let e=0,t=s.length;e=0?o:{code:0,msg:""}}catch(e){return{code:50301}}}}),un=re((function(e,t){var r=/^\[object .+?Constructor\]$/,n=/^(?:0|[1-9]\d*)$/,i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1;var o="object"==typeof te&&te&&te.Object===Object&&te,s="object"==typeof self&&self&&self.Object===Object&&self,a=o||s||Function("return this")(),c=t&&!t.nodeType&&t,u=c&&e&&!e.nodeType&&e,d=u&&u.exports===c,l=d&&o.process,p=function(){try{var e=u&&u.require&&u.require("util").types;return e||l&&l.binding&&l.binding("util")}catch(e){}}(),f=p&&p.isTypedArray;function h(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var m,g=Array.prototype,y=Function.prototype,w=Object.prototype,v=a["__core-js_shared__"],_=y.toString,b=w.hasOwnProperty,E=(m=/[^.]+$/.exec(v&&v.keys&&v.keys.IE_PROTO||""))?"Symbol(src)_1."+m:"",C=w.toString,T=_.call(Object),A=RegExp("^"+_.call(b).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),x=d?a.Buffer:void 0,S=a.Symbol,I=a.Uint8Array,O=x?x.allocUnsafe:void 0,k=function(e,t){return function(r){return e(t(r))}}(Object.getPrototypeOf,Object),j=Object.create,R=w.propertyIsEnumerable,P=g.splice,D=S?S.toStringTag:void 0,q=function(){try{var e=ae(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),N=x?x.isBuffer:void 0,L=Math.max,U=Date.now,V=ae(a,"Map"),M=ae(Object,"create"),B=function(){function e(){}return function(t){if(!ve(t))return{};if(j)return j(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();function $(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1},F.prototype.set=function(e,t){var r=this.__data__,n=Y(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},H.prototype.clear=function(){this.size=0,this.__data__={hash:new $,map:new(V||F),string:new $}},H.prototype.delete=function(e){var t=se(this,e).delete(e);return this.size-=t?1:0,t},H.prototype.get=function(e){return se(this,e).get(e)},H.prototype.has=function(e){return se(this,e).has(e)},H.prototype.set=function(e,t){var r=se(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},K.prototype.clear=function(){this.__data__=new F,this.size=0},K.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},K.prototype.get=function(e){return this.__data__.get(e)},K.prototype.has=function(e){return this.__data__.has(e)},K.prototype.set=function(e,t){var r=this.__data__;if(r instanceof F){var n=r.__data__;if(!V||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new H(n)}return r.set(e,t),this.size=r.size,this};var X,W=function(e,t,r){for(var n=-1,i=Object(e),o=r(e),s=o.length;s--;){var a=o[X?s:++n];if(!1===t(i[a],a,i))break}return e};function Z(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":D&&D in Object(e)?function(e){var t=b.call(e,D),r=e[D];try{e[D]=void 0;var n=!0}catch(e){}var i=C.call(e);n&&(t?e[D]=r:delete e[D]);return i}(e):function(e){return C.call(e)}(e)}function ee(e){return _e(e)&&"[object Arguments]"==Z(e)}function re(e){return!(!ve(e)||function(e){return!!E&&E in e}(e))&&(ye(e)?A:r).test(function(e){if(null!=e){try{return _.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function ne(e){if(!ve(e))return function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}(e);var t=ue(e),r=[];for(var n in e)("constructor"!=n||!t&&b.call(e,n))&&r.push(n);return r}function ie(e,t,r,n,i){e!==t&&W(t,(function(o,s){if(i||(i=new K),ve(o))!function(e,t,r,n,i,o,s){var a=de(e,r),c=de(t,r),u=s.get(c);if(u)return void z(e,r,u);var d=o?o(a,c,r+"",e,t,s):void 0,l=void 0===d;if(l){var p=he(c),f=!p&&ge(c),h=!p&&!f&&be(c);d=c,p||f||h?he(a)?d=a:_e(m=a)&&me(m)?d=function(e,t){var r=-1,n=e.length;t||(t=Array(n));for(;++r-1&&e%1==0&&e0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(q?function(e,t){return q(e,"toString",{configurable:!0,enumerable:!1,value:(r=t,function(){return r}),writable:!0});var r}:Ae);function pe(e,t){return e===t||e!=e&&t!=t}var fe=ee(function(){return arguments}())?ee:function(e){return _e(e)&&b.call(e,"callee")&&!R.call(e,"callee")},he=Array.isArray;function me(e){return null!=e&&we(e.length)&&!ye(e)}var ge=N||function(){return!1};function ye(e){if(!ve(e))return!1;var t=Z(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}function we(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}function ve(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function _e(e){return null!=e&&"object"==typeof e}var be=f?function(e){return function(t){return e(t)}}(f):function(e){return _e(e)&&we(e.length)&&!!i[Z(e)]};function Ee(e){return me(e)?G(e,!0):ne(e)}var Ce,Te=(Ce=function(e,t,r){ie(e,t,r)},oe((function(e,t){var r=-1,n=t.length,i=n>1?t[n-1]:void 0,o=n>2?t[2]:void 0;for(i=Ce.length>3&&"function"==typeof i?(n--,i):void 0,o&&function(e,t,r){if(!ve(r))return!1;var n=typeof t;return!!("number"==n?me(r)&&ce(t,r.length):"string"==n&&t in r)&&pe(r[t],e)}(t[0],t[1],o)&&(i=n<3?void 0:i,n=1),e=Object(e);++re.dcloudAppid===t)||e.find(e=>e.isDefaultConfig):e}_getConfigContent(){if(this.pluginConfig&&this.pluginConfig.hasFile("config.json")){let e;try{e=this.pluginConfig.config()}catch(e){throw new Error(this.t("config-file-invalid")+"\n"+e.messages)}return Array.isArray(e)?e:e[0]?Object.values(e):e}}init(){throw new Error("uniID.init has been deprecated, use uniID.createInstance instead")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_getConfig({appid:e,platform:t}={}){const r=`${e=e||this.context.APPID}_${t=t||this.context.PLATFORM}`;if(this._configCache[r])return this._configCache[r];if(!(this.config&&0!==Object.keys(this.config).length))throw new Error(this.t("config-file-not-found"));const n=this._getAppConfig(this.config),i=Object.assign(n,n[t])||{},o=Object.assign({bindTokenToDevice:!1,tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600,usernameToLowerCase:!0,emailToLowerCase:!0},i);return["passwordSecret","tokenSecret","tokenExpiresIn","passwordErrorLimit","passwordErrorRetryTime"].forEach(e=>{if(!o||!o[e])throw new Error(this.t("config-param-required",{param:e}))}),this._configCache[r]=o,o}}for(const e in cn)ln.prototype[e]=cn[e];function pn({context:e,config:t}={}){const r=new ln({context:e,config:t});return new Proxy(r,{get(e,t){if(t in e&&0!==t.indexOf("_")){if("function"==typeof e[t])return(r=e[t],function(){const e=r.apply(this,arguments);return f(e)?e.then(e=>(I.bind(this)(e),e)):(I.bind(this)(e),e)}).bind(e);if("context"!==t&&"config"!==t)return e[t]}var r}})}ln.prototype.createInstance=pn;var fn=pn();module.exports=fn; diff --git a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json index a114bef..3a6380f 100644 --- a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json +++ b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json @@ -1,6 +1,6 @@ { "name": "uni-id", - "version": "3.3.11", + "version": "3.3.12", "description": "uni-id for uniCloud", "main": "index.js", "homepage": "https://uniapp.dcloud.io/uniCloud/uni-id", -- GitLab