'use strict';Object.defineProperty(exports,'__esModule',{value:!0});conste=require('crypto');constt=require('path');functions(e){returne&&typeofe==='object'&&'default'ine?e:{default:e}}require('fs');consto=s(e);constn=s(t);consti='uni-cloud-s2s';constr={code:5e4,message:'Config error'};constc={code:51e3,message:'Access denied'};classaextendsError{constructor(e){super(e.message),this.errMsg=e.message||'',this.code=this.errCode=e.code,this.errSubject=e.subject,this.forceReturn=e.forceReturn||!1,this.cause=e.cause,Object.defineProperties(this,{message:{get(){returnthis.errMsg},set(e){this.errMsg=e}}})}toJSON(e=0){if(!(e>=10))returne++,{errCode:this.errCode,errMsg:this.errMsg,errSubject:this.errSubject,cause:this.cause&&this.cause.toJSON?this.cause.toJSON(e):this.cause}}}constd=Object.prototype.toString;consth=50002;constu=Object.create(null);['string','boolean','number','null'].forEach(e=>{u[e]=function(t,s){if((function(e){returnd.call(e).slice(8,-1).toLowerCase()}(t))!==e)return{code:h,message:`${s} is invalid`}}});constf='Unicloud-S2s-Authorization';classg{constructor(e){const{config:t}=e||{};this.config=t;const{connectCode:s}=t||{};if(this.connectCode=s,!s||typeofs!=='string')thrownewa({subject:i,code:r.code,message:'Invalid connectCode in config'})}getHeadersValue(e={},t,s){consto=Object.keys(e||{}).find(e=>e.toLowerCase()===t.toLowerCase());returno?e[o]:s}verifyHttpInfo(e){constt=this.getHeadersValue(e.headers,f,'');const[s='',o='']=t.split('');if(s.toLowerCase()==='CONNECTCODE'.toLowerCase()&&o===this.config.connectCode)return!0;thrownewa({subject:i,code:c.code,message:`Invalid CONNECTCODE in headers['${f}']`})}getSecureHeaders(e){return{[f]:`CONNECTCODE ${this.config.connectCode}`}}}functionl(e){returnfunction(t){const{content:s,signKey:n}=t||{};returno.default.createHash(e).update(s+'\n'+n).digest('hex')}}constp={md5:l('md5'),sha1:l('sha1'),sha256:l('md5'),'hmac-sha256':function(e){const{content:t,signKey:s}=e||{};returno.default.createHmac('sha256',s).update(t).digest('hex')}};functionm(e){const{timestamp:t,data:s={},signKey:o,hashMethod:n='hmac-sha256'}=e||{};consti=p[n];constr=['number','string','boolean'];constc=Object.keys(s).sort();consta=[];for(lete=0;e<c.length;e++){constt=c[e];consto=s[t];constn=typeofo;r.includes(n)&&a.push(`${t}=${o}`)}returni({content:`${t}\n${a.join('&')}`,signKey:o})}classw{constructor(e){const{config:t}=e||{};this.config=t;const{signKey:s,hashMethod:o='hmac-sha256',timeDiffTolerance:n=60}=t;if(!p[o])thrownewa({subject:i,code:r.code,message:`Invalid hashMethod in config, expected "md5", "sha1", "sha256" or "hmac-sha256", got "${o}"`});if(!s||typeofs!=='string')thrownewa({subject:i,code:r.code,message:'Invalid signKey in config'});this.signKey=s,this.hashMethod=o,this.timeDiffTolerance=n}getHttpHeaders(e){returne.headers||{}}getHeadersValue(e,t,s){consto=Object.keys(e||{}).find(e=>e.toLowerCase()===t.toLowerCase());returno?e[o]:s}getHttpData(e){constt=e.httpMethod.toLowerCase();consts=this.getHttpHeaders(e);consto=this.getHeadersValue(s,'Content-Type','');if(t==='get')returne.queryStringParameters;if(t!=='post')thrownewa({subject:i,code:c.code,message:`Invalid http method, expected "POST" or "get", got "${t}"`});if(o.indexOf('application/json')===0)returnJSON.parse(e.body);if(o.indexOf('application/x-www-form-urlencoded')===0)returnrequire('querystring').parse(e.body);thrownewa({subject:i,code:c.code,message:`Invalid content type of POST method, expected "application/json" or "application/x-www-form-urlencoded", got "${o}"`})}verifyHttpInfo(e){constt=e.headers||{};consts=this.getHeadersValue(t,'Unicloud-S2s-Timestamp','0');let[o,n]=this.getHeadersValue(t,'Unicloud-S2s-Signature','').split('');if(o=o.toLowerCase(),o!==this.hashMethod)thrownewa({subject:i,code:c.code,message:`Invalid hash method, expected "${this.hashMethod}", got "${o}"`});constr=parseInt(s);constd=Date.now();if(Math.abs(d-r)>1e3*this.timeDiffTolerance)thrownewa({subject:i,code:c.code,message:`Invalid timestamp, server timestamp is ${d}, ${r} exceed max timeDiffTolerance(${this.timeDiffTolerance} seconds)`});returnm({timestamp:r,data:this.getHttpData(e),signKey:this.signKey,hashMethod:this.hashMethod})===n}getSecureHeaders(e){const{data:t}=e||{};consts=Date.now();consto=m({timestamp:s,data:t,signKey:this.signKey,hashMethod:this.hashMethod});return{'Unicloud-S2s-Timestamp':s+'','Unicloud-S2s-Signature':this.hashMethod+''+o}}}consty=require('uni-config-center')({pluginId:i});classb{constructor(){this.config=y.config();conste=n.default.resolve(require.resolve('uni-config-center'),i,'config.json');if(!this.config)thrownewa({subject:i,code:r.code,message:`${i} config required, please check your config file: ${e}`});if(this.config.type==='connectCode')this.verifier=newg({config:this.config});else{if(!(function(e){returne.type==='sign'}(this.config)))thrownewa({subject:i,code:r.code,message:`Invalid ${i} config, expected policy is "code" or "sign", got ${this.config.policy}`});this.verifier=neww({config:this.config})}}verifyHttpInfo(e){if(!e)thrownewa({subject:i,code:c.code,message:'Access denied, httpInfo required'});returnthis.verifier.verifyHttpInfo(e)}getSecureHeaders(e){returnthis.verifier.getSecureHeaders(e)}}exports.getSecureHeaders=function(e){return(newb()).getSecureHeaders(e)},exports.verifyHttpInfo=function(e){constt=(newb()).verifyHttpInfo(e);if(!t)thrownewa({subject:i,code:c.code,message:c.message});returnt}
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});vare=require("crypto"),t=require("path");functions(e){returne&&"object"==typeofe&&"default"ine?e:{default:e}}require("fs");varo=s(e),n=s(t);consti="uni-cloud-s2s",r={code:5e4,message:"Config error"},c={code:51e3,message:"Access denied"};classaextendsError{constructor(e){super(e.message),this.errMsg=e.message||"",this.code=this.errCode=e.code,this.errSubject=e.subject,this.forceReturn=e.forceReturn||!1,this.cause=e.cause,Object.defineProperties(this,{message:{get(){returnthis.errMsg},set(e){this.errMsg=e}}})}toJSON(e=0){if(!(e>=10))returne++,{errCode:this.errCode,errMsg:this.errMsg,errSubject:this.errSubject,cause:this.cause&&this.cause.toJSON?this.cause.toJSON(e):this.cause}}}constd=Object.prototype.toString;consth=50002,u=Object.create(null);["string","boolean","number","null"].forEach((e=>{u[e]=function(t,s){if(function(e){returnd.call(e).slice(8,-1).toLowerCase()}(t)!==e)return{code:h,message:`${s} is invalid`}}}));constf="Unicloud-S2s-Authorization";classg{constructor(e){const{config:t}=e||{};this.config=t;const{connectCode:s}=t||{};if(this.connectCode=s,!s||"string"!=typeofs)thrownewa({subject:i,code:r.code,message:"Invalid connectCode in config"})}getHeadersValue(e={},t,s){consto=Object.keys(e||{}).find((e=>e.toLowerCase()===t.toLowerCase()));returno?e[o]:s}verifyHttpInfo(e){constt=this.getHeadersValue(e.headers,f,""),[s="",o=""]=t.split("");if(s.toLowerCase()==="CONNECTCODE".toLowerCase()&&o===this.config.connectCode)return!0;thrownewa({subject:i,code:c.code,message:`Invalid CONNECTCODE in headers['${f}']`})}getSecureHeaders(e){return{[f]:`CONNECTCODE ${this.config.connectCode}`}}}functionl(e){returnfunction(t){const{content:s,signKey:n}=t||{};returno.default.createHash(e).update(s+"\n"+n).digest("hex")}}constp={md5:l("md5"),sha1:l("sha1"),sha256:l("md5"),"hmac-sha256":function(e){const{content:t,signKey:s}=e||{};returno.default.createHmac("sha256",s).update(t).digest("hex")}};functionm(e){const{timestamp:t,data:s={},signKey:o,hashMethod:n="hmac-sha256"}=e||{},i=p[n],r=["number","string","boolean"],c=Object.keys(s).sort(),a=[];for(lete=0;e<c.length;e++){constt=c[e],o=s[t],n=typeofo;r.includes(n)&&a.push(`${t}=${o}`)}returni({content:`${t}\n${a.join("&")}`,signKey:o})}classw{constructor(e){const{config:t}=e||{};this.config=t;const{signKey:s,hashMethod:o="hmac-sha256",timeDiffTolerance:n=60}=t;if(!p[o])thrownewa({subject:i,code:r.code,message:`Invalid hashMethod in config, expected "md5", "sha1", "sha256" or "hmac-sha256", got "${o}"`});if(!s||"string"!=typeofs)thrownewa({subject:i,code:r.code,message:"Invalid signKey in config"});this.signKey=s,this.hashMethod=o,this.timeDiffTolerance=n}getHttpHeaders(e){returne.headers||{}}getHeadersValue(e,t,s){consto=Object.keys(e||{}).find((e=>e.toLowerCase()===t.toLowerCase()));returno?e[o]:s}getHttpData(e){constt=e.httpMethod.toLowerCase(),s=this.getHttpHeaders(e),o=this.getHeadersValue(s,"Content-Type","");if("get"===t)returne.queryStringParameters;if("post"!==t)thrownewa({subject:i,code:c.code,message:`Invalid http method, expected "POST" or "get", got "${t}"`});if(0===o.indexOf("application/json"))returnJSON.parse(e.body);if(0===o.indexOf("application/x-www-form-urlencoded"))returnrequire("querystring").parse(e.body);thrownewa({subject:i,code:c.code,message:`Invalid content type of POST method, expected "application/json" or "application/x-www-form-urlencoded", got "${o}"`})}verifyHttpInfo(e){constt=e.headers||{},s=this.getHeadersValue(t,"Unicloud-S2s-Timestamp","0");let[o,n]=this.getHeadersValue(t,"Unicloud-S2s-Signature","").split("");if(o=o.toLowerCase(),o!==this.hashMethod)thrownewa({subject:i,code:c.code,message:`Invalid hash method, expected "${this.hashMethod}", got "${o}"`});constr=parseInt(s),d=Date.now();if(Math.abs(d-r)>1e3*this.timeDiffTolerance)thrownewa({subject:i,code:c.code,message:`Invalid timestamp, server timestamp is ${d}, ${r} exceed max timeDiffTolerance(${this.timeDiffTolerance} seconds)`});returnm({timestamp:r,data:this.getHttpData(e),signKey:this.signKey,hashMethod:this.hashMethod})===n}getSecureHeaders(e){const{data:t}=e||{},s=Date.now(),o=m({timestamp:s,data:t,signKey:this.signKey,hashMethod:this.hashMethod});return{"Unicloud-S2s-Timestamp":s+"","Unicloud-S2s-Signature":this.hashMethod+""+o}}}consty=require("uni-config-center")({pluginId:i});classb{constructor(){this.config=y.config();conste=n.default.resolve(require.resolve("uni-config-center"),i,"config.json");if(!this.config)thrownewa({subject:i,code:r.code,message:`${i} config required, please check your config file: ${e}`});if("connectCode"===this.config.type)this.verifier=newg({config:this.config});else{if(!function(e){return"sign"===e.type}(this.config))thrownewa({subject:i,code:r.code,message:`Invalid ${i} config, expected policy is "code" or "sign", got ${this.config.policy}`});this.verifier=neww({config:this.config})}}verifyHttpInfo(e){if(!e)thrownewa({subject:i,code:c.code,message:"Access denied, httpInfo required"});returnthis.verifier.verifyHttpInfo(e)}getSecureHeaders(e){returnthis.verifier.getSecureHeaders(e)}}exports.getSecureHeaders=function(e){return(newb).getSecureHeaders(e)},exports.verifyHttpInfo=function(e){constt=(newb).verifyHttpInfo(e);if(!t)thrownewa({subject:i,code:c.code,message:c.message});returnt};
"use strict";vare,t=(e=require("crypto"))&&"object"==typeofe&&"default"ine?e.default:e;constn={TOKEN_EXPIRED:"uni-id-token-expired",CHECK_TOKEN_FAILED:"uni-id-check-token-failed",PARAM_REQUIRED:"uni-id-param-required",ACCOUNT_EXISTS:"uni-id-account-exists",ACCOUNT_NOT_EXISTS:"uni-id-account-not-exists",ACCOUNT_CONFLICT:"uni-id-account-conflict",ACCOUNT_BANNED:"uni-id-account-banned",ACCOUNT_AUDITING:"uni-id-account-auditing",ACCOUNT_AUDIT_FAILED:"uni-id-account-audit-failed",ACCOUNT_CLOSED:"uni-id-account-closed"};functioni(e){return!!e&&("object"==typeofe||"function"==typeofe)&&"function"==typeofe.then}functionr(e){if(!e)return;constt=e.match(/^(\d+).(\d+).(\d+)/);returnt?t.slice(1,4).map(e=>parseInt(e)):void0}functiono(e,t){constn=r(e),i=r(t);returnn?i?function(e,t){constn=Math.max(e.length,t.length);for(leti=0;i<n;i++){constn=e[i],r=t[i];if(n>r)return1;if(n<r)return-1}return0}(n,i):1:i?-1:0}consts={"uni-id-token-expired":30203,"uni-id-check-token-failed":30202};functionc(e){const{errCode:t,errMsgValue:n}=e;e.errMsg=this._t(t,n),tins&&(e.code=s[t]),deletee.errMsgValue}functiona(e){return"object"===(i=e,Object.prototype.toString.call(i).slice(8,-1).toLowerCase())&&e.errCode&&(t=e.errCode,Object.values(n).includes(t))&&!!e.errCode;vart,i}letu={"zh-Hans":{"uni-id-token-expired":"登录状态失效,token已过期","uni-id-check-token-failed":"token校验未通过","uni-id-param-required":"缺少参数: {param}","uni-id-account-exists":"此账号已注册","uni-id-account-not-exists":"此账号未注册","uni-id-account-conflict":"用户账号冲突","uni-id-account-banned":"从账号已封禁","uni-id-account-auditing":"此账号正在审核中","uni-id-account-audit-failed":"此账号审核失败","uni-id-account-closed":"此账号已注销"},en:{"uni-id-token-expired":"The login status is invalid, token has expired","uni-id-check-token-failed":"Check token failed","uni-id-param-required":"Parameter required: {param}","uni-id-account-exists":"Account exists","uni-id-account-not-exists":"Account does not exists","uni-id-account-conflict":"User account conflict","uni-id-account-banned":"Account has been banned","uni-id-account-auditing":"Account audit in progress","uni-id-account-audit-failed":"Account audit failed","uni-id-account-closed":"Account has been closed"}};try{conste=require.resolve("uni-config-center/uni-id/lang/index.js");u=function(e,t){constn=Object.keys(e);n.push(...Object.keys(t));consti={};for(letr=0;r<n.length;r++){consto=n[r];i[o]=Object.assign({},e[o],t[o])}returni}(u,require(e))}catch(e){}vard=u;functionl(e){returne.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}functionh(e){returnJSON.parse((t=function(e){vart=4-(e=e.toString()).length%4;if(4!==t)for(varn=0;n<t;++n)e+="=";returne.replace(/-/g,"+").replace(/_/g,"/")}(e),Buffer.from(t,"base64").toString("utf-8")));vart}functionf(e){returnl((t=JSON.stringify(e),Buffer.from(t,"utf-8").toString("base64")));vart}functionp(e,n){returnl(t.createHmac("sha256",n).update(e).digest("base64"))}constk=function(e,t){if("string"!=typeofe)thrownewError("Invalid token");constn=e.split(".");if(3!==n.length)thrownewError("Invalid token");const[i,r,o]=n;if(p(i+"."+r,t)!==o)thrownewError("Invalid token");consts=h(i);if("HS256"!==s.alg||"JWT"!==s.typ)thrownewError("Invalid token");constc=h(r);if(1e3*c.exp<Date.now()){conste=newError("Token expired");throwe.name="TokenExpiredError",e}returnc},g=function(e,t,n={}){const{expiresIn:i}=n;if(!i)thrownewError("expiresIn is required");constr=parseInt(Date.now()/1e3),o={...e,iat:r,exp:r+n.expiresIn},s=f({alg:"HS256",typ:"JWT"})+"."+f(o);returns+"."+p(s,t)},I=uniCloud.database(),_=I.command,C=I.collection("uni-id-users"),m=I.collection("uni-id-roles");classT{constructor({uniId:e}={}){this.uid=null,this.userRecord=null,this.userPermission=null,this.oldToken=null,this.oldTokenPayload=null,this.uniId=e,this.config=this.uniId._getConfig(),this.clientInfo=this.uniId._clientInfo,this.checkConfig()}checkConfig(){const{tokenExpiresIn:e,tokenExpiresThreshold:t}=this.config;if(t>e)thrownewError("Config error, tokenExpiresThreshold should be less than tokenExpiresIn")}getcustomToken(){returnthis.uniId.interceptorMap.get("customToken")}isTokenInDb(e){returno(e,"1.0.10")>=0}asyncgetUserRecord(){if(this.userRecord)returnthis.userRecord;conste=awaitC.doc(this.uid).get();if(this.userRecord=e.data[0],!this.userRecord)throw{errCode:n.ACCOUNT_NOT_EXISTS};switch(this.userRecord.status){casevoid0:case0:break;case1:throw{errCode:n.ACCOUNT_BANNED};case2:throw{errCode:n.ACCOUNT_AUDITING};case3:throw{errCode:n.ACCOUNT_AUDIT_FAILED};case4:throw{errCode:n.ACCOUNT_CLOSED}}if(this.oldTokenPayload){if(this.isTokenInDb(this.oldTokenPayload.uniIdVersion)){if(-1===(this.userRecord.token||[]).indexOf(this.oldToken))throw{errCode:n.CHECK_TOKEN_FAILED}}if(this.userRecord.valid_token_date&&this.userRecord.valid_token_date>1e3*this.oldTokenPayload.iat)throw{errCode:n.TOKEN_EXPIRED}}returnthis.userRecord}asyncupdateUserRecord(e){awaitC.doc(this.uid).update(e)}asyncgetUserPermission(){if(this.userPermission)returnthis.userPermission;conste=(awaitthis.getUserRecord()).role||[];if(0===e.length)returnthis.userPermission={role:[],permission:[]},this.userPermission;if(e.includes("admin"))returnthis.userPermission={role:e,permission:[]},this.userPermission;constt=awaitm.where({role_id:_.in(e)}).get(),n=(i=t.data.reduce((e,t)=>(t.permission&&e.push(...t.permission),e),[]),Array.from(newSet(i)));vari;returnthis.userPermission={role:e,permission:n},this.userPermission}async_createToken({uid:e,role:t,permission:i}={}){if(!t||!i){conste=awaitthis.getUserPermission();t=e.role,i=e.permission}letr={uid:e,role:t,permission:i};if(this.uniId.interceptorMap.has("customToken")){constn=this.uniId.interceptorMap.get("customToken");if("function"!=typeofn)thrownewError("Invalid custom token file");r=awaitn({uid:e,role:t,permission:i})}consto=Date.now(),{tokenSecret:s,tokenExpiresIn:c}=this.config,a=g({...r,uniIdVersion:"1.0.14"},s,{expiresIn:c}),u=awaitthis.getUserRecord(),d=(u.token||[]).filter(e=>{try{constt=this._checkToken(e);if(u.valid_token_date&&u.valid_token_date>1e3*t.iat)return!1}catch(e){if(e.errCode===n.TOKEN_EXPIRED)return!1}return!0});returnd.push(a),awaitthis.updateUserRecord({last_login_ip:this.clientInfo.clientIP,last_login_date:o,token:d}),{token:a,tokenExpired:o+1e3*c}}asynccreateToken({uid:e,role:t,permission:i}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"uid"}};this.uid=e;const{token:r,tokenExpired:o}=awaitthis._createToken({uid:e,role:t,permission:i});return{errCode:0,token:r,tokenExpired:o}}asyncrefreshToken({token:e}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;constt=this._checkToken(e);this.uid=t.uid,this.oldTokenPayload=t;const{uid:i}=t,{role:r,permission:o}=awaitthis.getUserPermission(),{token:s,tokenExpired:c}=awaitthis._createToken({uid:i,role:r,permission:o});return{errCode:0,token:s,tokenExpired:c}}_checkToken(e){const{tokenSecret:t}=this.config;leti;try{i=k(e,t)}catch(e){if("TokenExpiredError"===e.name)throw{errCode:n.TOKEN_EXPIRED};throw{errCode:n.CHECK_TOKEN_FAILED}}returni}asynccheckToken(e,{autoRefresh:t=!0}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;consti=this._checkToken(e);this.uid=i.uid,this.oldTokenPayload=i;const{tokenExpiresThreshold:r}=this.config,{uid:o,role:s,permission:c}=i,a={role:s,permission:c};if(!s&&!c){const{role:e,permission:t}=awaitthis.getUserPermission();a.role=e,a.permission=t}if(!r||!t){conste={code:0,errCode:0,...i,...a};returndeletee.uniIdVersion,e}constu=Date.now();letd={};1e3*i.exp-u<1e3*r&&(d=awaitthis._createToken({uid:o}));constl={code:0,errCode:0,...i,...a,...d};returndeletel.uniIdVersion,l}}varE=Object.freeze({__proto__:null,checkToken:asyncfunction(e,{autoRefresh:t=!0}={}){returnnewT({uniId:this}).checkToken(e,{autoRefresh:t})},createToken:asyncfunction({uid:e,role:t,permission:n}={}){returnnewT({uniId:this}).createToken({uid:e,role:t,permission:n})},refreshToken:asyncfunction({token:e}={}){returnnewT({uniId:this}).refreshToken({token:e})}});constw=require("uni-config-center")({pluginId:"uni-id"});classA{constructor({context:e,clientInfo:t,config:n}={}){this._clientInfo=e?function(e){return{appId:e.APPID,platform:e.PLATFORM,locale:e.LOCALE,clientIP:e.CLIENTIP,deviceId:e.DEVICEID}}(e):t,this.config=n||this._getOriginConfig(),this.interceptorMap=newMap,w.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(w.resolve("custom-token.js"))),this._i18n=uniCloud.initI18n({locale:this._clientInfo.locale,fallbackLocale:"zh-Hans",messages:d})}setInterceptor(e,t){this.interceptorMap.set(e,t)}_t(...e){returnthis._i18n.t(...e)}_parseOriginConfig(e){returnArray.isArray(e)?e:e[0]?Object.values(e):e}_getOriginConfig(){if(w.hasFile("config.json")){lete;try{e=w.config()}catch(e){thrownewError("Invalid uni-id config file\n"+e.message)}returnthis._parseOriginConfig(e)}try{returnthis._parseOriginConfig(require("uni-id/config.json"))}catch(e){thrownewError("Invalid uni-id config file")}}_getAppConfig(){conste=this._getOriginConfig();returnArray.isArray(e)?e.find(e=>e.dcloudAppid===this._clientInfo.appId)||e.find(e=>e.isDefaultConfig):e}_getPlatformConfig(){conste=this._getAppConfig();if(!e)thrownewError(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`);lett;switch("app-plus"===this._clientInfo.platform&&(this._clientInfo.platform="app"),"h5"===this._clientInfo.platform&&(this._clientInfo.platform="web"),this._clientInfo.platform){case"web":t="h5";break;case"app":t="app-plus"}constn=[{tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600},e];t&&e[t]&&n.push(e[t]),n.push(e[this._clientInfo.platform]);consti=Object.assign(...n);return["tokenSecret","tokenExpiresIn"].forEach(e=>{if(!i||!i[e])thrownewError(`Config parameter missing, ${e} is required`)}),i}_getConfig(){returnthis._getPlatformConfig()}}for(consteinE)A.prototype[e]=E[e];functiony(e){constt=newA(e);returnnewProxy(t,{get(e,t){if(tine&&0!==t.indexOf("_")){if("function"==typeofe[t])return(n=e[t],function(){lete;try{e=n.apply(this,arguments)}catch(e){if(a(e))returnc.call(this,e),e;throwe}returni(e)?e.then(e=>(a(e)&&c.call(this,e),e),e=>{if(a(e))returnc.call(this,e),e;throwe}):(a(e)&&c.call(this,e),e)}).bind(e);if("context"!==t&&"config"!==t)returne[t]}varn}})}A.prototype.createInstance=y;constx={createInstance:y};module.exports=x;
"use strict";vare,t=(e=require("crypto"))&&"object"==typeofe&&"default"ine?e.default:e;constn={TOKEN_EXPIRED:"uni-id-token-expired",CHECK_TOKEN_FAILED:"uni-id-check-token-failed",PARAM_REQUIRED:"uni-id-param-required",ACCOUNT_EXISTS:"uni-id-account-exists",ACCOUNT_NOT_EXISTS:"uni-id-account-not-exists",ACCOUNT_CONFLICT:"uni-id-account-conflict",ACCOUNT_BANNED:"uni-id-account-banned",ACCOUNT_AUDITING:"uni-id-account-auditing",ACCOUNT_AUDIT_FAILED:"uni-id-account-audit-failed",ACCOUNT_CLOSED:"uni-id-account-closed"};functioni(e){return!!e&&("object"==typeofe||"function"==typeofe)&&"function"==typeofe.then}functionr(e){if(!e)return;constt=e.match(/^(\d+).(\d+).(\d+)/);returnt?t.slice(1,4).map(e=>parseInt(e)):void0}functiono(e,t){constn=r(e),i=r(t);returnn?i?function(e,t){constn=Math.max(e.length,t.length);for(leti=0;i<n;i++){constn=e[i],r=t[i];if(n>r)return1;if(n<r)return-1}return0}(n,i):1:i?-1:0}consts={"uni-id-token-expired":30203,"uni-id-check-token-failed":30202};functionc(e){const{errCode:t,errMsgValue:n}=e;e.errMsg=this._t(t,n),tins&&(e.code=s[t]),deletee.errMsgValue}functiona(e){return"object"===(i=e,Object.prototype.toString.call(i).slice(8,-1).toLowerCase())&&e.errCode&&(t=e.errCode,Object.values(n).includes(t))&&!!e.errCode;vart,i}letu={"zh-Hans":{"uni-id-token-expired":"登录状态失效,token已过期","uni-id-check-token-failed":"token校验未通过","uni-id-param-required":"缺少参数: {param}","uni-id-account-exists":"此账号已注册","uni-id-account-not-exists":"此账号未注册","uni-id-account-conflict":"用户账号冲突","uni-id-account-banned":"从账号已封禁","uni-id-account-auditing":"此账号正在审核中","uni-id-account-audit-failed":"此账号审核失败","uni-id-account-closed":"此账号已注销"},en:{"uni-id-token-expired":"The login status is invalid, token has expired","uni-id-check-token-failed":"Check token failed","uni-id-param-required":"Parameter required: {param}","uni-id-account-exists":"Account exists","uni-id-account-not-exists":"Account does not exists","uni-id-account-conflict":"User account conflict","uni-id-account-banned":"Account has been banned","uni-id-account-auditing":"Account audit in progress","uni-id-account-audit-failed":"Account audit failed","uni-id-account-closed":"Account has been closed"}};try{conste=require.resolve("uni-config-center/uni-id/lang/index.js");u=function(e,t){constn=Object.keys(e);n.push(...Object.keys(t));consti={};for(letr=0;r<n.length;r++){consto=n[r];i[o]=Object.assign({},e[o],t[o])}returni}(u,require(e))}catch(e){}vard=u;functionl(e){returne.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}functionh(e){returnJSON.parse((t=function(e){vart=4-(e=e.toString()).length%4;if(4!==t)for(varn=0;n<t;++n)e+="=";returne.replace(/-/g,"+").replace(/_/g,"/")}(e),Buffer.from(t,"base64").toString("utf-8")));vart}functionf(e){returnl((t=JSON.stringify(e),Buffer.from(t,"utf-8").toString("base64")));vart}functionp(e,n){returnl(t.createHmac("sha256",n).update(e).digest("base64"))}constk=function(e,t){if("string"!=typeofe)thrownewError("Invalid token");constn=e.split(".");if(3!==n.length)thrownewError("Invalid token");const[i,r,o]=n;if(p(i+"."+r,t)!==o)thrownewError("Invalid token");consts=h(i);if("HS256"!==s.alg||"JWT"!==s.typ)thrownewError("Invalid token");constc=h(r);if(1e3*c.exp<Date.now()){conste=newError("Token expired");throwe.name="TokenExpiredError",e}returnc},g=function(e,t,n={}){const{expiresIn:i}=n;if(!i)thrownewError("expiresIn is required");constr=parseInt(Date.now()/1e3),o={...e,iat:r,exp:r+n.expiresIn},s=f({alg:"HS256",typ:"JWT"})+"."+f(o);returns+"."+p(s,t)},I=uniCloud.database(),_=I.command,C=I.collection("uni-id-users"),T=I.collection("uni-id-roles");classm{constructor({uniId:e}={}){this.uid=null,this.userRecord=null,this.userPermission=null,this.oldToken=null,this.oldTokenPayload=null,this.uniId=e,this.config=this.uniId._getConfig(),this.clientInfo=this.uniId._clientInfo,this.checkConfig()}checkConfig(){const{tokenExpiresIn:e,tokenExpiresThreshold:t}=this.config;if(t>=e)thrownewError("Config error, tokenExpiresThreshold should be less than tokenExpiresIn");t>e/2&&console.warn(`Please check whether the tokenExpiresThreshold configuration is set too large, tokenExpiresThreshold: ${t}, tokenExpiresIn: ${e}`)}getcustomToken(){returnthis.uniId.interceptorMap.get("customToken")}isTokenInDb(e){returno(e,"1.0.10")>=0}asyncgetUserRecord(){if(this.userRecord)returnthis.userRecord;conste=awaitC.doc(this.uid).get();if(this.userRecord=e.data[0],!this.userRecord)throw{errCode:n.ACCOUNT_NOT_EXISTS};switch(this.userRecord.status){casevoid0:case0:break;case1:throw{errCode:n.ACCOUNT_BANNED};case2:throw{errCode:n.ACCOUNT_AUDITING};case3:throw{errCode:n.ACCOUNT_AUDIT_FAILED};case4:throw{errCode:n.ACCOUNT_CLOSED}}if(this.oldTokenPayload){if(this.isTokenInDb(this.oldTokenPayload.uniIdVersion)){if(-1===(this.userRecord.token||[]).indexOf(this.oldToken))throw{errCode:n.CHECK_TOKEN_FAILED}}if(this.userRecord.valid_token_date&&this.userRecord.valid_token_date>1e3*this.oldTokenPayload.iat)throw{errCode:n.TOKEN_EXPIRED}}returnthis.userRecord}asyncupdateUserRecord(e){awaitC.doc(this.uid).update(e)}asyncgetUserPermission(){if(this.userPermission)returnthis.userPermission;conste=(awaitthis.getUserRecord()).role||[];if(0===e.length)returnthis.userPermission={role:[],permission:[]},this.userPermission;if(e.includes("admin"))returnthis.userPermission={role:e,permission:[]},this.userPermission;constt=awaitT.where({role_id:_.in(e)}).get(),n=(i=t.data.reduce((e,t)=>(t.permission&&e.push(...t.permission),e),[]),Array.from(newSet(i)));vari;returnthis.userPermission={role:e,permission:n},this.userPermission}async_createToken({uid:e,role:t,permission:i}={}){if(!t||!i){conste=awaitthis.getUserPermission();t=e.role,i=e.permission}letr={uid:e,role:t,permission:i};if(this.uniId.interceptorMap.has("customToken")){constn=this.uniId.interceptorMap.get("customToken");if("function"!=typeofn)thrownewError("Invalid custom token file");r=awaitn({uid:e,role:t,permission:i})}consto=Date.now(),{tokenSecret:s,tokenExpiresIn:c,maxTokenLength:a=10}=this.config,u=g({...r,uniIdVersion:"1.0.16"},s,{expiresIn:c}),d=awaitthis.getUserRecord(),l=(d.token||[]).filter(e=>{try{constt=this._checkToken(e);if(d.valid_token_date&&d.valid_token_date>1e3*t.iat)return!1}catch(e){if(e.errCode===n.TOKEN_EXPIRED)return!1}return!0});returnl.push(u),l.length>a&&l.splice(0,l.length-a),awaitthis.updateUserRecord({last_login_ip:this.clientInfo.clientIP,last_login_date:o,token:l}),{token:u,tokenExpired:o+1e3*c}}asynccreateToken({uid:e,role:t,permission:i}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"uid"}};this.uid=e;const{token:r,tokenExpired:o}=awaitthis._createToken({uid:e,role:t,permission:i});return{errCode:0,token:r,tokenExpired:o}}asyncrefreshToken({token:e}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;constt=this._checkToken(e);this.uid=t.uid,this.oldTokenPayload=t;const{uid:i}=t,{role:r,permission:o}=awaitthis.getUserPermission(),{token:s,tokenExpired:c}=awaitthis._createToken({uid:i,role:r,permission:o});return{errCode:0,token:s,tokenExpired:c}}_checkToken(e){const{tokenSecret:t}=this.config;leti;try{i=k(e,t)}catch(e){if("TokenExpiredError"===e.name)throw{errCode:n.TOKEN_EXPIRED};throw{errCode:n.CHECK_TOKEN_FAILED}}returni}asynccheckToken(e,{autoRefresh:t=!0}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;consti=this._checkToken(e);this.uid=i.uid,this.oldTokenPayload=i;const{tokenExpiresThreshold:r}=this.config,{uid:o,role:s,permission:c}=i,a={role:s,permission:c};if(!s&&!c){const{role:e,permission:t}=awaitthis.getUserPermission();a.role=e,a.permission=t}if(!r||!t){conste={code:0,errCode:0,...i,...a};returndeletee.uniIdVersion,e}constu=Date.now();letd={};1e3*i.exp-u<1e3*r&&(d=awaitthis._createToken({uid:o}));constl={code:0,errCode:0,...i,...a,...d};returndeletel.uniIdVersion,l}}varE=Object.freeze({__proto__:null,checkToken:asyncfunction(e,{autoRefresh:t=!0}={}){returnnewm({uniId:this}).checkToken(e,{autoRefresh:t})},createToken:asyncfunction({uid:e,role:t,permission:n}={}){returnnewm({uniId:this}).createToken({uid:e,role:t,permission:n})},refreshToken:asyncfunction({token:e}={}){returnnewm({uniId:this}).refreshToken({token:e})}});constw=require("uni-config-center")({pluginId:"uni-id"});classx{constructor({context:e,clientInfo:t,config:n}={}){this._clientInfo=e?function(e){return{appId:e.APPID,platform:e.PLATFORM,locale:e.LOCALE,clientIP:e.CLIENTIP,deviceId:e.DEVICEID}}(e):t,this.config=n||this._getOriginConfig(),this.interceptorMap=newMap,w.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(w.resolve("custom-token.js")));this._i18n=uniCloud.initI18n({locale:this._clientInfo.locale,fallbackLocale:"zh-Hans",messages:JSON.parse(JSON.stringify(d))}),d[this._i18n.locale]||this._i18n.setLocale("zh-Hans")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_t(...e){returnthis._i18n.t(...e)}_parseOriginConfig(e){returnArray.isArray(e)?e:e[0]?Object.values(e):e}_getOriginConfig(){if(w.hasFile("config.json")){lete;try{e=w.config()}catch(e){thrownewError("Invalid uni-id config file\n"+e.message)}returnthis._parseOriginConfig(e)}try{returnthis._parseOriginConfig(require("uni-id/config.json"))}catch(e){thrownewError("Invalid uni-id config file")}}_getAppConfig(){conste=this._getOriginConfig();returnArray.isArray(e)?e.find(e=>e.dcloudAppid===this._clientInfo.appId)||e.find(e=>e.isDefaultConfig):e}_getPlatformConfig(){conste=this._getAppConfig();if(!e)thrownewError(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`);lett;switch("app-plus"===this._clientInfo.platform&&(this._clientInfo.platform="app"),"h5"===this._clientInfo.platform&&(this._clientInfo.platform="web"),this._clientInfo.platform){case"web":t="h5";break;case"app":t="app-plus"}constn=[{tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600},e];t&&e[t]&&n.push(e[t]),n.push(e[this._clientInfo.platform]);consti=Object.assign(...n);return["tokenSecret","tokenExpiresIn"].forEach(e=>{if(!i||!i[e])thrownewError(`Config parameter missing, ${e} is required`)}),i}_getConfig(){returnthis._getPlatformConfig()}}for(consteinE)x.prototype[e]=E[e];functiony(e){constt=newx(e);returnnewProxy(t,{get(e,t){if(tine&&0!==t.indexOf("_")){if("function"==typeofe[t])return(n=e[t],function(){lete;try{e=n.apply(this,arguments)}catch(e){if(a(e))returnc.call(this,e),e;throwe}returni(e)?e.then(e=>(a(e)&&c.call(this,e),e),e=>{if(a(e))returnc.call(this,e),e;throwe}):(a(e)&&c.call(this,e),e)}).bind(e);if("context"!==t&&"config"!==t)returne[t]}varn}})}x.prototype.createInstance=y;constA={createInstance:y};module.exports=A;