feathers-ucan 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,999 @@
1
- import{validateUcan as t,_unset as e,ucanToken as n,_get as r,parseUcan as i,encodeKeyPair as o,buildUcan as a,_set as c,genCapability as u,verifyUcan as s,stackAbilities as l,reduceAbilities as f}from"symbol-ucan";import{AuthenticationBaseStrategy as h,AuthenticationService as v,authenticate as p}from"@feathersjs/authentication";import d from"long-timeout";function m(t){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var e=t.done;return Promise.resolve(t.value).then(function(t){return{value:t,done:e}})}return m=function(t){this.s=t,this.n=t.next},m.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(t){var n=this.s.return;return void 0===n?Promise.resolve({value:t,done:!0}):e(n.apply(this.s,arguments))},throw:function(t){var n=this.s.return;return void 0===n?Promise.reject(t):e(n.apply(this.s,arguments))}},new m(t)}function y(){return y=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},y.apply(this,arguments)}function g(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,b(t,e)}function P(t){return P=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},P(t)}function b(t,e){return b=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},b(t,e)}function w(t,e,n){return w=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&b(i,n.prototype),i},w.apply(null,arguments)}function _(t){var e="function"==typeof Map?new Map:void 0;return _=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return w(t,arguments,P(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),b(n,t)},_(t)}function j(t,e){if(null==t)return{};var n,r,i={},o=Object.keys(t);for(r=0;r<o.length;r++)e.indexOf(n=o[r])>=0||(i[n]=t[n]);return i}function x(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function k(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return x(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?x(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var S=/*#__PURE__*/function(t){function e(e){return t.call(this,e)||this}return g(e,t),e}(/*#__PURE__*/_(Error)),E=/(\S+)\s+(\S+)/,O=/*#__PURE__*/function(i){function o(){for(var t,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return(t=i.call.apply(i,[this].concat(n))||this).expirationTimers=new WeakMap,t}g(o,i);var a,c,u=o.prototype;return u.setAuthentication=function(t){t.verifyAccessToken=function(t){return{}},i.prototype.setAuthentication.call(this,t)},u.handleConnection=function(e,n,r){try{var i=this,o="logout"===e&&n.authentication&&r&&n.authentication.accessToken===r.accessToken,a=(r||{}).accessToken,c=function(){if(a&&"login"===e)return Promise.resolve(t(a).catch(function(t){console.log("Could not validate ucan in connection: ",t.message);var e={code:0,message:"Unknown Issue Validating Ucan"};throw t.message.indexOf("Expired.")>-1&&(e.code=1,e.message="Expired Ucan"),new Error(e.message)})).then(function(t){var e=1e3*(t||{payload:{exp:0}}).payload.exp-Date.now(),r=d.setTimeout(function(){return i.app.emit("disconnect",n)},e);d.clearTimeout(i.expirationTimers.get(n)),i.expirationTimers.set(n,r),n.authentication={strategy:i.name,accessToken:a}});("disconnect"===e||o)&&(delete n[i.configuration.entity],delete n.authentication,d.clearTimeout(i.expirationTimers.get(n)),i.expirationTimers.delete(n))}();return Promise.resolve(c&&c.then?c.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},u.verifyConfiguration=function(){for(var t=["entity","entityId","service","header","schemes","audience"],e=0,n=Object.keys(this.configuration);e<n.length;e++){var r=n[e];if(!t.includes(r))throw new Error("Invalid ucanStrategy option 'authentication."+this.name+"."+r+"'. Did you mean to set it in 'authentication.jwtOptions'?")}if("string"!=typeof this.configuration.header)throw new Error("The 'header' option for the "+this.name+" strategy must be a string")},u.getEntityQuery=function(t){return Promise.resolve({})},u.getEntity=function(t,n){try{var r=this,i=r.entityService,o=r.configuration.entity;if(null===i)throw new S("Could not find entity service");return Promise.resolve(r.getEntityQuery(n)).then(function(r){var a=Object.assign({},e(n,"provider"),{query:r});return Promise.resolve(i.get(t,a)).then(function(e){var r;return n.provider?i.get(t,y({},n,((r={})[o]=e,r))):e})})}catch(t){return Promise.reject(t)}},u.getEntityId=function(t,e){try{var n=e.query,r=e.loginId;if(r)return Promise.resolve(r);var i,o,a=this.configuration,c=a.service,u=a.core_path,s=void 0===u?"core":u,l=((i={query:y({},n,{$limit:1})})[s]=y({skipJoins:!0},e[s]),i);return Promise.resolve(null==(o=this.app)?void 0:o.service(c).find(y({},l,{skipJoins:!0,skip_hooks:!0,admin_pass:!0}))).then(function(t){if(t.total)return t.data[0]._id;throw new S("Could not find login associated with this ucan")})}catch(t){return Promise.reject(t)}},u.authenticate=function(e,i){try{var o=this,a=e.accessToken,c=e.loginId,u=e.ucan,s=o.configuration,l=s.entity,f=s.core_path;if(!a){if(!u)throw new S("Error generating ucan");a=n(u)}return Promise.resolve(t(a).catch(function(t){console.log("Could not validate ucan during authentication: ",t.message);var e={code:0,message:"Unknown Issue Validating Ucan"};throw t.message.indexOf("Expired.")>-1&&(e.code=1,e.message="Expired Ucan"),new Error(e.message)})).then(function(t){function e(){var t;return y({},u,((t={})[l]=n,t))}var n,u={accessToken:a,authentication:{strategy:"jwt",accessToken:a}};if(null===l)return u;var s=r(i,[f,l]),h=function(){if(!s)return Promise.resolve(o.getEntityId(u,y({},i,{loginId:c,query:{did:null==t?void 0:t.payload.aud}}))).then(function(t){return Promise.resolve(o.getEntity(t,i)).then(function(t){n=t})});n=s}();return h&&h.then?h.then(e):e()})}catch(t){return Promise.reject(t)}},u.parse=function(t){try{var e=this.configuration,n=e.schemes,r=t.headers&&t.headers[e.header.toLowerCase()];if(!r||"string"!=typeof r)return Promise.resolve(null);var i=r.match(E)||[],o=i[1],a=i[2],c=o&&n.some(function(t){return new RegExp(t,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:r})}catch(t){return Promise.reject(t)}},a=o,(c=[{key:"configuration",get:function(){var t,e=(null==(t=this.authentication)?void 0:t.configuration)||{service:void 0,entity:void 0,entityId:void 0};return y({service:e.service,entity:e.entity,entityId:e.entityId,header:"Authorization",schemes:["Bearer","JWT"]},i.prototype.configuration)}}])&&function(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,"symbol"==typeof(i=function(t,e){if("object"!=typeof t||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(r.key))?i:String(i),r)}var i}(a.prototype,c),Object.defineProperty(a,"prototype",{writable:!1}),o}(h),T=["NotAuthenticated"],A=/*#__PURE__*/function(t){function e(e){return t.call(this,e)||this}return g(e,t),e}(/*#__PURE__*/_(Error)),C=/*#__PURE__*/function(e){function c(t,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=j(r,T);return(i=e.call(this,t,n,a)||this).options=void 0,i.app=t,i.options={NotAuthenticated:o},i}return g(c,e),c.prototype.create=function(e,c){try{var u,s,l=this,f=(null==(u=l.options)?void 0:u.NotAuthenticated)||A,h=l.app.get("authentication"),v=h.entity,p=h.service,d=h.ucan_path,m=void 0===d?"ucan":d,g=(null==(s=c)?void 0:s.authStrategies)||l.configuration.authStrategies;if(c||(c={}),!g.length)throw new f("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(l.authenticate.apply(l,[e,c].concat(g)).catch(function(t){throw new Error(t.message)})).then(function(u){if(u.accessToken)return u;var s=e.did||r(u,[v,"did"]),f=e.ucan||r(u,[v,"ucan"]);if(!s)throw new Error("No did audience provided");if(!f)throw new Error("No ucan provided to authentication call");return Promise.resolve(t(f).catch(function(t){console.log("Could not validate ucan creating authentication: ",t.message);var e={code:0,message:"Unknown Issue Validating Ucan"};return t.message.indexOf("Expired.")>-1&&(e.code=1,e.message="Expired Ucan"),console.warn("Could not validate ucan creating authentication",f,e.message),null})).then(function(t){function e(){var t=n(f);return y({accessToken:t},u,{authentication:y({},u.authentication,{payload:t})})}var s=function(){if(!t){var e=i(f),s=l.app.get("authentication"),h=o({secretKey:s.secret});return Promise.resolve(a({audience:e.payload.aud,issuer:h,lifetimeInSeconds:5184e3,capabilities:e.payload.att})).then(function(t){var e;return f=t,c.admin_pass=!0,Promise.resolve(l.app.service(p).patch(r(u,[v,"_id"]),(e={},e[m]=n(f),e),y({},c))).then(function(){})})}}();return s&&s.then?s.then(e):e()})})}catch(t){return Promise.reject(t)}},c}(v),I=/*#__PURE__*/function(){function t(t,e,n){var r;this.context=void 0,this.service=void 0,this.core=void 0,this.entity=void 0,this.service=t,this.context=e;var i=(e.app.get("authentication")||{entity:"login"}).entity||"login";this.entity=i;var o=(null==(r=e.params)?void 0:r.core)||{};o[i]||(o[i]=e.params[i]),this.core=y({},o,n)}var e=t.prototype;return e.get=function(t,e){void 0===e&&(e={});try{var n,r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(n=o.context.app)?void 0:n.service(o.service).get(t,y({},e,((r={})[o.entity]=e[o.entity],r),((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e.find=function(t){void 0===t&&(t={});try{var e,n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(e=i.context.app)?void 0:e.service(i.service).find(y({},t,((n={})[i.entity]=t[i.entity],n.skip_hooks=!0,n.admin_pass=!0,n),((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e.create=function(t,e){void 0===e&&(e={});try{var n,r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(n=o.context.app)?void 0:n.service(o.service).create(t,y({},e,((r={})[o.entity]=e[o.entity],r),((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e.patch=function(t,e,n){void 0===n&&(n={});try{var r,i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(r=a.context.app)?void 0:r.service(a.service).patch(t,e,y({},n,((i={})[a.entity]=n[a.entity],i),((o={})[c]=a.core,o))))}catch(t){return Promise.reject(t)}},e.update=function(t,e,n){void 0===n&&(n={});try{var r,i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(r=a.context.app)?void 0:r.service(a.service).update(t,e,y({},n,((i={})[a.entity]=n[a.entity],i),((o={})[c]=a.core,o))))}catch(t){return Promise.reject(t)}},e.remove=function(t,e){void 0===e&&(e={});try{var n,r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(n=o.context.app)?void 0:n.service(o.service).remove(t,y({},e,((r={})[o.entity]=e[o.entity],r),((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e._get=function(t,e){void 0===e&&(e={});try{var n,r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(n=o.context.app)?void 0:n.service(o.service)._get(t,y({},e,((r={})[o.entity]=e[o.entity],r),((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e._find=function(t){void 0===t&&(t={});try{var e,n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(e=i.context.app)?void 0:e.service(i.service)._find(y({},t,((n={})[i.entity]=t[i.entity],n),((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e._create=function(t,e){void 0===e&&(e={});try{var n,r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(n=o.context.app)?void 0:n.service(o.service)._create(t,y({},e,((r={})[o.entity]=e[o.entity],r),((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e._patch=function(t,e,n){void 0===n&&(n={});try{var r,i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(r=a.context.app)?void 0:r.service(a.service)._patch(t,e,y({},n,((i={})[a.entity]=n[a.entity],i),((o={})[c]=a.core,o))))}catch(t){return Promise.reject(t)}},e._update=function(t,e,n){void 0===n&&(n={});try{var r,i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(r=a.context.app)?void 0:r.service(a.service)._update(t,e,y({},n,((i={})[a.entity]=n[a.entity],i),((o={})[c]=a.core,o))))}catch(t){return Promise.reject(t)}},e._remove=function(t,e){void 0===e&&(e={});try{var n,r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(n=o.context.app)?void 0:n.service(o.service)._remove(t,y({},e,((r={})[o.entity]=e[o.entity],r),((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},t}(),U="_exists",q=function(t){var e=t.app.get("existsPath")||U;return r(t.params,"core."+e+"."+t.path+"."+t.id)||void 0},$=function(t,e){try{var n=q(t),r=function(){if(!n&&t.id)return Promise.resolve(new I(t.path,t,{skipJoins:!1!==(null==e?void 0:e.skipJoins)}).get(t.id,y({exists_check:!0,admin_pass:!0,skip_hooks:!0},(null==e?void 0:e.params)||{}))).then(function(t){n=t})}();return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(t){return Promise.reject(t)}},N=function(t,e){var n=t.app.get("existsPath")||U;return t.params=c(t.params,"core."+n+"."+t.path+"."+((null==e?void 0:e._id)||t.id),e),t},J=["ucan"];function M(t,e){try{var n=t()}catch(t){return e(t)}return n&&n.then?n.then(void 0,e):n}function R(t,e,n){if(!t.s){if(n instanceof K){if(!n.s)return void(n.o=R.bind(null,t,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(R.bind(null,t,e),R.bind(null,t,2));t.s=e,t.v=n;var r=t.o;r&&r(t)}}const K=/*#__PURE__*/function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const t=1&i?e:n;if(t){try{R(r,1,t(this.v))}catch(t){R(r,2,t)}return r}return this}return this.o=function(t){try{const i=t.v;1&t.s?R(r,1,e?e(i):i):n?R(r,1,n(i)):R(r,2,i)}catch(t){R(r,2,t)}},r},t}();function B(t){return t instanceof K&&1&t.s}function V(t,e,n){var r,i,o=-1;return function a(c){try{for(;++o<t.length&&(!n||!n());)if((c=e(o))&&c.then){if(!B(c))return void c.then(a,i||(i=R.bind(null,r=new K,2)));c=c.v}r?R(r,1,c):r=c}catch(t){R(r||(r=new K),2,t)}}(),r}function W(t,e,n){var r=[];for(var i in t)r.push(i);return V(r,function(t){return e(r[t])},n)}var D="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function F(t,e){try{var n=t()}catch(t){return e(!0,t)}return n&&n.then?n.then(e.bind(null,!1),e.bind(null,!0)):e(!1,n)}var L="*",Q="$",z=function(t){try{var e,n=t.app.get("authentication"),i=r(t,["auth",n.entity]);i&&(t=c(t,[n.core_path,n.entity],i));var o=M(function(){return Promise.resolve(p("jwt")(t).catch(function(){return t})).then(function(e){t=e})},function(){return e=1,t});return Promise.resolve(o&&o.then?o.then(function(n){return e?n:t}):e?o:t)}catch(t){return Promise.reject(t)}},H=function(t){try{var e=t.app.get("authentication"),n=r(t,["auth",e.entity]);return n&&(t=c(t,[e.core_path,e.entity],n)),Promise.resolve(p("jwt")(t))}catch(t){return Promise.reject(t)}},Y=function(t,e,n){try{return Promise.resolve(M(function(){return Promise.resolve(s(t,e)).then(function(r){var o=function(o){if((null==(o=r)||!o.ok)&&e.requiredCapabilities){var a=e.requiredCapabilities.map(function(t){return"*"!==t.capability.can&&(t.capability.can.segments=["*"]),t});return n&&console.log("set new req capabilities",a,i(t)),Promise.resolve(s(t,y({},e,{requiredCapabilities:a}))).then(function(t){r=t,n&&console.log("Second verification result:",r)})}}();return o&&o.then?o.then(function(){return r}):r})},function(t){return{ok:!1,err:[t.message]}}))}catch(t){return Promise.reject(t)}},G=function(t,e){try{var n={ok:!1,value:[]};return Promise.resolve(M(function(){var r,o=W(t,function(o){e&&console.log("or verify loop",t[o],i(t[o].ucan));var a=function(i){if(null==(i=n)||!i.ok){var a=t[o],c=a.ucan,u=j(a,J);return Promise.resolve(Y(c,u,e)).then(function(t){n=t,e&&console.log("got in verify loop",n)})}r=1}();if(a&&a.then)return a.then(function(){})},function(){return r});return o&&o.then?o.then(function(){return n}):n},function(t){return{ok:!1,err:[t.message]}}))}catch(t){return Promise.reject(t)}},X=function(t,e,i){return function(o){try{var a,c=null==i?void 0:i.log,u=r(o.params,e.client_ucan),s=(null==i?void 0:i.audience)||r(o.params,e.ucan_aud);c&&console.log("verify against reqs",t);var l=(null==i?void 0:i.or)||[];return a=u&&("*"===l||l.includes(o.method))?function(e,n){return G((t||[]).map(function(t){return{ucan:e||u,audience:(null==n?void 0:n.aud)||s,requiredCapabilities:[t]}}),c)}:function(e,n){return Y(e||u,{audience:(null==n?void 0:n.aud)||s,requiredCapabilities:t},c)},Promise.resolve(a()).then(function(t){var u,s;if(c&&console.log("first verify try",t),null!=(u=t)&&u.ok)return t;var l=((null==i?void 0:i.cap_subjects)||[]).filter(function(t){return!!t});c&&console.log("check cap_subjects",l);var f=function(){if(l){var u=(null==e?void 0:e.loginConfig)||o.app.get("authentication"),f=String(r(o.params,u.entity+"._id"||""));return Promise.resolve(new I(u.capability_service||"caps",o).find({query:{$limit:l.length,subject:{$in:l}},skip_hooks:!0,admin_pass:!0}).catch(function(t){return console.log("Error finding caps in ucan auth: "+t.message)})).then(function(e){var r;return c&&console.log("caps",e),function(){if(null!=e&&e.data)return function(t,e,n){if("function"==typeof t[D]){var r,i,o,a=t[D]();if(function t(c){try{for(;!((r=a.next()).done||n&&n());)if((c=e(r.value))&&c.then){if(!B(c))return void c.then(t,o||(o=R.bind(null,i=new K,2)));c=c.v}i?R(i,1,c):i=c}catch(t){R(i||(i=new K),2,t)}}(),a.return){var c=function(t){try{r.done||a.return()}catch(t){}return t};if(i&&i.then)return i.then(c,function(t){throw c(t)});c()}return i}if(!("length"in t))throw new TypeError("Object is not iterable");for(var u=[],s=0;s<t.length;s++)u.push(t[s]);return V(u,function(t){return e(u[t])},n)}(e.data,function(e){return W(e.caps||{},function(r){return c&&console.log("check cap",r,e.caps[r].logins,f),function(){if((e.caps[r].logins||[]).map(function(t){return String(t)}).includes(f)){var o=function(){var e;if(null!=i&&i.log&&console.log("tried v on cap",t),null!=(e=t)&&e.ok)return s=1,t},u=M(function(){var i=n(e.caps[r].ucan);c&&console.log("got ucan string",i);var o=function(){if(i)return Promise.resolve(a(i,{aud:e.did})).then(function(e){t=e,c&&console.log("tried v on cap",t)})}();if(o&&o.then)return o.then(function(){})},function(t){console.log("Error verifying ucan from cap: "+e._id+". Err:"+t.message)});return u&&u.then?u.then(o):o()}}()},function(){return r})},function(){return r})}()})}}();return f&&f.then?f.then(function(e){return s?e:t}):s?f:t})}catch(t){return Promise.reject(t)}}},Z=function(t,e){var n=o({secretKey:e.secret}).did();return Array.isArray(t)?t.map(function(t){return{capability:Array.isArray(t)?u({with:{scheme:e.defaultScheme,hierPart:e.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},e):u(t,e),rootIssuer:n}}):[]},tt=function(t,e){return function(n){try{var i=function(){var t,i;if(null!=(t=a)&&t.ok)return n.params.authenticated=!0,n.params.canU=!0,n;if(null!=e&&e.log&&console.log("checking special change",null==e?void 0:e.specialChange),null!=e&&e.specialChange){if("*"===e.specialChange)return n.params.canU=!0,n;if(Array.isArray(e.specialChange)&&["create","patch","update"].includes(n.method)){if(Array.isArray(n.data))throw new Error("No multi data allowed with special change");for(var u in n.data||{})if(["$set","$unset","$addToSet","$pull","$push"].includes(u)){for(var s in n.data[u]||{})if(!e.specialChange.includes(s)){var l=s.split(".");1===l.length?delete n.data[u][s]:e.specialChange.includes(l[0])||delete n.data[u][s]}}else e.specialChange.includes(u)||delete n.data[u];return n.params.canU=!0,n}}if(null!=(i=a)&&i.ok)return n.params.authenticated=!0,n.params.canU=!0,n;var f=function(t){var r;if(null!=(r=a)&&r.ok)return n.params.authenticated=!0,n.params.canU=!0,n;if(null!=e&&e.log&&console.error("Ucan capabilities requirements not met: ",a,n.type,n.path),null!=e&&e.noThrow)return n.params._no_throw_error={type:n.type,method:n.method,path:n.path},n;throw new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)},h=(e||{loginPass:[[["*"],["nonExistentMethod"]]]}).loginPass,v=function(){if(null!=h&&h.length){var t,i=function(t){if(_interrupt2)return t;s&&(n=c(n,"data",u))},u={},s=!0,l=!1,f=!1,v=F(function(){return M(function(){var t,i,f=function(t){var e,n,r,i=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&null!=(e=t[n]))return e.call(t);if(r&&null!=(e=t[r]))return new m(e.call(t));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(h),v=function(t,e,n){for(var r;;){var i=t();if(B(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!B(o)){r=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!B(a)){r=2;break}}}var c=new K,u=R.bind(null,c,2);return(0===r?i.then(l):1===r?o.then(s):a.then(f)).then(void 0,u),c;function s(r){o=r;do{if(e&&(a=e())&&a.then&&!B(a))return void a.then(f).then(void 0,u);if(!(i=t())||B(i)&&!i.v)return void R(c,1,o);if(i.then)return void i.then(l).then(void 0,u);B(o=n())&&(o=o.v)}while(!o||!o.then);o.then(s).then(void 0,u)}function l(t){t?(o=n())&&o.then?o.then(s).then(void 0,u):s(o):R(c,1,o)}function f(){(i=t())?i.then?i.then(l).then(void 0,u):l(i):R(c,1,o)}}(function(){function e(e){return!t&&(l=!(i=e).done)}return t?!!e(!t&&f.next()):Promise.resolve(!t&&f.next()).then(e)},function(){return!!(l=!1)},function(){var l=i.value,f=function(){if(s)return Promise.resolve(function(t){try{var i=[],l="*"===t[1],f=-1;l?f=0:(i=t[1].map(function(t){return t.split("/")[0]}),f=i.indexOf(n.method));var h=function(){if(f>-1)return Promise.resolve($(n,{params:null==e?void 0:e.existingParams})).then(function(e){var i=!1,h=function(t,e){void 0===e&&(e="_id");var a=r(n.params,o.entity+"."+e);if(a&&t){var c=Array.isArray(a)?a.map(function(t){return String(t)}):[String(a)];if(Array.isArray(t))for(var u=0;u<c.length;u++){for(var s=String(c[u]),l=0;l<t.length;)String(t[l])===s?i=!0:l++;if(i)return}else if(c.includes(String(t)))return i=!0}};if(e){n=N(n,e);for(var v,p=k(t[0]||[]);!(v=p()).done;){var d=String(v.value).split("/");if(d[0].includes("*")){var m=d[0].split("*"),y=r(e,m[0]);if(y&&"object"==typeof y)if(Array.isArray(y))for(var g,P=k(y);!(g=P()).done&&(h(r(g.value,m[1]),d[1]||"_id"),!i););else for(var b in y)if(h(r(y,b+"."+m[1]),d[1]||"_id"),i)break}else h(r(e,d[0]),d[1]||"_id")}}if(i)if(a.ok=!0,"*"===t[1]||["find","get","remove"].some(function(e){return t[1].includes(e)}))s=!1;else{var w=l?"*":t[1][f];if(w.split("/")[0]!==w)for(var _,j=k(w.split("/").slice(1).join("").split(",")||[]);!(_=j()).done;){var x=_.value,S=r(n.data,x);if(S)u=c(u,x,S);else for(var E=0,O=["$addToSet","$pull"];E<O.length;E++){var T=O[E],A=r(n.data,T+"."+x);A&&(u=c(u,T+"."+x,A))}}else s=!1}})}();return Promise.resolve(h&&h.then?h.then(function(){}):void 0)}catch(t){return Promise.reject(t)}}(l)).then(function(){});t=1}();return f&&f.then?f.then(function(){}):void 0});if(v&&v.then)return v.then(function(){})},function(e){f=!0,t=e})},function(e,n){function r(t){if(e)throw n;return n}var i=F(function(){var t=function(){if(l&&null!=_iterator.return)return Promise.resolve(_iterator.return()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(e,n){if(f)throw t;if(e)throw n;return n});return i&&i.then?i.then(r):r()});return v&&v.then?v.then(i):i(v)}}();return v&&v.then?v.then(f):f()},o=(null==e?void 0:e.loginConfig)||n.app.get("authentication"),a={ok:!1,value:[]},u=Z(t,o),s=function(){if(u.length)return Promise.resolve(X(u,o,e)(n)).then(function(t){a=t});"*"!==t&&(a.ok=!0)}();return Promise.resolve(s&&s.then?s.then(i):i())}catch(t){return Promise.reject(t)}}},et=function(t,e){return function(n){try{var i,o=function(o){if(i)return o;function c(){return"*"!==t||null!=e&&e.specialChange?s?n:t?Promise.resolve(tt(t,e)(n)):n:(n.params.authenticated=!!n.params[u],n)}var s=((null==e?void 0:e.adminPass)||[]).includes(n.method)&&(r(n.params,"admin_pass")||r(n.params,[a.core_path,"admin_pass"])),l=function(){if(!f&&!h)return Promise.resolve(s||null!=e&&e.specialChange?z(n):H(n)).then(function(t){n=t})}();return l&&l.then?l.then(c):c()},a=n.app.get("authentication"),c=a.core_path||"core",u=a.entity||"login",s=r(n.params,[c,u])||r(n.params,"login")||r(n.params.connect,u),l="string"==typeof s?s:null==s?void 0:s._id,f=!(!s||"string"!=typeof s&&!l),h=r(n.params,a.client_ucan||"client_ucan");null!=e&&e.log&&console.log("ucan auth","hasLogin",f,"loginId",l,"existingUcan",!!h,"core_path",c,"entity",u,"core",n.params[c],"params login",n.params.login,"required capabilities",t);var v=function(){if("$"===t||t&&"$"===t[n.method]){var e=function(t){return i=1,t};return f?e(n):Promise.resolve(z(n)).then(e)}}();return Promise.resolve(v&&v.then?v.then(o):o(v))}catch(t){return Promise.reject(t)}}},nt=function(t,e){return function(n){try{var i=n.app.get("authentication"),o=i.core_path||"core",a=i.entity||"login";if(!r(n.params,[o,a])){var u=r(n,["auth",a]);u&&(n=c(n,[o,a],u))}if("before"===n.type){var s=n.method;return Promise.resolve(t[s]||t.all?et(t[s]||t.all,e)(n):n)}return Promise.resolve(n)}catch(t){return Promise.reject(t)}}},rt=function(){return function(e){try{var c=e.data,u=c.add,h=void 0===u?[]:u,v=c.remove,p=void 0===v?[]:v;if(!(null!=h&&h.length||null!=p&&p.length))throw new Error("No new capabilities passed");var d=e.app.get("authentication"),m=d.secret,g=d.ucan_aud,P=d.entity,b=d.ucan,w=o({secretKey:m}).did(),_=l([].concat(h,p));return Promise.resolve(s(r(e.params,[P,b]),{audience:r(e.params,g),requiredCapabilities:_.map(function(t){return{capability:t,rootIssuer:w}})})).then(function(c){if(null==c||!c.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var u=e.id,s=e.data.service||"logins",v=e.data.path||"ucan";return Promise.resolve(new I(s,e,{skipJoins:!0}).get(u)).then(function(c){var d=i(r(c,v)).payload,g=d.aud,P=d.att,b=d.prf,w=[].concat(P);return null!=p&&p.length&&(w=f(p,P)),null!=h&&h.length&&(w=l([].concat(P,h))),Promise.resolve(a(y({issuer:o({secretKey:m}),audience:g,lifetimeInSeconds:5184e3,proofs:b},e.data,{capabilities:w}))).then(function(r){var i=n(r);return Promise.resolve(t(i)).then(function(t){var n;if(!t)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new I(s,e).patch(u,(n={},n[v]=i,n))).then(function(t){return e.result={raw:e.data,encoded:i,subject:t},e})})})})})}catch(t){return Promise.reject(t)}}};export{C as AuthService,I as CoreCall,A as NotAuthError,O as UcanStrategy,nt as allUcanAuth,L as anyAuth,H as bareAuth,tt as checkUcan,U as existsPath,q as getExists,$ as loadExists,Z as modelCapabilities,Q as noThrow,z as noThrowAuth,G as orVerifyLoop,N as setExists,et as ucanAuth,rt as updateUcan,X as verifyAgainstReqs};
1
+ import { validateUcan, _unset, ucanToken, _get, parseUcan, encodeKeyPair, buildUcan, _set, genCapability, verifyUcan, stackAbilities, reduceAbilities } from 'symbol-ucan';
2
+ import { AuthenticationBaseStrategy, AuthenticationService, authenticate } from '@feathersjs/authentication';
3
+ import lt from 'long-timeout';
4
+
5
+ class NotAuthError$1 extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ }
9
+ }
10
+ const SPLIT_HEADER = /(\S+)\s+(\S+)/;
11
+ class UcanStrategy extends AuthenticationBaseStrategy {
12
+ constructor(...args) {
13
+ super(...args);
14
+ this.expirationTimers = new WeakMap();
15
+ }
16
+ setAuthentication(auth) {
17
+ // console.log('set authentication', auth);
18
+ auth.verifyAccessToken = accessToken => {
19
+ return {};
20
+ };
21
+ super.setAuthentication(auth);
22
+ }
23
+ get configuration() {
24
+ var _this$authentication;
25
+ const authConfig = ((_this$authentication = this.authentication) == null ? void 0 : _this$authentication.configuration) || {
26
+ service: undefined,
27
+ entity: undefined,
28
+ entityId: undefined
29
+ };
30
+ const config = super.configuration;
31
+ return {
32
+ service: authConfig.service,
33
+ entity: authConfig.entity,
34
+ entityId: authConfig.entityId,
35
+ header: 'Authorization',
36
+ schemes: ['Bearer', 'JWT'],
37
+ ...config
38
+ };
39
+ }
40
+ async handleConnection(event, connection, authResult) {
41
+ const isValidLogout = event === 'logout' && connection.authentication && authResult && connection.authentication.accessToken === authResult.accessToken;
42
+ const {
43
+ accessToken,
44
+ entity
45
+ } = authResult || {};
46
+ if (accessToken && event === 'login') {
47
+ const validUcan = await validateUcan(accessToken).catch(err => {
48
+ console.log('Could not validate ucan in connection: ', err.message);
49
+ const errObj = {
50
+ code: 0,
51
+ message: 'Unknown Issue Validating Ucan'
52
+ };
53
+ if (err.message.indexOf('Expired.') > -1) {
54
+ errObj.code = 1;
55
+ errObj.message = 'Expired Ucan';
56
+ }
57
+ throw new Error(errObj.message);
58
+ });
59
+ const {
60
+ payload: {
61
+ exp
62
+ }
63
+ } = validUcan || {
64
+ payload: {
65
+ exp: 0
66
+ }
67
+ };
68
+ // The time (in ms) until the token expires
69
+ const duration = exp * 1000 - Date.now();
70
+ // This may have to be a `logout` event but right now we don't want
71
+ // the whole context object lingering around until the timer is gone
72
+ const timer = lt.setTimeout(() => this.app.emit('disconnect', connection), duration);
73
+ lt.clearTimeout(this.expirationTimers.get(connection));
74
+ this.expirationTimers.set(connection, timer);
75
+ connection.authentication = {
76
+ strategy: this.name,
77
+ accessToken
78
+ };
79
+ } else if (event === 'disconnect' || isValidLogout) {
80
+ const {
81
+ entity
82
+ } = this.configuration;
83
+ delete connection[entity];
84
+ delete connection.authentication;
85
+ lt.clearTimeout(this.expirationTimers.get(connection));
86
+ this.expirationTimers.delete(connection);
87
+ }
88
+ }
89
+ verifyConfiguration() {
90
+ const allowedKeys = ['entity', 'entityId', 'service', 'header', 'schemes', 'audience'];
91
+ for (const key of Object.keys(this.configuration)) {
92
+ if (!allowedKeys.includes(key)) {
93
+ throw new Error(`Invalid ucanStrategy option 'authentication.${this.name}.${key}'. Did you mean to set it in 'authentication.jwtOptions'?`);
94
+ }
95
+ }
96
+ if (typeof this.configuration.header !== 'string') {
97
+ throw new Error(`The 'header' option for the ${this.name} strategy must be a string`);
98
+ }
99
+ }
100
+ // eslint-disable-next-line no-unused-vars
101
+ async getEntityQuery(_params) {
102
+ return {};
103
+ }
104
+ /**
105
+ * Return the entity for a given id
106
+ * @param id The id to use
107
+ * @param params Service call parameters
108
+ */
109
+ async getEntity(id, params) {
110
+ const entityService = this.entityService;
111
+ const {
112
+ entity
113
+ } = this.configuration;
114
+ if (entityService === null) {
115
+ throw new NotAuthError$1('Could not find entity service');
116
+ }
117
+ const query = await this.getEntityQuery(params);
118
+ const getParams = Object.assign({}, _unset(params, 'provider'), {
119
+ query
120
+ });
121
+ const result = await entityService.get(id, getParams);
122
+ if (!params.provider) {
123
+ return result;
124
+ }
125
+ return entityService.get(id, {
126
+ ...params,
127
+ [entity]: result
128
+ });
129
+ }
130
+ async getEntityId(authResult, _params) {
131
+ let {
132
+ query,
133
+ loginId
134
+ } = _params;
135
+ if (loginId) return loginId;else {
136
+ var _this$app;
137
+ const {
138
+ service,
139
+ core_path = 'core'
140
+ } = this.configuration;
141
+ const pms = {
142
+ query: {
143
+ ...query,
144
+ $limit: 1
145
+ },
146
+ [core_path]: {
147
+ skipJoins: true,
148
+ ..._params[core_path]
149
+ }
150
+ };
151
+ const entities = await ((_this$app = this.app) == null ? void 0 : _this$app.service(service).find({
152
+ ...pms,
153
+ skipJoins: true,
154
+ skip_hooks: true,
155
+ admin_pass: true
156
+ }));
157
+ if (entities.total) return entities.data[0]._id;else throw new NotAuthError$1('Could not find login associated with this ucan');
158
+ }
159
+ }
160
+ async authenticate(authentication, params) {
161
+ let {
162
+ accessToken,
163
+ loginId,
164
+ ucan
165
+ } = authentication;
166
+ const {
167
+ entity,
168
+ core_path
169
+ } = this.configuration;
170
+ if (!accessToken) {
171
+ if (ucan) accessToken = ucanToken(ucan);else throw new NotAuthError$1('Error generating ucan');
172
+ // } else throw new NotAuthenticated('No access token');
173
+ }
174
+ //
175
+ // await verifyUcan(accessToken, {audience: ucan_audience || params.ucan_aud, requiredCapabilities})
176
+ // .catch(err => {
177
+ // console.error('error verifying ucan', err);
178
+ // throw new NotAuthenticated('Could not verify ucan: ' + err.message);
179
+ // });
180
+ const decodedUcan = await validateUcan(accessToken).catch(err => {
181
+ console.log('Could not validate ucan during authentication: ', err.message);
182
+ const errObj = {
183
+ code: 0,
184
+ message: 'Unknown Issue Validating Ucan'
185
+ };
186
+ if (err.message.indexOf('Expired.') > -1) {
187
+ errObj.code = 1;
188
+ errObj.message = 'Expired Ucan';
189
+ }
190
+ throw new Error(errObj.message);
191
+ });
192
+ const result = {
193
+ accessToken,
194
+ authentication: {
195
+ strategy: 'jwt',
196
+ accessToken
197
+ }
198
+ };
199
+ if (entity === null) {
200
+ return result;
201
+ }
202
+ let value;
203
+ const coreEntity = _get(params, [core_path, entity]);
204
+ if (!coreEntity) {
205
+ const entityId = await this.getEntityId(result, {
206
+ ...params,
207
+ loginId,
208
+ query: {
209
+ did: decodedUcan == null ? void 0 : decodedUcan.payload.aud
210
+ }
211
+ });
212
+ value = await this.getEntity(entityId, params);
213
+ } else value = coreEntity;
214
+ return {
215
+ ...result,
216
+ [entity]: value
217
+ };
218
+ }
219
+ async parse(req) {
220
+ const {
221
+ header,
222
+ schemes
223
+ } = this.configuration;
224
+ const headerValue = req.headers && req.headers[header.toLowerCase()];
225
+ if (!headerValue || typeof headerValue !== 'string') {
226
+ return null;
227
+ }
228
+ const [, scheme, schemeValue] = headerValue.match(SPLIT_HEADER) || [];
229
+ const hasScheme = scheme && schemes.some(current => new RegExp(current, 'i').test(scheme));
230
+ if (scheme && !hasScheme) {
231
+ return null;
232
+ }
233
+ return {
234
+ strategy: this.name,
235
+ accessToken: hasScheme ? schemeValue : headerValue
236
+ };
237
+ }
238
+ }
239
+
240
+ class NotAuthError extends Error {
241
+ constructor(message) {
242
+ super(message);
243
+ }
244
+ }
245
+ class AuthService extends AuthenticationService {
246
+ constructor(app, configKey = 'authentication', opts = {}) {
247
+ const {
248
+ NotAuthenticated,
249
+ ...rest
250
+ } = opts;
251
+ super(app, configKey, rest);
252
+ this.options = void 0;
253
+ this.app = app;
254
+ this.options = {
255
+ NotAuthenticated
256
+ };
257
+ }
258
+ async create(data, params) {
259
+ var _this$options, _params;
260
+ const NotAuth = ((_this$options = this.options) == null ? void 0 : _this$options.NotAuthenticated) || NotAuthError;
261
+ const {
262
+ entity,
263
+ service,
264
+ ucan_path = 'ucan'
265
+ } = this.app.get('authentication');
266
+ const authStrategies = ((_params = params) == null ? void 0 : _params.authStrategies) || this.configuration.authStrategies;
267
+ if (!params) params = {};
268
+ if (!authStrategies.length) {
269
+ throw new NotAuth('No authentication strategies allowed for creating a JWT (`authStrategies`)');
270
+ }
271
+ const authResult = await this.authenticate(data, params, ...authStrategies).catch(err => {
272
+ throw new Error(err.message);
273
+ });
274
+ if (authResult.accessToken) {
275
+ return authResult;
276
+ }
277
+ const did = data.did || _get(authResult, [entity, 'did']);
278
+ let ucan = data.ucan || _get(authResult, [entity, 'ucan']);
279
+ if (!did) throw new Error('No did audience provided');
280
+ if (!ucan) throw new Error('No ucan provided to authentication call');
281
+ // const {secret} = this.configuration;
282
+ const validatedUcan = await validateUcan(ucan).catch(err => {
283
+ console.log('Could not validate ucan creating authentication: ', err.message);
284
+ const errObj = {
285
+ code: 0,
286
+ message: 'Unknown Issue Validating Ucan'
287
+ };
288
+ if (err.message.indexOf('Expired.') > -1) {
289
+ errObj.code = 1;
290
+ errObj.message = 'Expired Ucan';
291
+ }
292
+ console.warn('Could not validate ucan creating authentication', ucan, errObj.message);
293
+ return null;
294
+ });
295
+ if (!validatedUcan) {
296
+ const parsed = parseUcan(ucan);
297
+ let {
298
+ secret
299
+ } = this.app.get('authentication');
300
+ const issuer = encodeKeyPair({
301
+ secretKey: secret
302
+ });
303
+ ucan = await buildUcan({
304
+ audience: parsed.payload.aud,
305
+ issuer,
306
+ lifetimeInSeconds: 60 * 60 * 24 * 60,
307
+ capabilities: parsed.payload.att
308
+ });
309
+ params.admin_pass = true;
310
+ await this.app.service(service).patch(_get(authResult, [entity, '_id']), {
311
+ [ucan_path]: ucanToken(ucan)
312
+ }, {
313
+ ...params
314
+ });
315
+ }
316
+ const accessToken = ucanToken(ucan);
317
+ return {
318
+ accessToken,
319
+ ...authResult,
320
+ authentication: {
321
+ ...authResult.authentication,
322
+ payload: accessToken
323
+ }
324
+ };
325
+ }
326
+ }
327
+
328
+ class CoreCall {
329
+ constructor(service, context, coreOptions) {
330
+ var _context$params;
331
+ this.context = void 0;
332
+ this.service = void 0;
333
+ this.core = void 0;
334
+ this.entity = void 0;
335
+ this.service = service;
336
+ this.context = context;
337
+ const entity = (context.app.get('authentication') || {
338
+ entity: 'login'
339
+ }).entity || 'login';
340
+ this.entity = entity;
341
+ const core = ((_context$params = context.params) == null ? void 0 : _context$params.core) || {};
342
+ if (!core[entity]) core[entity] = context.params[entity];
343
+ this.core = {
344
+ ...core,
345
+ ...coreOptions
346
+ };
347
+ }
348
+ async get(id, params = {}) {
349
+ var _this$context$app;
350
+ const {
351
+ core_path
352
+ } = this.context.app.get('authentication');
353
+ return (_this$context$app = this.context.app) == null ? void 0 : _this$context$app.service(this.service).get(id, {
354
+ ...params,
355
+ [this.entity]: params[this.entity],
356
+ ...{
357
+ [core_path]: this.core
358
+ }
359
+ });
360
+ }
361
+ async find(params = {}) {
362
+ var _this$context$app2;
363
+ const {
364
+ core_path
365
+ } = this.context.app.get('authentication');
366
+ return (_this$context$app2 = this.context.app) == null ? void 0 : _this$context$app2.service(this.service).find({
367
+ ...params,
368
+ [this.entity]: params[this.entity],
369
+ skip_hooks: true,
370
+ admin_pass: true,
371
+ ...{
372
+ [core_path]: this.core
373
+ }
374
+ });
375
+ }
376
+ async create(data, params = {}) {
377
+ var _this$context$app3;
378
+ const {
379
+ core_path
380
+ } = this.context.app.get('authentication');
381
+ return (_this$context$app3 = this.context.app) == null ? void 0 : _this$context$app3.service(this.service).create(data, {
382
+ ...params,
383
+ [this.entity]: params[this.entity],
384
+ ...{
385
+ [core_path]: this.core
386
+ }
387
+ });
388
+ }
389
+ async patch(id, data, params = {}) {
390
+ var _this$context$app4;
391
+ const {
392
+ core_path
393
+ } = this.context.app.get('authentication');
394
+ return (_this$context$app4 = this.context.app) == null ? void 0 : _this$context$app4.service(this.service).patch(id, data, {
395
+ ...params,
396
+ [this.entity]: params[this.entity],
397
+ ...{
398
+ [core_path]: this.core
399
+ }
400
+ });
401
+ }
402
+ async update(id, data, params = {}) {
403
+ var _this$context$app5;
404
+ const {
405
+ core_path
406
+ } = this.context.app.get('authentication');
407
+ return (_this$context$app5 = this.context.app) == null ? void 0 : _this$context$app5.service(this.service).update(id, data, {
408
+ ...params,
409
+ [this.entity]: params[this.entity],
410
+ ...{
411
+ [core_path]: this.core
412
+ }
413
+ });
414
+ }
415
+ async remove(id, params = {}) {
416
+ var _this$context$app6;
417
+ const {
418
+ core_path
419
+ } = this.context.app.get('authentication');
420
+ return (_this$context$app6 = this.context.app) == null ? void 0 : _this$context$app6.service(this.service).remove(id, {
421
+ ...params,
422
+ [this.entity]: params[this.entity],
423
+ ...{
424
+ [core_path]: this.core
425
+ }
426
+ });
427
+ }
428
+ async _get(id, params = {}) {
429
+ var _this$context$app7;
430
+ const {
431
+ core_path
432
+ } = this.context.app.get('authentication');
433
+ return (_this$context$app7 = this.context.app) == null ? void 0 : _this$context$app7.service(this.service)._get(id, {
434
+ ...params,
435
+ [this.entity]: params[this.entity],
436
+ ...{
437
+ [core_path]: this.core
438
+ }
439
+ });
440
+ }
441
+ async _find(params = {}) {
442
+ var _this$context$app8;
443
+ const {
444
+ core_path
445
+ } = this.context.app.get('authentication');
446
+ return (_this$context$app8 = this.context.app) == null ? void 0 : _this$context$app8.service(this.service)._find({
447
+ ...params,
448
+ [this.entity]: params[this.entity],
449
+ ...{
450
+ [core_path]: this.core
451
+ }
452
+ });
453
+ }
454
+ async _create(data, params = {}) {
455
+ var _this$context$app9;
456
+ const {
457
+ core_path
458
+ } = this.context.app.get('authentication');
459
+ return (_this$context$app9 = this.context.app) == null ? void 0 : _this$context$app9.service(this.service)._create(data, {
460
+ ...params,
461
+ [this.entity]: params[this.entity],
462
+ ...{
463
+ [core_path]: this.core
464
+ }
465
+ });
466
+ }
467
+ async _patch(id, data, params = {}) {
468
+ var _this$context$app10;
469
+ const {
470
+ core_path
471
+ } = this.context.app.get('authentication');
472
+ return (_this$context$app10 = this.context.app) == null ? void 0 : _this$context$app10.service(this.service)._patch(id, data, {
473
+ ...params,
474
+ [this.entity]: params[this.entity],
475
+ ...{
476
+ [core_path]: this.core
477
+ }
478
+ });
479
+ }
480
+ async _update(id, data, params = {}) {
481
+ var _this$context$app11;
482
+ const {
483
+ core_path
484
+ } = this.context.app.get('authentication');
485
+ return (_this$context$app11 = this.context.app) == null ? void 0 : _this$context$app11.service(this.service)._update(id, data, {
486
+ ...params,
487
+ [this.entity]: params[this.entity],
488
+ ...{
489
+ [core_path]: this.core
490
+ }
491
+ });
492
+ }
493
+ async _remove(id, params = {}) {
494
+ var _this$context$app12;
495
+ const {
496
+ core_path
497
+ } = this.context.app.get('authentication');
498
+ return (_this$context$app12 = this.context.app) == null ? void 0 : _this$context$app12.service(this.service)._remove(id, {
499
+ ...params,
500
+ [this.entity]: params[this.entity],
501
+ ...{
502
+ [core_path]: this.core
503
+ }
504
+ });
505
+ }
506
+ }
507
+
508
+ const existsPath = '_exists';
509
+ const getExists = context => {
510
+ const path = context.app.get('existsPath') || existsPath;
511
+ return _get(context.params, `core.${path}.${context.path}.${context.id}`) || undefined;
512
+ };
513
+ const loadExists = async (context, options) => {
514
+ let ex = getExists(context);
515
+ if (!ex && context.id) {
516
+ ex = await new CoreCall(context.path, context, {
517
+ skipJoins: (options == null ? void 0 : options.skipJoins) !== false
518
+ }).get(context.id, {
519
+ exists_check: true,
520
+ admin_pass: true,
521
+ skip_hooks: true,
522
+ ...((options == null ? void 0 : options.params) || {})
523
+ });
524
+ }
525
+ return ex;
526
+ };
527
+ const setExists = (context, val) => {
528
+ const path = context.app.get('existsPath') || existsPath;
529
+ context.params = _set(context.params, `core.${path}.${context.path}.${(val == null ? void 0 : val._id) || context.id}`, val);
530
+ return context;
531
+ };
532
+
533
+ const SUPERUSER = '*';
534
+ const anyAuth = '*';
535
+ const noThrow = '$';
536
+ const noThrowAuth = async context => {
537
+ const config = context.app.get('authentication');
538
+ const entity = _get(context, ['auth', config.entity]);
539
+ if (entity) {
540
+ context = _set(context, [config.core_path, config.entity], entity);
541
+ }
542
+ try {
543
+ context = await authenticate('jwt')(context).catch(() => {
544
+ return context;
545
+ });
546
+ } catch (e) {
547
+ return context;
548
+ }
549
+ return context;
550
+ };
551
+ const bareAuth = async context => {
552
+ const config = context.app.get('authentication');
553
+ const entity = _get(context, ['auth', config.entity]);
554
+ if (entity) context = _set(context, [config.core_path, config.entity], entity);
555
+ return authenticate('jwt')(context);
556
+ };
557
+ const verifyOne = async (ucan, options, log) => {
558
+ try {
559
+ var _v;
560
+ let v = await verifyUcan(ucan, options);
561
+ if (!((_v = v) != null && _v.ok) && options.requiredCapabilities) {
562
+ const newCapabilities = options.requiredCapabilities.map(a => {
563
+ if (a.capability.can !== SUPERUSER) a.capability.can.segments = ['*'];
564
+ return a;
565
+ });
566
+ if (log) console.log('set new req capabilities', newCapabilities, parseUcan(ucan));
567
+ v = await verifyUcan(ucan, {
568
+ ...options,
569
+ requiredCapabilities: newCapabilities
570
+ });
571
+ if (log) console.log('Second verification result:', v);
572
+ }
573
+ return v;
574
+ } catch (e) {
575
+ return {
576
+ ok: false,
577
+ err: [e.message]
578
+ };
579
+ }
580
+ };
581
+ const orVerifyLoop = async (arr, log) => {
582
+ let v = {
583
+ ok: false,
584
+ value: []
585
+ };
586
+ try {
587
+ for (const i in arr) {
588
+ var _v2;
589
+ if (log) console.log('or verify loop', arr[i], parseUcan(arr[i].ucan));
590
+ if (!((_v2 = v) != null && _v2.ok)) {
591
+ const {
592
+ ucan,
593
+ ...options
594
+ } = arr[i];
595
+ v = await verifyOne(ucan, options, log);
596
+ if (log) console.log('got in verify loop', v);
597
+ } else break;
598
+ }
599
+ return v;
600
+ } catch (e) {
601
+ return {
602
+ ok: false,
603
+ err: [e.message]
604
+ };
605
+ }
606
+ };
607
+ const verifyAgainstReqs = (reqs, config, options) => {
608
+ return async context => {
609
+ var _v3;
610
+ const log = options == null ? void 0 : options.log;
611
+ const ucan = _get(context.params, config.client_ucan);
612
+ const audience = (options == null ? void 0 : options.audience) || _get(context.params, config.ucan_aud);
613
+ if (log) console.log('verify against reqs', reqs);
614
+ let vMethod;
615
+ const or = (options == null ? void 0 : options.or) || [];
616
+ if (ucan && (or === '*' || or.includes(context.method))) vMethod = (uc, methodOpts) => orVerifyLoop((reqs || []).map(a => {
617
+ return {
618
+ ucan: uc || ucan,
619
+ audience: (methodOpts == null ? void 0 : methodOpts.aud) || audience,
620
+ requiredCapabilities: [a]
621
+ };
622
+ }), log);else vMethod = (uc, methodOpts) => verifyOne(uc || ucan, {
623
+ audience: (methodOpts == null ? void 0 : methodOpts.aud) || audience,
624
+ requiredCapabilities: reqs
625
+ }, log);
626
+ let v = await vMethod();
627
+ if (log) console.log('first verify try', v);
628
+ if ((_v3 = v) != null && _v3.ok) return v;
629
+ const cs = ((options == null ? void 0 : options.cap_subjects) || []).filter(a => !!a);
630
+ if (log) console.log('check cap_subjects', cs);
631
+ if (cs) {
632
+ const configuration = (config == null ? void 0 : config.loginConfig) || context.app.get('authentication');
633
+ const loginCheckId = String(_get(context.params, `${configuration.entity}._id` || ''));
634
+ const caps = await new CoreCall(configuration.capability_service || 'caps', context).find({
635
+ query: {
636
+ $limit: cs.length,
637
+ subject: {
638
+ $in: cs
639
+ }
640
+ },
641
+ skip_hooks: true,
642
+ admin_pass: true
643
+ }).catch(err => console.log(`Error finding caps in ucan auth: ${err.message}`));
644
+ if (log) console.log('caps', caps);
645
+ if (caps != null && caps.data) {
646
+ for (const cap of caps.data) {
647
+ for (const k in cap.caps || {}) {
648
+ if (log) console.log('check cap', k, cap.caps[k].logins, loginCheckId);
649
+ if ((cap.caps[k].logins || []).map(a => String(a)).includes(loginCheckId)) {
650
+ var _v4;
651
+ try {
652
+ const ucanString = ucanToken(cap.caps[k].ucan);
653
+ if (log) console.log('got ucan string', ucanString);
654
+ if (ucanString) {
655
+ v = await vMethod(ucanString, {
656
+ aud: cap.did
657
+ });
658
+ if (log) console.log('tried v on cap', v);
659
+ }
660
+ } catch (e) {
661
+ console.log(`Error verifying ucan from cap: ${cap._id}. Err:${e.message}`);
662
+ }
663
+ if (options != null && options.log) console.log('tried v on cap', v);
664
+ if ((_v4 = v) != null && _v4.ok) return v;
665
+ }
666
+ }
667
+ }
668
+ }
669
+ }
670
+ return v;
671
+ };
672
+ };
673
+ const modelCapabilities = (reqs, config) => {
674
+ const rootIssuer = encodeKeyPair({
675
+ secretKey: config.secret
676
+ }).did();
677
+ if (!Array.isArray(reqs)) return [];
678
+ return reqs.map(a => {
679
+ return {
680
+ capability: Array.isArray(a) ? genCapability({
681
+ with: {
682
+ scheme: config.defaultScheme,
683
+ hierPart: config.defaultHierPart
684
+ },
685
+ can: {
686
+ namespace: a[0],
687
+ segments: typeof a[1] === 'string' ? [a[1]] : a[1]
688
+ }
689
+ }, config) : genCapability(a, config),
690
+ rootIssuer
691
+ };
692
+ });
693
+ };
694
+ const checkUcan = (requiredCapabilities, options) => {
695
+ return async context => {
696
+ var _v5;
697
+ const configuration = (options == null ? void 0 : options.loginConfig) || context.app.get('authentication');
698
+ let v = {
699
+ ok: false,
700
+ value: []
701
+ };
702
+ const reqs = modelCapabilities(requiredCapabilities, configuration);
703
+ if (reqs.length) {
704
+ v = await verifyAgainstReqs(reqs, configuration, options)(context);
705
+ /** if the anyAuth setting is used along with specialChange, a user could get through to this point despite not being authenticated, so this step does not allow a pass for anyAuth setting even though no requiredCapabilities are present - because it was intended to throw if not authenticated unless special change conditions are met */
706
+ } else if (requiredCapabilities !== '*') v.ok = true;
707
+ if ((_v5 = v) != null && _v5.ok) {
708
+ context.params.authenticated = true;
709
+ context.params.canU = true;
710
+ return context;
711
+ } else {
712
+ var _v6;
713
+ // if (!v?.ok) {
714
+ // let hasSplitNamespace = false;
715
+ // const reducedReqs: Array<RequiredCapability> = [];
716
+ // reqs.forEach((req, i) => {
717
+ // const splt = (_get<RequiredCapability, string>(req, 'capability.can.namespace') || '').split(':')
718
+ // if (splt[1]) {
719
+ // req = _set(req, 'capability.can.namespace', splt[0]);
720
+ // hasSplitNamespace = true;
721
+ // }
722
+ // reducedReqs.push(req)
723
+ // })
724
+ // if (hasSplitNamespace) v = await verifyAgainstReqs(reqs, configuration as VerifyConfig, options)(context);
725
+ // }
726
+ if (options != null && options.log) console.log('checking special change', options == null ? void 0 : options.specialChange);
727
+ if (options != null && options.specialChange) {
728
+ if (options.specialChange === anyAuth) {
729
+ context.params.canU = true;
730
+ return context;
731
+ } else if (Array.isArray(options.specialChange)) {
732
+ if (['create', 'patch', 'update'].includes(context.method)) {
733
+ if (Array.isArray(context.data)) throw new Error('No multi data allowed with special change');
734
+ for (const k in context.data || {}) {
735
+ if (['$set', '$unset', '$addToSet', '$pull', '$push'].includes(k)) {
736
+ for (const sk in context.data[k] || {}) {
737
+ if (!options.specialChange.includes(sk)) {
738
+ const spl = sk.split('.');
739
+ if (spl.length === 1) delete context.data[k][sk];else if (!options.specialChange.includes(spl[0])) delete context.data[k][sk];
740
+ }
741
+ }
742
+ } else if (!options.specialChange.includes(k)) delete context.data[k];
743
+ }
744
+ context.params.canU = true;
745
+ return context;
746
+ }
747
+ }
748
+ }
749
+ if ((_v6 = v) != null && _v6.ok) {
750
+ context.params.authenticated = true;
751
+ context.params.canU = true;
752
+ return context;
753
+ } else {
754
+ var _v7;
755
+ //If creator pass enabled, check to see if the auth login is the creator of the record
756
+ const {
757
+ loginPass
758
+ } = options || {
759
+ loginPass: [[['*'], ['nonExistentMethod']]]
760
+ };
761
+ if (loginPass != null && loginPass.length) {
762
+ //object of scrubbed data object for pass that includes only limited access or full context.data object if no limits were present
763
+ let scrubbedData = {};
764
+ //scruData defaults to true - is only set to false
765
+ let scrubData = true;
766
+ const checkLoginPass = async lpass => {
767
+ let methodsOnly = [];
768
+ const allMethods = lpass[1] === '*';
769
+ let methodIdx = -1;
770
+ if (allMethods) methodIdx = 0;else {
771
+ //separate out any field specific methods e.g. patch/name,avatar
772
+ methodsOnly = lpass[1].map(a => a.split('/')[0]);
773
+ methodIdx = methodsOnly.indexOf(context.method);
774
+ }
775
+ /**ensure loginPass is allowed for this method*/
776
+ if (methodIdx > -1) {
777
+ /**retrieve existing record to check ids for login id*/
778
+ const existing = await loadExists(context, {
779
+ params: options == null ? void 0 : options.existingParams
780
+ });
781
+ let loginOk = false;
782
+ /** function for comparing record login id with context login*/
783
+ const checkLogin = (recordLoginPassId, loginIdPath = '_id') => {
784
+ const loginCheckId = _get(context.params, `${configuration.entity}.${loginIdPath}`);
785
+ /**Make sure both are present to avoid pass on undefined*/
786
+ if (loginCheckId && recordLoginPassId) {
787
+ /** change login path result to array no matter what */
788
+ const checkArr = Array.isArray(loginCheckId) ? loginCheckId.map(a => String(a)) : [String(loginCheckId)];
789
+ if (Array.isArray(recordLoginPassId)) {
790
+ /**loop through to see if there is a match present use for loops for performance instead of some*/
791
+ for (let i = 0; i < checkArr.length; i++) {
792
+ const checkId = String(checkArr[i]);
793
+ for (let rl = 0; rl < recordLoginPassId.length;) {
794
+ const rlId = String(recordLoginPassId[rl]);
795
+ if (rlId === checkId) loginOk = true;else rl++;
796
+ }
797
+ if (loginOk) return;
798
+ }
799
+ } else if (checkArr.includes(String(recordLoginPassId))) {
800
+ return loginOk = true;
801
+ }
802
+ } else return;
803
+ };
804
+ if (existing) {
805
+ context = setExists(context, existing);
806
+ for (const passPath of lpass[0] || []) {
807
+ const spl = String(passPath).split('/');
808
+ if (spl[0].includes('*')) {
809
+ const spl2 = spl[0].split('*');
810
+ const obj = _get(existing, spl2[0]);
811
+ if (obj && typeof obj === 'object') {
812
+ if (Array.isArray(obj)) {
813
+ /** IF array, iterate through array and check the sub-path */
814
+ for (const o of obj) {
815
+ checkLogin(_get(o, spl2[1]), spl[1] || '_id');
816
+ if (loginOk) break;
817
+ }
818
+ } else {
819
+ /** IF object, iterate through object and check the sub-path */
820
+ for (const k in obj) {
821
+ checkLogin(_get(obj, `${k}.${spl2[1]}`), spl[1] || '_id');
822
+ if (loginOk) break;
823
+ }
824
+ }
825
+ }
826
+ } else checkLogin(_get(existing, spl[0]), spl[1] || '_id');
827
+ }
828
+ }
829
+ if (loginOk) {
830
+ v.ok = true;
831
+ /**loginPass is true - but check for granular field permissions such as patch/owner,color,status that imply limited permission*/
832
+ //TODO: possibly a throw option here. If loginPass is ok, it will go forward, but could send an empty or modified patch object
833
+ if (lpass[1] !== '*' && !['find', 'get', 'remove'].some(a => lpass[1].includes(a))) {
834
+ const currentMethod = allMethods ? '*' : lpass[1][methodIdx];
835
+ const splitMethod = currentMethod.split('/')[0];
836
+ //check if current method contains a split '/' signaling limited permission check
837
+ if (splitMethod !== currentMethod) {
838
+ //get an array of the allowed fields
839
+ const fields = currentMethod.split('/').slice(1).join('').split(',') || [];
840
+ for (const field of fields) {
841
+ const topLevel = _get(context.data, field);
842
+ if (topLevel) scrubbedData = _set(scrubbedData, field, topLevel);else {
843
+ for (const operator of ['$addToSet', '$pull']) {
844
+ const operatorLevel = _get(context.data, `${operator}.${field}`);
845
+ if (operatorLevel) scrubbedData = _set(scrubbedData, `${operator}.${field}`, operatorLevel);
846
+ }
847
+ }
848
+ }
849
+ } else scrubData = false;
850
+ } else scrubData = false;
851
+ }
852
+ }
853
+ };
854
+ for await (const lpass of loginPass) {
855
+ if (scrubData) await checkLoginPass(lpass);else break;
856
+ }
857
+ if (scrubData) context = _set(context, 'data', scrubbedData);
858
+ }
859
+ if ((_v7 = v) != null && _v7.ok) {
860
+ context.params.authenticated = true;
861
+ context.params.canU = true;
862
+ return context;
863
+ } else {
864
+ if (options != null && options.log) console.error('Ucan capabilities requirements not met: ', v, context.type, context.path);
865
+ if (!(options != null && options.noThrow)) throw new Error('Missing proper capabilities for this action: ' + context.type + ': ' + context.path + ' - ' + context.method);else {
866
+ context.params._no_throw_error = {
867
+ type: context.type,
868
+ method: context.method,
869
+ path: context.path
870
+ };
871
+ return context;
872
+ }
873
+ }
874
+ }
875
+ }
876
+ };
877
+ };
878
+ const ucanAuth = (requiredCapabilities, options) => {
879
+ return async context => {
880
+ const configuration = context.app.get('authentication');
881
+ const core_path = configuration.core_path || 'core';
882
+ const entity = configuration.entity || 'login';
883
+ const existingLogin = _get(context.params, [core_path, entity]) || _get(context.params, 'login') || _get(context.params.connection, entity);
884
+ if (existingLogin) context.params[entity] = existingLogin;
885
+ const loginId = typeof existingLogin === 'string' ? existingLogin : existingLogin == null ? void 0 : existingLogin._id;
886
+ const hasLogin = !!(existingLogin && (typeof existingLogin === 'string' || !!loginId));
887
+ const existingUcan = _get(context.params, configuration.client_ucan || 'client_ucan');
888
+ if (options != null && options.log) console.log('ucan auth', 'hasLogin', hasLogin, 'loginId', loginId, 'existingUcan', !!existingUcan, 'core_path', core_path, 'entity', entity, 'core', context.params[core_path], 'params login', context.params.login, 'required capabilities', requiredCapabilities);
889
+ //Below for passing through auth with no required capabilities
890
+ if (requiredCapabilities === noThrow || requiredCapabilities && requiredCapabilities[context.method] === noThrow) return hasLogin ? context : await noThrowAuth(context);
891
+ const adminPass = ((options == null ? void 0 : options.adminPass) || []).includes(context.method) && (_get(context.params, 'admin_pass') || _get(context.params, [configuration.core_path, 'admin_pass']));
892
+ // If no login is present and no client UCAN is provided, perform authentication. Otherwise, reuse existing state/ucan.
893
+ if (!hasLogin && !existingUcan) context = adminPass || options != null && options.specialChange ? await noThrowAuth(context) : await bareAuth(context);
894
+ if (requiredCapabilities === anyAuth && !(options != null && options.specialChange)) {
895
+ context.params.authenticated = !!context.params[entity];
896
+ return context;
897
+ }
898
+ if (adminPass) return context;
899
+ if (!requiredCapabilities) return context;
900
+ return await checkUcan(requiredCapabilities, options)(context);
901
+ };
902
+ };
903
+ const allUcanAuth = (methods, options) => {
904
+ return async context => {
905
+ const config = context.app.get('authentication');
906
+ // if a login is already present in params[core_path][entity], don't overwrite it
907
+ const corePath = config.core_path || 'core';
908
+ const entityKey = config.entity || 'login';
909
+ const existingLogin = _get(context.params, [corePath, entityKey]);
910
+ if (!existingLogin) {
911
+ const entity = _get(context, ['auth', entityKey]);
912
+ if (entity) context = _set(context, [corePath, entityKey], entity);
913
+ }
914
+ if (context.type === 'before') {
915
+ const {
916
+ method
917
+ } = context;
918
+ if (methods[method] || methods['all']) {
919
+ return await ucanAuth(methods[method] || methods['all'], options)(context);
920
+ } else return context;
921
+ } else return context;
922
+ };
923
+ };
924
+
925
+ const updateUcan = () => {
926
+ return async context => {
927
+ const {
928
+ add = [],
929
+ remove = []
930
+ } = context.data;
931
+ //ensure capabilities were passed
932
+ if (!(add != null && add.length) && !(remove != null && remove.length)) throw new Error('No new capabilities passed');
933
+ //check ability to edit the affected capabilities
934
+ const {
935
+ secret,
936
+ ucan_aud,
937
+ entity,
938
+ ucan
939
+ } = context.app.get('authentication');
940
+ const rootIssuer = encodeKeyPair({
941
+ secretKey: secret
942
+ }).did();
943
+ const checkAbilities = stackAbilities([...add, ...remove]);
944
+ const canEdit = await verifyUcan(_get(context.params, [entity, ucan]), {
945
+ audience: _get(context.params, ucan_aud),
946
+ requiredCapabilities: checkAbilities.map(a => {
947
+ return {
948
+ //TODO: possibly READ shouldn't have the ability to allow others to READ
949
+ capability: a,
950
+ rootIssuer
951
+ };
952
+ })
953
+ });
954
+ if (!(canEdit != null && canEdit.ok)) throw new Error('You don\'t have sufficient capabilities to grant those capabilities');
955
+ //prep edited ucan
956
+ const subjectId = context.id;
957
+ const service = context.data.service || 'logins';
958
+ const path = context.data.path || 'ucan';
959
+ const subject = await new CoreCall(service, context, {
960
+ skipJoins: true
961
+ }).get(subjectId);
962
+ const decoded = parseUcan(_get(subject, path));
963
+ const {
964
+ aud,
965
+ att,
966
+ fct,
967
+ nbf,
968
+ prf
969
+ } = decoded.payload;
970
+ let capabilities = [...att];
971
+ if (remove != null && remove.length) capabilities = reduceAbilities(remove, att);
972
+ if (add != null && add.length) capabilities = stackAbilities([...att, ...add]);
973
+ const raw = await buildUcan({
974
+ issuer: encodeKeyPair({
975
+ secretKey: secret
976
+ }),
977
+ audience: aud,
978
+ lifetimeInSeconds: 60 * 60 * 24 * 60,
979
+ proofs: prf,
980
+ ...context.data,
981
+ capabilities
982
+ });
983
+ const encoded = ucanToken(raw);
984
+ const isValid = await validateUcan(encoded);
985
+ if (!isValid) throw new Error('Invalid ucan generated when updating');
986
+ const patched = await new CoreCall(service, context).patch(subjectId, {
987
+ [path]: encoded
988
+ });
989
+ context.result = {
990
+ raw: context.data,
991
+ encoded,
992
+ subject: patched
993
+ };
994
+ return context;
995
+ };
996
+ };
997
+
998
+ export { AuthService, CoreCall, NotAuthError, UcanStrategy, allUcanAuth, anyAuth, bareAuth, checkUcan, existsPath, getExists, loadExists, modelCapabilities, noThrow, noThrowAuth, orVerifyLoop, setExists, ucanAuth, updateUcan, verifyAgainstReqs };
2
999
  //# sourceMappingURL=index.modern.js.map