feathers-ucan 0.0.34 → 0.0.36

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.
package/README.md CHANGED
@@ -113,7 +113,7 @@ Note: the way ucans works, you cannot simply provide a “greatest ability” an
113
113
  ```jsx
114
114
  declare type UcanAuthOptions = {
115
115
  creatorPass?: '*' | Array<string>,
116
- loginPass?: [Array<string>, Array<string> | '*'],
116
+ loginPass?: Array<[Array<string>, Array<string> | '*']>,
117
117
  or?: Array<string>,
118
118
  adminPass?: Array<string>
119
119
  }
@@ -121,7 +121,7 @@ declare type UcanAuthOptions = {
121
121
 
122
122
  ### This section needs to be reworked to be open-sourcable. This is too specific to our internal material still
123
123
  - **************************creatorPass:************************** allows for a pass if the `login._id` calling the method is the same as the record in question `record.createdBy.login`
124
- - **********************loginPass:********************** allows for a free pass list of record paths that match the `login._id` calling the method. The first element of the array are the paths such as `[owner.id]` (dot notation for nested paths). In the future we expect to add `$in` functionality that can handle nested arrays as well (the current version will pass an array that includes the correct id, but only a flat array of simple ObjectIds). The second element are the methods you want to allow this on ie: `['patch', 'create']`Use the `*` superuser for allowing all methods to pass. If you want more granular field permissions - such as only allowing `patch` for the fields `color` and `name`, we support that. You would write the second argument of loginPass with a `patch/color,name` as follows (this is the full loginPass argument to avoid confusion here) [[{first argument}], ['patch/color,name', 'create']] (allowed for create as well just to illustrate how this is used);
124
+ - **********************loginPass:********************** allows for a free pass list of record paths that match the `login._id` calling the method. This is an array of loginPass config options. The first element of each array are the paths such as `[owner.id]` (dot notation for nested paths). In the future we expect to add `$in` functionality that can handle nested arrays as well (the current version will pass an array that includes the correct id, but only a flat array of simple ObjectIds). The second element are the methods you want to allow this on ie: `['patch', 'create']`Use the `*` superuser for allowing all methods to pass. If you want more granular field permissions - such as only allowing `patch` for the fields `color` and `name`, we support that. You would write the second argument of loginPass with a `patch/color,name` as follows (this is the full loginPass argument to avoid confusion here) [[{first argument}], ['patch/color,name', 'create']] (allowed for create as well just to illustrate how this is used);
125
125
  - ********or:******** explains to run the `Capability` configuration passed to the ********allUcanAuth methods******** to be run as an or scenario instead of and. This is a significant extension of how ucans otherwise work. It will run multiple verify methods and if any pass, the auth will pass.
126
126
  - **********adminPass:********** allow internal call overrides of ucan requirements. This is important for writing functions that internal operations may need to perform like removing a created org if a hook isn’t successful. Calling this requires passing an array of methods as the value of the admin option (`Array<string>`) as well as setting `context.params.admin_pass` to `true` from within the feathers app (no client side overrides). The value of this property is an array of methods to allow `admin_pass` params on.
127
127
 
@@ -1 +1 @@
1
- export declare const VERSION = "0.0.34";
1
+ export declare const VERSION = "0.0.36";
@@ -15,9 +15,10 @@ export declare const anyAuth: AnyAuth;
15
15
  type NoThrow = '$';
16
16
  export declare const noThrow: NoThrow;
17
17
  export type CapabilityParts = Partial<Capability> | [string, Array<string> | string];
18
- declare type UcanAuthOptions = {
18
+ export declare type LoginPassOption = [Array<string>, Array<string> | '*'];
19
+ export declare type UcanAuthOptions = {
19
20
  creatorPass?: '*' | Array<string>;
20
- loginPass?: [Array<string>, Array<string> | '*'];
21
+ loginPass?: Array<LoginPassOption>;
21
22
  or?: Array<string>;
22
23
  adminPass?: Array<string>;
23
24
  };
package/lib/index.cjs CHANGED
@@ -1 +1 @@
1
- var e=require("symbol-ucan"),t=require("@feathersjs/authentication");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/r(require("long-timeout"));function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i.apply(this,arguments)}function o(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,c(e,t)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function c(e,t){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},c(e,t)}function u(e,t,r){return u=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(e){return!1}}()?Reflect.construct.bind():function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&c(i,r.prototype),i},u.apply(null,arguments)}function s(e){var t="function"==typeof Map?new Map:void 0;return s=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return u(e,arguments,a(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),c(r,e)},s(e)}function l(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)t.indexOf(r=o[n])>=0||(i[r]=e[r]);return i}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var h=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return o(t,e),t}(/*#__PURE__*/s(Error)),p=/(\S+)\s+(\S+)/,v=/*#__PURE__*/function(t){function r(){for(var e,r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(e=t.call.apply(t,[this].concat(n))||this).expirationTimers=new WeakMap,e}o(r,t);var a,c,u=r.prototype;return u.setAuthentication=function(e){e.verifyAccessToken=function(e){return{}},this.authentication=e},u.handleConnection=function(t,r,i){try{var o=this,a="logout"===t&&r.authentication&&i&&r.authentication.accessToken===i.accessToken,c=(i||{}).accessToken,u=function(){if(c&&"login"===t)return Promise.resolve(e.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){var t=1e3*(e||{payload:{exp:0}}).payload.exp-Date.now(),i=n.default.setTimeout(function(){return o.app.emit("disconnect",r)},t);n.default.clearTimeout(o.expirationTimers.get(r)),o.expirationTimers.set(r,i),r.authentication={strategy:o.name,accessToken:c}});("disconnect"===t||a)&&(delete r[o.configuration.entity],delete r.authentication,n.default.clearTimeout(o.expirationTimers.get(r)),o.expirationTimers.delete(r))}();return Promise.resolve(u&&u.then?u.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},u.verifyConfiguration=function(){for(var e=["entity","entityId","service","header","schemes","audience"],t=0,r=Object.keys(this.configuration);t<r.length;t++){var n=r[t];if(!e.includes(n))throw new Error("Invalid ucanStrategy option 'authentication."+this.name+"."+n+"'. 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(e){return Promise.resolve({})},u.getEntity=function(t,r){try{var n=this,o=n.entityService,a=n.configuration.entity;if(null===o)throw new h("Could not find entity service");return Promise.resolve(n.getEntityQuery(r)).then(function(n){var c=Object.assign({},e._unset(r,"provider"),{query:n});return Promise.resolve(o.get(t,c)).then(function(e){var n;return r.provider?o.get(t,i({},r,((n={})[a]=e,n))):e})})}catch(e){return Promise.reject(e)}},u.getEntityId=function(e,t){try{var r=t.query,n=t.loginId;if(n)return Promise.resolve(n);var o,a,c=this.configuration,u=c.service,s=c.core_path,l=void 0===s?"core":s,f=((o={query:i({},r,{$limit:1})})[l]=i({skipJoins:!0},t[l]),o);return Promise.resolve(null==(a=this.app)?void 0:a.service(u).find(i({},f,{skipJoins:!0}))).then(function(e){if(e.total)return e.data[0]._id;throw new h("Could not find login associated with this ucan")})}catch(e){return Promise.reject(e)}},u.authenticate=function(t,r){try{var n=this,o=t.accessToken,a=t.loginId,c=t.ucan,u=n.configuration,s=u.entity,l=u.core_path;if(!o){if(!c)throw new h("Error generating ucan");o=e.ucanToken(c)}return Promise.resolve(e.validateUcan(o).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(t){function c(){var e;return i({},f,((e={})[s]=u,e))}var u,f={accessToken:o,authentication:{strategy:"jwt",accessToken:o}};if(null===s)return f;var h=e._get(r,[l,s]),p=function(){if(!h)return Promise.resolve(n.getEntityId(f,i({},r,{loginId:a,query:{did:null==t?void 0:t.payload.aud}}))).then(function(e){return Promise.resolve(n.getEntity(e,r)).then(function(e){u=e})});u=h}();return p&&p.then?p.then(c):c()})}catch(e){return Promise.reject(e)}},u.parse=function(e){try{var t=this.configuration,r=t.schemes,n=e.headers&&e.headers[t.header.toLowerCase()];if(!n||"string"!=typeof n)return Promise.resolve(null);var i=n.match(p)||[],o=i[1],a=i[2],c=o&&r.some(function(e){return new RegExp(e,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:n})}catch(e){return Promise.reject(e)}},a=r,(c=[{key:"configuration",get:function(){var e,r=(null==(e=this.authentication)?void 0:e.configuration)||{service:void 0,entity:void 0,entityId:void 0};return i({service:r.service,entity:r.entity,entityId:r.entityId,header:"Authorization",schemes:["Bearer","JWT"]},t.prototype.configuration)}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,"symbol"==typeof(i=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(n.key))?i:String(i),n)}var i}(a.prototype,c),Object.defineProperty(a,"prototype",{writable:!1}),r}(t.AuthenticationBaseStrategy),d=["NotAuthenticated"],m=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return o(t,e),t}(/*#__PURE__*/s(Error)),y=/*#__PURE__*/function(t){function r(e,r,n){var i;void 0===r&&(r="authentication"),void 0===n&&(n={});var o=n.NotAuthenticated,a=l(n,d);return(i=t.call(this,e,r,a)||this).options=void 0,i.app=e,i.options={NotAuthenticated:o},i}return o(r,t),r.prototype.create=function(t,r){try{var n,o,a=this,c=(null==(n=a.options)?void 0:n.NotAuthenticated)||m,u=a.app.get("authentication"),s=u.entity,l=u.service,f=u.ucan_path,h=void 0===f?"ucan":f,p=(null==(o=r)?void 0:o.authStrategies)||a.configuration.authStrategies;if(r||(r={}),!p.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(a.authenticate.apply(a,[t,r].concat(p)).catch(function(e){throw new Error(e.message)})).then(function(n){if(n.accessToken)return n;var o=t.did||e._get(n,[s,"did"]),c=t.ucan||e._get(n,[s,"ucan"]);if(!o)throw new Error("No did audience provided");if(!c)throw new Error("No ucan provided to authentication call");return Promise.resolve(e.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};return e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),console.warn("Could not validate ucan",c,t.message),null})).then(function(t){function o(){var t=e.ucanToken(c);return i({accessToken:t},n,{authentication:i({},n.authentication,{payload:t})})}var u=function(){if(!t){var o=e.parseUcan(c),u=a.app.get("authentication"),f=e.encodeKeyPair({secretKey:u.secret});return Promise.resolve(e.buildUcan({audience:o.payload.aud,issuer:f,lifetimeInSeconds:5184e3,capabilities:o.payload.att})).then(function(t){var o;return c=t,r.admin_pass=!0,Promise.resolve(a.app.service(l).patch(e._get(n,[s,"_id"]),(o={},o[h]=e.ucanToken(c),o),i({},r))).then(function(){})})}}();return u&&u.then?u.then(o):o()})})}catch(e){return Promise.reject(e)}},r}(t.AuthenticationService),g=/*#__PURE__*/function(){function e(e,t,r){var n;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=i({},null==(n=t.params)?void 0:n.core,r)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var r,n,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).get(e,i({},t,((n={})[a]=o.core,n))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,r,n=this,o=n.context.app.get("authentication").core_path;return Promise.resolve(null==(t=n.context.app)?void 0:t.service(n.service).find(i({},e,((r={})[o]=n.core,r))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var r,n,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).create(e,i({},t,((n={})[a]=o.core,n))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r){void 0===r&&(r={});try{var n,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service).patch(e,t,i({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,r){void 0===r&&(r={});try{var n,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service).update(e,t,i({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var r,n,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).remove(e,i({},t,((n={})[a]=o.core,n))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var r,n,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._get(e,i({},t,((n={})[a]=o.core,n))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,r,n=this,o=n.context.app.get("authentication").core_path;return Promise.resolve(null==(t=n.context.app)?void 0:t.service(n.service)._find(i({},e,((r={})[o]=n.core,r))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var r,n,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._create(e,i({},t,((n={})[a]=o.core,n))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,r){void 0===r&&(r={});try{var n,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service)._patch(e,t,i({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,r){void 0===r&&(r={});try{var n,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service)._update(e,t,i({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var r,n,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._remove(e,i({},t,((n={})[a]=o.core,n))))}catch(e){return Promise.reject(e)}},e}(),P="_exists",_=function(e){var t=e.app.get("existsPath")||P;return e.params?e.params[t+"_"+e.path]:void 0},b=function(e,t){try{var r=_(e),n=function(){if(!r&&e.id)return Promise.resolve(new g(e.path,e,{skipJoins:!1!==(null==t?void 0:t.skipJoins)}).get(e.id,{admin_pass:!0})).then(function(e){r=e})}();return Promise.resolve(n&&n.then?n.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},x=function(e,t){var r=e.app.get("existsPath")||P;return e.params[r+"_"+e.path]=t,e},w=["ucan"];function j(e,t,r){if(!e.s){if(r instanceof k){if(!r.s)return void(r.o=j.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(j.bind(null,e,t),j.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}const k=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,r){const n=new e,i=this.s;if(i){const e=1&i?t:r;if(e){try{j(n,1,e(this.v))}catch(e){j(n,2,e)}return n}return this}return this.o=function(e){try{const i=e.v;1&e.s?j(n,1,t?t(i):i):r?j(n,1,r(i)):j(n,2,i)}catch(e){j(n,2,e)}},n},e}();var E=function(r){try{var n=r.app.get("authentication"),i=e._get(r,["auth",n.entity]);return i&&(r=e._set(r,[n.core_path,n.entity],i)),Promise.resolve(t.authenticate("jwt")(r).catch(function(e){return console.error("got error in no throw auth",e),r})).then(function(e){return r=e})}catch(e){return Promise.reject(e)}},T=function(r){try{var n=r.app.get("authentication"),i=e._get(r,["auth",n.entity]);return i&&(r=e._set(r,[n.core_path,n.entity],i)),Promise.resolve(t.authenticate("jwt")(r))}catch(e){return Promise.reject(e)}},A=function(t){try{var r,n={ok:!1,value:[]},i=function(i,o,a){var c=[];for(var u in i)c.push(u);return function(e,t,r){var n,i,o=-1;return function a(c){try{for(;++o<e.length&&(!r||!r());)if((c=t(o))&&c.then){if(!((u=c)instanceof k&&1&u.s))return void c.then(a,i||(i=j.bind(null,n=new k,2)));c=c.v}n?j(n,1,c):n=c}catch(e){j(n||(n=new k),2,e)}var u}(),n}(c,function(i){return function(i){var o=function(o){if(null==(o=n)||!o.ok){var a=t[i],c=a.ucan,u=l(a,w);return Promise.resolve(function(t,r){try{return Promise.resolve(e.verifyUcan(t,r))}catch(e){return Promise.reject(e)}}(c,u)).then(function(e){n=e})}r=1}();if(o&&o.then)return o.then(function(){})}(c[i])},function(){return r})}(t);return Promise.resolve(i&&i.then?i.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},O=function(t,r,n){return function(i){try{var o,a=e._get(i.params,r.client_ucan),c=e._get(i.params,r.ucan_aud);return a&&c&&null!=n&&null!=(o=n.or)&&o.includes(i.method)?Promise.resolve(A((t||[]).map(function(e){return{ucan:a,audience:c,requiredCapabilities:[e]}}))):Promise.resolve(e.verifyUcan(a,{audience:c,requiredCapabilities:t}))}catch(e){return Promise.reject(e)}}},S=function(t,r){var n=e.encodeKeyPair({secretKey:r.secret}).did();return(t||[]).map(function(t){return{capability:Array.isArray(t)?e.genCapability({with:{scheme:r.defaultScheme,hierPart:r.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},r):e.genCapability(t,r),rootIssuer:n}})},U=function(t,r){return function(n){try{var i,o,a=function(i){if(o)return i;function a(){function i(){var t,i;if(null!=(t=o)&&t.ok)return n;var u=function(t){if(i)return t;function u(){if(o.ok)return n;throw console.error("Ucan capabilities requirements not met: ",o,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)}var s=function(t){if(null==(t=o)||!t.ok){var i=!1,u=[];a.forEach(function(t,r){var n=(e._get(t,"capability.can.namespace")||"").split(":");n[1]&&(t=e._set(t,"capability.can.namespace",n[0]),i=!0),u.push(t)});var s=function(){if(i)return Promise.resolve(O(a,c,r)(n)).then(function(e){o=e})}();if(s&&s.then)return s.then(function(){})}}();return s&&s.then?s.then(u):u()},s=(r||{loginPass:[["*"],["nonExistentMethod"]]}).loginPass,l=function(){if(null!=s&&s.length){var t=("*"===s[1]?[n.method]:s[1].map(function(e){return e.split("/")[0]})).indexOf(n.method);return function(){if(t>-1)return Promise.resolve(b(n)).then(function(r){if(n=x(n,r),s){var a=e._flatten((s[0]||[]).map(function(t){return e._get(r,t)}).filter(function(e){return!!e}).map(function(e){return Array.isArray(e)?e:[e]})),u=e._get(n.params,[c.entity,"_id"]);if(a.map(function(e){return String(e)}).includes(String(u))){if("*"!==s[1]&&!["find","get","remove"].includes(n.method)){for(var l,h={},p=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return f(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?f(e,t):void 0}}(e))){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(s[1][t].split(",")||[]);!(l=p()).done;){var v=l.value,d=e._get(n.data,v);if(d)h=e._set(h,v,d);else for(var m=0,y=["$addToSet","$pull"];m<y.length;m++){var g=y[m],P=e._get(n.data,g+"."+v);P&&(h=e._set(h,g+"."+v,P))}}return n=e._set(n,"data",h),i=1,n}o.ok=!0}}})}()}}();return l&&l.then?l.then(u):u(l)}if("*"===t)return n;if(((null==r?void 0:r.adminPass)||[]).includes(n.method)&&(e._get(n.params,"admin_pass")||e._get(n.params,[c.core_path,"admin_pass"])))return n;var o={ok:!1,value:[]},a=S(t,c),u=function(){if(a.length)return Promise.resolve(O(a,c,r)(n)).then(function(e){o=e});o.ok=!0}();return u&&u.then?u.then(i):i()}var s=function(){if(!u)return Promise.resolve(T(n)).then(function(e){n=e})}();return s&&s.then?s.then(a):a()},c=n.app.get("authentication"),u=null==(i=n.params)||null==(i=i.login)?void 0:i._id,s=function(){if("$"===t){var e=function(e){return o=1,e};return u?e(n):Promise.resolve(E(n)).then(e)}}();return Promise.resolve(s&&s.then?s.then(a):a(s))}catch(e){return Promise.reject(e)}}};exports.AuthService=y,exports.CoreCall=g,exports.NotAuthError=m,exports.UcanStrategy=v,exports.allUcanAuth=function(t,r){return function(n){try{var i=n.app.get("authentication"),o=e._get(n,["auth",i.entity]);if(o&&(n=e._set(n,[i.core_path,i.entity],o)),"before"===n.type){var a=n.method;return Promise.resolve(t[a]||t.all?U(t[a]||t.all,r)(n):n)}return Promise.resolve(n)}catch(e){return Promise.reject(e)}}},exports.anyAuth="*",exports.bareAuth=T,exports.existsPath=P,exports.getExists=_,exports.loadExists=b,exports.modelCapabilities=S,exports.noThrow="$",exports.noThrowAuth=E,exports.orVerifyLoop=A,exports.setExists=x,exports.ucanAuth=U,exports.updateUcan=function(){return function(t){try{var r=t.data,n=r.add,o=void 0===n?[]:n,a=r.remove,c=void 0===a?[]:a;if(!(null!=o&&o.length||null!=c&&c.length))throw new Error("No new capabilities passed");var u=t.app.get("authentication"),s=u.secret,l=u.ucan_aud,f=u.entity,h=u.ucan,p=e.encodeKeyPair({secretKey:s}).did(),v=e.stackAbilities([].concat(o,c));return Promise.resolve(e.verifyUcan(e._get(t.params,[f,h]),{audience:e._get(t.params,l),requiredCapabilities:v.map(function(e){return{capability:e,rootIssuer:p}})})).then(function(r){if(null==r||!r.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var n=t.id,a=t.data.service||"logins",u=t.data.path||"ucan";return Promise.resolve(new g(a,t,{skipJoins:!0}).get(n)).then(function(r){var l=e.parseUcan(e._get(r,u)).payload,f=l.aud,h=l.att,p=l.prf,v=[].concat(h);return null!=c&&c.length&&(v=e.reduceAbilities(c,h)),null!=o&&o.length&&(v=e.stackAbilities([].concat(h,o))),Promise.resolve(e.buildUcan(i({issuer:e.encodeKeyPair({secretKey:s}),audience:f,lifetimeInSeconds:5184e3,proofs:p},t.data,{capabilities:v}))).then(function(r){var i=e.ucanToken(r);return Promise.resolve(e.validateUcan(i)).then(function(e){var r;if(!e)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new g(a,t).patch(n,(r={},r[u]=i,r))).then(function(e){return t.result={raw:t.data,encoded:i,subject:e},t})})})})})}catch(e){return Promise.reject(e)}}},exports.verifyAgainstReqs=O;
1
+ var e=require("symbol-ucan"),t=require("@feathersjs/authentication");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=/*#__PURE__*/n(require("long-timeout"));function i(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return i=function(e){this.s=e,this.n=e.next},i.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new i(e)}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o.apply(this,arguments)}function a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,u(e,t)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function u(e,t){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},u(e,t)}function s(e,t,n){return s=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(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&u(i,n.prototype),i},s.apply(null,arguments)}function l(e){var t="function"==typeof Map?new Map:void 0;return l=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return s(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),u(n,e)},l(e)}function f(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t.indexOf(n=o[r])>=0||(i[n]=e[n]);return i}function h(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var v=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return a(t,e),t}(/*#__PURE__*/l(Error)),p=/(\S+)\s+(\S+)/,d=/*#__PURE__*/function(t){function n(){for(var e,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(e=t.call.apply(t,[this].concat(r))||this).expirationTimers=new WeakMap,e}a(n,t);var i,c,u=n.prototype;return u.setAuthentication=function(e){e.verifyAccessToken=function(e){return{}},this.authentication=e},u.handleConnection=function(t,n,i){try{var o=this,a="logout"===t&&n.authentication&&i&&n.authentication.accessToken===i.accessToken,c=(i||{}).accessToken,u=function(){if(c&&"login"===t)return Promise.resolve(e.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){var t=1e3*(e||{payload:{exp:0}}).payload.exp-Date.now(),i=r.default.setTimeout(function(){return o.app.emit("disconnect",n)},t);r.default.clearTimeout(o.expirationTimers.get(n)),o.expirationTimers.set(n,i),n.authentication={strategy:o.name,accessToken:c}});("disconnect"===t||a)&&(delete n[o.configuration.entity],delete n.authentication,r.default.clearTimeout(o.expirationTimers.get(n)),o.expirationTimers.delete(n))}();return Promise.resolve(u&&u.then?u.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},u.verifyConfiguration=function(){for(var e=["entity","entityId","service","header","schemes","audience"],t=0,n=Object.keys(this.configuration);t<n.length;t++){var r=n[t];if(!e.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(e){return Promise.resolve({})},u.getEntity=function(t,n){try{var r=this,i=r.entityService,a=r.configuration.entity;if(null===i)throw new v("Could not find entity service");return Promise.resolve(r.getEntityQuery(n)).then(function(r){var c=Object.assign({},e._unset(n,"provider"),{query:r});return Promise.resolve(i.get(t,c)).then(function(e){var r;return n.provider?i.get(t,o({},n,((r={})[a]=e,r))):e})})}catch(e){return Promise.reject(e)}},u.getEntityId=function(e,t){try{var n=t.query,r=t.loginId;if(r)return Promise.resolve(r);var i,a,c=this.configuration,u=c.service,s=c.core_path,l=void 0===s?"core":s,f=((i={query:o({},n,{$limit:1})})[l]=o({skipJoins:!0},t[l]),i);return Promise.resolve(null==(a=this.app)?void 0:a.service(u).find(o({},f,{skipJoins:!0}))).then(function(e){if(e.total)return e.data[0]._id;throw new v("Could not find login associated with this ucan")})}catch(e){return Promise.reject(e)}},u.authenticate=function(t,n){try{var r=this,i=t.accessToken,a=t.loginId,c=t.ucan,u=r.configuration,s=u.entity,l=u.core_path;if(!i){if(!c)throw new v("Error generating ucan");i=e.ucanToken(c)}return Promise.resolve(e.validateUcan(i).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(t){function c(){var e;return o({},f,((e={})[s]=u,e))}var u,f={accessToken:i,authentication:{strategy:"jwt",accessToken:i}};if(null===s)return f;var h=e._get(n,[l,s]),v=function(){if(!h)return Promise.resolve(r.getEntityId(f,o({},n,{loginId:a,query:{did:null==t?void 0:t.payload.aud}}))).then(function(e){return Promise.resolve(r.getEntity(e,n)).then(function(e){u=e})});u=h}();return v&&v.then?v.then(c):c()})}catch(e){return Promise.reject(e)}},u.parse=function(e){try{var t=this.configuration,n=t.schemes,r=e.headers&&e.headers[t.header.toLowerCase()];if(!r||"string"!=typeof r)return Promise.resolve(null);var i=r.match(p)||[],o=i[1],a=i[2],c=o&&n.some(function(e){return new RegExp(e,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:r})}catch(e){return Promise.reject(e)}},i=n,(c=[{key:"configuration",get:function(){var e,n=(null==(e=this.authentication)?void 0:e.configuration)||{service:void 0,entity:void 0,entityId:void 0};return o({service:n.service,entity:n.entity,entityId:n.entityId,header:"Authorization",schemes:["Bearer","JWT"]},t.prototype.configuration)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,"symbol"==typeof(i=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(r.key))?i:String(i),r)}var i}(i.prototype,c),Object.defineProperty(i,"prototype",{writable:!1}),n}(t.AuthenticationBaseStrategy),m=["NotAuthenticated"],y=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return a(t,e),t}(/*#__PURE__*/l(Error)),g=/*#__PURE__*/function(t){function n(e,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=f(r,m);return(i=t.call(this,e,n,a)||this).options=void 0,i.app=e,i.options={NotAuthenticated:o},i}return a(n,t),n.prototype.create=function(t,n){try{var r,i,a=this,c=(null==(r=a.options)?void 0:r.NotAuthenticated)||y,u=a.app.get("authentication"),s=u.entity,l=u.service,f=u.ucan_path,h=void 0===f?"ucan":f,v=(null==(i=n)?void 0:i.authStrategies)||a.configuration.authStrategies;if(n||(n={}),!v.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(a.authenticate.apply(a,[t,n].concat(v)).catch(function(e){throw new Error(e.message)})).then(function(r){if(r.accessToken)return r;var i=t.did||e._get(r,[s,"did"]),c=t.ucan||e._get(r,[s,"ucan"]);if(!i)throw new Error("No did audience provided");if(!c)throw new Error("No ucan provided to authentication call");return Promise.resolve(e.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};return e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),console.warn("Could not validate ucan",c,t.message),null})).then(function(t){function i(){var t=e.ucanToken(c);return o({accessToken:t},r,{authentication:o({},r.authentication,{payload:t})})}var u=function(){if(!t){var i=e.parseUcan(c),u=a.app.get("authentication"),f=e.encodeKeyPair({secretKey:u.secret});return Promise.resolve(e.buildUcan({audience:i.payload.aud,issuer:f,lifetimeInSeconds:5184e3,capabilities:i.payload.att})).then(function(t){var i;return c=t,n.admin_pass=!0,Promise.resolve(a.app.service(l).patch(e._get(r,[s,"_id"]),(i={},i[h]=e.ucanToken(c),i),o({},n))).then(function(){})})}}();return u&&u.then?u.then(i):i()})})}catch(e){return Promise.reject(e)}},n}(t.AuthenticationService),P=/*#__PURE__*/function(){function e(e,t,n){var r;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=o({},null==(r=t.params)?void 0:r.core,n)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).get(e,o({},t,((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(t=r.context.app)?void 0:t.service(r.service).find(o({},e,((n={})[i]=r.core,n))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).create(e,o({},t,((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,n){void 0===n&&(n={});try{var r,i,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(e,t,o({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,n){void 0===n&&(n={});try{var r,i,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(e,t,o({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).remove(e,o({},t,((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._get(e,o({},t,((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(t=r.context.app)?void 0:t.service(r.service)._find(o({},e,((n={})[i]=r.core,n))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._create(e,o({},t,((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,n){void 0===n&&(n={});try{var r,i,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(e,t,o({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,n){void 0===n&&(n={});try{var r,i,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(e,t,o({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._remove(e,o({},t,((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},e}(),b="_exists",_=function(t){var n=t.app.get("existsPath")||b;return e._get(t.params,n+"."+t.path+"."+t.id)||void 0},w=function(e,t){try{var n=_(e),r=function(){if(!n&&e.id)return Promise.resolve(new P(e.path,e,{skipJoins:!1!==(null==t?void 0:t.skipJoins)}).get(e.id,{admin_pass:!0})).then(function(e){n=e})}();return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},x=function(t,n){var r=t.app.get("existsPath")||b;return t.params=e._set(t.params,r+"."+t.path+"."+(n._id||t.id),n),t},j=["ucan"];function k(e,t,n){if(!e.s){if(n instanceof E){if(!n.s)return void(n.o=k.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(k.bind(null,e,t),k.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}const E=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{k(r,1,e(this.v))}catch(e){k(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?k(r,1,t?t(i):i):n?k(r,1,n(i)):k(r,2,i)}catch(e){k(r,2,e)}},r},e}();function T(e){return e instanceof E&&1&e.s}function O(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var A=function(n){try{var r=n.app.get("authentication"),i=e._get(n,["auth",r.entity]);return i&&(n=e._set(n,[r.core_path,r.entity],i)),Promise.resolve(t.authenticate("jwt")(n).catch(function(e){return console.error("got error in no throw auth",e),n})).then(function(e){return n=e})}catch(e){return Promise.reject(e)}},S=function(n){try{var r=n.app.get("authentication"),i=e._get(n,["auth",r.entity]);return i&&(n=e._set(n,[r.core_path,r.entity],i)),Promise.resolve(t.authenticate("jwt")(n))}catch(e){return Promise.reject(e)}},U=function(t){try{var n,r={ok:!1,value:[]},i=function(i,o,a){var c=[];for(var u in i)c.push(u);return function(e,t,n){var r,i,o=-1;return function a(c){try{for(;++o<e.length&&(!n||!n());)if((c=t(o))&&c.then){if(!T(c))return void c.then(a,i||(i=k.bind(null,r=new E,2)));c=c.v}r?k(r,1,c):r=c}catch(e){k(r||(r=new E),2,e)}}(),r}(c,function(i){return function(i){var o=function(o){if(null==(o=r)||!o.ok){var a=t[i],c=a.ucan,u=f(a,j);return Promise.resolve(function(t,n){try{return Promise.resolve(e.verifyUcan(t,n))}catch(e){return Promise.reject(e)}}(c,u)).then(function(e){r=e})}n=1}();if(o&&o.then)return o.then(function(){})}(c[i])},function(){return n})}(t);return Promise.resolve(i&&i.then?i.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},I=function(t,n,r){return function(i){try{var o,a=e._get(i.params,n.client_ucan),c=e._get(i.params,n.ucan_aud);return a&&c&&null!=r&&null!=(o=r.or)&&o.includes(i.method)?Promise.resolve(U((t||[]).map(function(e){return{ucan:a,audience:c,requiredCapabilities:[e]}}))):Promise.resolve(e.verifyUcan(a,{audience:c,requiredCapabilities:t}))}catch(e){return Promise.reject(e)}}},C=function(t,n){var r=e.encodeKeyPair({secretKey:n.secret}).did();return(t||[]).map(function(t){return{capability:Array.isArray(t)?e.genCapability({with:{scheme:n.defaultScheme,hierPart:n.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},n):e.genCapability(t,n),rootIssuer:r}})},q=function(t,n){return function(r){try{var o,a,c=function(o){if(a)return o;function c(){function o(){var t;if(null!=(t=a)&&t.ok)return r;var o=function(t){function i(){if(a.ok)return r;throw console.error("Ucan capabilities requirements not met: ",a,r.type,r.path),new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)}var o=function(t){if(null==(t=a)||!t.ok){var i=!1,o=[];c.forEach(function(t,n){var r=(e._get(t,"capability.can.namespace")||"").split(":");r[1]&&(t=e._set(t,"capability.can.namespace",r[0]),i=!0),o.push(t)});var s=function(){if(i)return Promise.resolve(I(c,u,n)(r)).then(function(e){a=e})}();if(s&&s.then)return s.then(function(){})}}();return o&&o.then?o.then(i):i()},s=(n||{loginPass:[[["*"],["nonExistentMethod"]]]}).loginPass,l=function(){if(null!=s&&s.length){var t,n=function(t){if(_interrupt2)return t;c&&(r=e._set(r,"data",o))},o={},c=!0,l=!1,f=!1,v=O(function(){return function(t,n){try{var f=function(){var t,n,f=function(e){var t,n,r,o=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);o--;){if(n&&null!=(t=e[n]))return t.call(e);if(r&&null!=(t=e[r]))return new i(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(s),v=function(e,t,n){for(var r;;){var i=e();if(T(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!T(o)){r=1;break}o=o.s}if(t){var a=t();if(a&&a.then&&!T(a)){r=2;break}}}var c=new E,u=k.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(t&&(a=t())&&a.then&&!T(a))return void a.then(f).then(void 0,u);if(!(i=e())||T(i)&&!i.v)return void k(c,1,o);if(i.then)return void i.then(l).then(void 0,u);T(o=n())&&(o=o.v)}while(!o||!o.then);o.then(s).then(void 0,u)}function l(e){e?(o=n())&&o.then?o.then(s).then(void 0,u):s(o):k(c,1,o)}function f(){(i=e())?i.then?i.then(l).then(void 0,u):l(i):k(c,1,o)}}(function(){function e(e){return!t&&(l=!(n=e).done)}return t?!!e(!t&&f.next()):Promise.resolve(!t&&f.next()).then(e)},function(){return!!(l=!1)},function(){var i=n.value,s=function(){if(c)return Promise.resolve(function(t){try{var n=[],i="*"===t[1],s=-1;i?s=0:(n=t[1].map(function(e){return e.split("/")[0]}),s=n.indexOf(r.method));var l=function(){if(s>-1)return Promise.resolve(w(r)).then(function(n){r=x(r,n);var l=e._flatten((t[0]||[]).map(function(t){return e._get(n,t)}).filter(function(e){return!!e}).map(function(e){return Array.isArray(e)?e:[e]})),f=e._get(r.params,[u.entity,"_id"]);if(l.map(function(e){return String(e)}).includes(String(f)))if(a.ok=!0,"*"===t[1]||["find","get","remove"].some(function(e){return t[1].includes(e)}))c=!1;else{var v=i?"*":t[1][s];if(v.split("/")[0]!==v)for(var p,d=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return h(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?h(e,t):void 0}}(e))){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[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.")}(v.split("/").slice(1).join("").split(",")||[]);!(p=d()).done;){var m=p.value,y=e._get(r.data,m);if(y)o=e._set(o,m,y);else for(var g=0,P=["$addToSet","$pull"];g<P.length;g++){var b=P[g],_=e._get(r.data,b+"."+m);_&&(o=e._set(o,b+"."+m,_))}}else c=!1}})}();return Promise.resolve(l&&l.then?l.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}(i)).then(function(){});t=1}();return s&&s.then?s.then(function(){}):void 0});if(v&&v.then)return v.then(function(){})}()}catch(e){return n(e)}return f&&f.then?f.then(void 0,n):f}(0,function(e){f=!0,t=e})},function(e,n){function r(t){if(e)throw n;return n}var i=O(function(){var e=function(){if(l&&null!=_iterator.return)return Promise.resolve(_iterator.return()).then(function(){})}();if(e&&e.then)return e.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(n):n(v)}}();return l&&l.then?l.then(o):o()}if("*"===t)return r;if(((null==n?void 0:n.adminPass)||[]).includes(r.method)&&(e._get(r.params,"admin_pass")||e._get(r.params,[u.core_path,"admin_pass"])))return r;var a={ok:!1,value:[]},c=C(t,u),s=function(){if(c.length)return Promise.resolve(I(c,u,n)(r)).then(function(e){a=e});a.ok=!0}();return s&&s.then?s.then(o):o()}var l=function(){if(!s)return Promise.resolve(S(r)).then(function(e){r=e})}();return l&&l.then?l.then(c):c()},u=r.app.get("authentication"),s=null==(o=r.params)||null==(o=o.login)?void 0:o._id,l=function(){if("$"===t){var e=function(e){return a=1,e};return s?e(r):Promise.resolve(A(r)).then(e)}}();return Promise.resolve(l&&l.then?l.then(c):c(l))}catch(e){return Promise.reject(e)}}};exports.AuthService=g,exports.CoreCall=P,exports.NotAuthError=y,exports.UcanStrategy=d,exports.allUcanAuth=function(t,n){return function(r){try{var i=r.app.get("authentication"),o=e._get(r,["auth",i.entity]);if(o&&(r=e._set(r,[i.core_path,i.entity],o)),"before"===r.type){var a=r.method;return Promise.resolve(t[a]||t.all?q(t[a]||t.all,n)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},exports.anyAuth="*",exports.bareAuth=S,exports.existsPath=b,exports.getExists=_,exports.loadExists=w,exports.modelCapabilities=C,exports.noThrow="$",exports.noThrowAuth=A,exports.orVerifyLoop=U,exports.setExists=x,exports.ucanAuth=q,exports.updateUcan=function(){return function(t){try{var n=t.data,r=n.add,i=void 0===r?[]:r,a=n.remove,c=void 0===a?[]:a;if(!(null!=i&&i.length||null!=c&&c.length))throw new Error("No new capabilities passed");var u=t.app.get("authentication"),s=u.secret,l=u.ucan_aud,f=u.entity,h=u.ucan,v=e.encodeKeyPair({secretKey:s}).did(),p=e.stackAbilities([].concat(i,c));return Promise.resolve(e.verifyUcan(e._get(t.params,[f,h]),{audience:e._get(t.params,l),requiredCapabilities:p.map(function(e){return{capability:e,rootIssuer:v}})})).then(function(n){if(null==n||!n.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var r=t.id,a=t.data.service||"logins",u=t.data.path||"ucan";return Promise.resolve(new P(a,t,{skipJoins:!0}).get(r)).then(function(n){var l=e.parseUcan(e._get(n,u)).payload,f=l.aud,h=l.att,v=l.prf,p=[].concat(h);return null!=c&&c.length&&(p=e.reduceAbilities(c,h)),null!=i&&i.length&&(p=e.stackAbilities([].concat(h,i))),Promise.resolve(e.buildUcan(o({issuer:e.encodeKeyPair({secretKey:s}),audience:f,lifetimeInSeconds:5184e3,proofs:v},t.data,{capabilities:p}))).then(function(n){var i=e.ucanToken(n);return Promise.resolve(e.validateUcan(i)).then(function(e){var n;if(!e)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new P(a,t).patch(r,(n={},n[u]=i,n))).then(function(e){return t.result={raw:t.data,encoded:i,subject:e},t})})})})})}catch(e){return Promise.reject(e)}}},exports.verifyAgainstReqs=I;
@@ -1 +1 @@
1
- import{validateUcan as t,_unset as e,ucanToken as a,_get as i,parseUcan as n,encodeKeyPair as s,buildUcan as o,_set as r,verifyUcan as c,genCapability as u,_flatten as h,stackAbilities as p,reduceAbilities as l}from"symbol-ucan";import{AuthenticationBaseStrategy as d,AuthenticationService as g,authenticate as v}from"@feathersjs/authentication";import y from"long-timeout";function f(){return f=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},f.apply(this,arguments)}function m(t,e){if(null==t)return{};var a,i,n={},s=Object.keys(t);for(i=0;i<s.length;i++)e.indexOf(a=s[i])>=0||(n[a]=t[a]);return n}class w extends Error{constructor(t){super(t)}}const x=/(\S+)\s+(\S+)/;class _ extends d{constructor(...t){super(...t),this.expirationTimers=new WeakMap}setAuthentication(t){t.verifyAccessToken=t=>({}),super.authentication=t}get configuration(){var t;const e=(null==(t=this.authentication)?void 0:t.configuration)||{service:void 0,entity:void 0,entityId:void 0};return f({service:e.service,entity:e.entity,entityId:e.entityId,header:"Authorization",schemes:["Bearer","JWT"]},super.configuration)}async handleConnection(e,a,i){const n="logout"===e&&a.authentication&&i&&a.authentication.accessToken===i.accessToken,{accessToken:s}=i||{};if(s&&"login"===e){const e=await t(s).catch(t=>{console.log("Could not validate ucan: ",t.message);const 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)}),{payload:{exp:i}}=e||{payload:{exp:0}},n=1e3*i-Date.now(),o=y.setTimeout(()=>this.app.emit("disconnect",a),n);y.clearTimeout(this.expirationTimers.get(a)),this.expirationTimers.set(a,o),a.authentication={strategy:this.name,accessToken:s}}else if("disconnect"===e||n){const{entity:t}=this.configuration;delete a[t],delete a.authentication,y.clearTimeout(this.expirationTimers.get(a)),this.expirationTimers.delete(a)}}verifyConfiguration(){const t=["entity","entityId","service","header","schemes","audience"];for(const e of Object.keys(this.configuration))if(!t.includes(e))throw new Error(`Invalid ucanStrategy option 'authentication.${this.name}.${e}'. 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`)}async getEntityQuery(t){return{}}async getEntity(t,a){const i=this.entityService,{entity:n}=this.configuration;if(null===i)throw new w("Could not find entity service");const s=await this.getEntityQuery(a),o=Object.assign({},e(a,"provider"),{query:s}),r=await i.get(t,o);return a.provider?i.get(t,f({},a,{[n]:r})):r}async getEntityId(t,e){let{query:a,loginId:i}=e;if(i)return i;{var n;const{service:t,core_path:i="core"}=this.configuration,s={query:f({},a,{$limit:1}),[i]:f({skipJoins:!0},e[i])},o=await(null==(n=this.app)?void 0:n.service(t).find(f({},s,{skipJoins:!0})));if(o.total)return o.data[0]._id;throw new w("Could not find login associated with this ucan")}}async authenticate(e,n){let{accessToken:s,loginId:o,ucan:r}=e;const{entity:c,core_path:u}=this.configuration;if(!s){if(!r)throw new w("Error generating ucan");s=a(r)}const h=await t(s).catch(t=>{console.log("Could not validate ucan: ",t.message);const 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)}),p={accessToken:s,authentication:{strategy:"jwt",accessToken:s}};if(null===c)return p;let l;const d=i(n,[u,c]);if(d)l=d;else{const t=await this.getEntityId(p,f({},n,{loginId:o,query:{did:null==h?void 0:h.payload.aud}}));l=await this.getEntity(t,n)}return f({},p,{[c]:l})}async parse(t){const{header:e,schemes:a}=this.configuration,i=t.headers&&t.headers[e.toLowerCase()];if(!i||"string"!=typeof i)return null;const[,n,s]=i.match(x)||[],o=n&&a.some(t=>new RegExp(t,"i").test(n));return n&&!o?null:{strategy:this.name,accessToken:o?s:i}}}const k=["NotAuthenticated"];class E extends Error{constructor(t){super(t)}}class b extends g{constructor(t,e="authentication",a={}){const{NotAuthenticated:i}=a;super(t,e,m(a,k)),this.options=void 0,this.app=t,this.options={NotAuthenticated:i}}async create(e,r){var c,u;const h=(null==(c=this.options)?void 0:c.NotAuthenticated)||E,{entity:p,service:l,ucan_path:d="ucan"}=this.app.get("authentication"),g=(null==(u=r)?void 0:u.authStrategies)||this.configuration.authStrategies;if(r||(r={}),!g.length)throw new h("No authentication strategies allowed for creating a JWT (`authStrategies`)");const v=await this.authenticate(e,r,...g).catch(t=>{throw new Error(t.message)});if(v.accessToken)return v;const y=e.did||i(v,[p,"did"]);let m=e.ucan||i(v,[p,"ucan"]);if(!y)throw new Error("No did audience provided");if(!m)throw new Error("No ucan provided to authentication call");if(!await t(m).catch(t=>{console.log("Could not validate ucan: ",t.message);const 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",m,e.message),null})){const t=n(m);let{secret:e}=this.app.get("authentication");const c=s({secretKey:e});m=await o({audience:t.payload.aud,issuer:c,lifetimeInSeconds:5184e3,capabilities:t.payload.att}),r.admin_pass=!0,await this.app.service(l).patch(i(v,[p,"_id"]),{[d]:a(m)},f({},r))}const w=a(m);return f({accessToken:w},v,{authentication:f({},v.authentication,{payload:w})})}}class T{constructor(t,e,a){var i;this.context=void 0,this.service=void 0,this.core=void 0,this.service=t,this.context=e,this.core=f({},null==(i=e.params)?void 0:i.core,a)}async get(t,e={}){var a;const{core_path:i}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service).get(t,f({},e,{[i]:this.core}))}async find(t={}){var e;const{core_path:a}=this.context.app.get("authentication");return null==(e=this.context.app)?void 0:e.service(this.service).find(f({},t,{[a]:this.core}))}async create(t,e={}){var a;const{core_path:i}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service).create(t,f({},e,{[i]:this.core}))}async patch(t,e,a={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).patch(t,e,f({},a,{[n]:this.core}))}async update(t,e,a={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).update(t,e,f({},a,{[n]:this.core}))}async remove(t,e={}){var a;const{core_path:i}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service).remove(t,f({},e,{[i]:this.core}))}async _get(t,e={}){var a;const{core_path:i}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service)._get(t,f({},e,{[i]:this.core}))}async _find(t={}){var e;const{core_path:a}=this.context.app.get("authentication");return null==(e=this.context.app)?void 0:e.service(this.service)._find(f({},t,{[a]:this.core}))}async _create(t,e={}){var a;const{core_path:i}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service)._create(t,f({},e,{[i]:this.core}))}async _patch(t,e,a={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._patch(t,e,f({},a,{[n]:this.core}))}async _update(t,e,a={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._update(t,e,f({},a,{[n]:this.core}))}async _remove(t,e={}){var a;const{core_path:i}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service)._remove(t,f({},e,{[i]:this.core}))}}const I="_exists",$=t=>{const e=t.app.get("existsPath")||I;return t.params?t.params[`${e}_${t.path}`]:void 0},O=async(t,e)=>{let a=$(t);return!a&&t.id&&(a=await new T(t.path,t,{skipJoins:!1!==(null==e?void 0:e.skipJoins)}).get(t.id,{admin_pass:!0})),a},S=(t,e)=>{const a=t.app.get("existsPath")||I;return t.params[`${a}_${t.path}`]=e,t},j=["ucan"],C="*",A="$",U=async t=>{const e=t.app.get("authentication"),a=i(t,["auth",e.entity]);return a&&(t=r(t,[e.core_path,e.entity],a)),t=await v("jwt")(t).catch(e=>(console.error("got error in no throw auth",e),t))},q=async t=>{const e=t.app.get("authentication"),a=i(t,["auth",e.entity]);return a&&(t=r(t,[e.core_path,e.entity],a)),v("jwt")(t)},N=async t=>{let e={ok:!1,value:[]};const a=async(t,e)=>await c(t,e);for(const n in t){var i;if(null!=(i=e)&&i.ok)break;{const i=t[n],{ucan:s}=i,o=m(i,j);e=await a(s,o)}}return e},P=(t,e,a)=>async n=>{var s;const o=i(n.params,e.client_ucan),r=i(n.params,e.ucan_aud);return o&&r&&null!=a&&null!=(s=a.or)&&s.includes(n.method)?await N((t||[]).map(t=>({ucan:o,audience:r,requiredCapabilities:[t]}))):await c(o,{audience:r,requiredCapabilities:t})},J=(t,e)=>{const a=s({secretKey:e.secret}).did();return(t||[]).map(t=>({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:a}))},K=(t,e)=>async a=>{var n,s;const o=a.app.get("authentication"),c=null==(n=a.params)||null==(n=n.login)?void 0:n._id;if("$"===t)return c?a:await U(a);if(c||(a=await q(a)),"*"===t)return a;if(((null==e?void 0:e.adminPass)||[]).includes(a.method)&&(i(a.params,"admin_pass")||i(a.params,[o.core_path,"admin_pass"])))return a;let u={ok:!1,value:[]};const p=J(t,o);if(p.length?u=await P(p,o,e)(a):u.ok=!0,null!=(s=u)&&s.ok)return a;{var l;const{loginPass:t}=e||{loginPass:[["*"],["nonExistentMethod"]]};if(null!=t&&t.length){let e=[];e="*"===t[1]?[a.method]:t[1].map(t=>t.split("/")[0]);const n=e.indexOf(a.method);if(n>-1){const e=await O(a);if(a=S(a,e),t){const s=h((t[0]||[]).map(t=>i(e,t)).filter(t=>!!t).map(t=>Array.isArray(t)?t:[t])),c=i(a.params,[o.entity,"_id"]);if(s.map(t=>String(t)).includes(String(c))){if("*"!==t[1]&&!["find","get","remove"].includes(a.method)){const e=t[1][n].split(",")||[];let s={};for(const t of e){const e=i(a.data,t);if(e)s=r(s,t,e);else for(const e of["$addToSet","$pull"]){const n=i(a.data,`${e}.${t}`);n&&(s=r(s,`${e}.${t}`,n))}}return r(a,"data",s)}u.ok=!0}}}}if(null==(l=u)||!l.ok){let t=!1;p.forEach((e,a)=>{const n=(i(e,"capability.can.namespace")||"").split(":");n[1]&&(e=r(e,"capability.can.namespace",n[0]),t=!0)}),t&&(u=await P(p,o,e)(a))}if(u.ok)return a;throw console.error("Ucan capabilities requirements not met: ",u,a.type,a.path),new Error("Missing proper capabilities for this action: "+a.type+": "+a.path+" - "+a.method)}},M=(t,e)=>async a=>{const n=a.app.get("authentication"),s=i(a,["auth",n.entity]);if(s&&(a=r(a,[n.core_path,n.entity],s)),"before"===a.type){const{method:i}=a;return t[i]||t.all?await K(t[i]||t.all,e)(a):a}return a},V=()=>async e=>{const{add:r=[],remove:u=[]}=e.data;if(!(null!=r&&r.length||null!=u&&u.length))throw new Error("No new capabilities passed");const{secret:h,ucan_aud:d,entity:g,ucan:v}=e.app.get("authentication"),y=s({secretKey:h}).did(),m=p([...r,...u]),w=await c(i(e.params,[g,v]),{audience:i(e.params,d),requiredCapabilities:m.map(t=>({capability:t,rootIssuer:y}))});if(null==w||!w.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");const x=e.id,_=e.data.service||"logins",k=e.data.path||"ucan",E=await new T(_,e,{skipJoins:!0}).get(x),b=n(i(E,k)),{aud:I,att:$,prf:O}=b.payload;let S=[...$];null!=u&&u.length&&(S=l(u,$)),null!=r&&r.length&&(S=p([...$,...r]));const j=await o(f({issuer:s({secretKey:h}),audience:I,lifetimeInSeconds:5184e3,proofs:O},e.data,{capabilities:S})),C=a(j);if(!await t(C))throw new Error("Invalid ucan generated when updating");const A=await new T(_,e).patch(x,{[k]:C});return e.result={raw:e.data,encoded:C,subject:A},e};export{b as AuthService,T as CoreCall,E as NotAuthError,_ as UcanStrategy,M as allUcanAuth,C as anyAuth,q as bareAuth,I as existsPath,$ as getExists,O as loadExists,J as modelCapabilities,A as noThrow,U as noThrowAuth,N as orVerifyLoop,S as setExists,K as ucanAuth,V as updateUcan,P as verifyAgainstReqs};
1
+ import{validateUcan as t,_unset as e,ucanToken as n,_get as i,parseUcan as a,encodeKeyPair as s,buildUcan as o,_set as r,verifyUcan as c,genCapability as u,_flatten as h,stackAbilities as l,reduceAbilities as p}from"symbol-ucan";import{AuthenticationBaseStrategy as d,AuthenticationService as v,authenticate as g}from"@feathersjs/authentication";import y from"long-timeout";function f(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 f=function(t){this.s=t,this.n=t.next},f.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 f(t)}function m(){return m=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},m.apply(this,arguments)}function w(t,e){if(null==t)return{};var n,i,a={},s=Object.keys(t);for(i=0;i<s.length;i++)e.indexOf(n=s[i])>=0||(a[n]=t[n]);return a}class x extends Error{constructor(t){super(t)}}const _=/(\S+)\s+(\S+)/;class b extends d{constructor(...t){super(...t),this.expirationTimers=new WeakMap}setAuthentication(t){t.verifyAccessToken=t=>({}),super.authentication=t}get configuration(){var t;const e=(null==(t=this.authentication)?void 0:t.configuration)||{service:void 0,entity:void 0,entityId:void 0};return m({service:e.service,entity:e.entity,entityId:e.entityId,header:"Authorization",schemes:["Bearer","JWT"]},super.configuration)}async handleConnection(e,n,i){const a="logout"===e&&n.authentication&&i&&n.authentication.accessToken===i.accessToken,{accessToken:s}=i||{};if(s&&"login"===e){const e=await t(s).catch(t=>{console.log("Could not validate ucan: ",t.message);const 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)}),{payload:{exp:i}}=e||{payload:{exp:0}},a=1e3*i-Date.now(),o=y.setTimeout(()=>this.app.emit("disconnect",n),a);y.clearTimeout(this.expirationTimers.get(n)),this.expirationTimers.set(n,o),n.authentication={strategy:this.name,accessToken:s}}else if("disconnect"===e||a){const{entity:t}=this.configuration;delete n[t],delete n.authentication,y.clearTimeout(this.expirationTimers.get(n)),this.expirationTimers.delete(n)}}verifyConfiguration(){const t=["entity","entityId","service","header","schemes","audience"];for(const e of Object.keys(this.configuration))if(!t.includes(e))throw new Error(`Invalid ucanStrategy option 'authentication.${this.name}.${e}'. 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`)}async getEntityQuery(t){return{}}async getEntity(t,n){const i=this.entityService,{entity:a}=this.configuration;if(null===i)throw new x("Could not find entity service");const s=await this.getEntityQuery(n),o=Object.assign({},e(n,"provider"),{query:s}),r=await i.get(t,o);return n.provider?i.get(t,m({},n,{[a]:r})):r}async getEntityId(t,e){let{query:n,loginId:i}=e;if(i)return i;{var a;const{service:t,core_path:i="core"}=this.configuration,s={query:m({},n,{$limit:1}),[i]:m({skipJoins:!0},e[i])},o=await(null==(a=this.app)?void 0:a.service(t).find(m({},s,{skipJoins:!0})));if(o.total)return o.data[0]._id;throw new x("Could not find login associated with this ucan")}}async authenticate(e,a){let{accessToken:s,loginId:o,ucan:r}=e;const{entity:c,core_path:u}=this.configuration;if(!s){if(!r)throw new x("Error generating ucan");s=n(r)}const h=await t(s).catch(t=>{console.log("Could not validate ucan: ",t.message);const 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)}),l={accessToken:s,authentication:{strategy:"jwt",accessToken:s}};if(null===c)return l;let p;const d=i(a,[u,c]);if(d)p=d;else{const t=await this.getEntityId(l,m({},a,{loginId:o,query:{did:null==h?void 0:h.payload.aud}}));p=await this.getEntity(t,a)}return m({},l,{[c]:p})}async parse(t){const{header:e,schemes:n}=this.configuration,i=t.headers&&t.headers[e.toLowerCase()];if(!i||"string"!=typeof i)return null;const[,a,s]=i.match(_)||[],o=a&&n.some(t=>new RegExp(t,"i").test(a));return a&&!o?null:{strategy:this.name,accessToken:o?s:i}}}const k=["NotAuthenticated"];class E extends Error{constructor(t){super(t)}}class T extends v{constructor(t,e="authentication",n={}){const{NotAuthenticated:i}=n;super(t,e,w(n,k)),this.options=void 0,this.app=t,this.options={NotAuthenticated:i}}async create(e,r){var c,u;const h=(null==(c=this.options)?void 0:c.NotAuthenticated)||E,{entity:l,service:p,ucan_path:d="ucan"}=this.app.get("authentication"),v=(null==(u=r)?void 0:u.authStrategies)||this.configuration.authStrategies;if(r||(r={}),!v.length)throw new h("No authentication strategies allowed for creating a JWT (`authStrategies`)");const g=await this.authenticate(e,r,...v).catch(t=>{throw new Error(t.message)});if(g.accessToken)return g;const y=e.did||i(g,[l,"did"]);let f=e.ucan||i(g,[l,"ucan"]);if(!y)throw new Error("No did audience provided");if(!f)throw new Error("No ucan provided to authentication call");if(!await t(f).catch(t=>{console.log("Could not validate ucan: ",t.message);const 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",f,e.message),null})){const t=a(f);let{secret:e}=this.app.get("authentication");const c=s({secretKey:e});f=await o({audience:t.payload.aud,issuer:c,lifetimeInSeconds:5184e3,capabilities:t.payload.att}),r.admin_pass=!0,await this.app.service(p).patch(i(g,[l,"_id"]),{[d]:n(f)},m({},r))}const w=n(f);return m({accessToken:w},g,{authentication:m({},g.authentication,{payload:w})})}}class I{constructor(t,e,n){var i;this.context=void 0,this.service=void 0,this.core=void 0,this.service=t,this.context=e,this.core=m({},null==(i=e.params)?void 0:i.core,n)}async get(t,e={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).get(t,m({},e,{[i]:this.core}))}async find(t={}){var e;const{core_path:n}=this.context.app.get("authentication");return null==(e=this.context.app)?void 0:e.service(this.service).find(m({},t,{[n]:this.core}))}async create(t,e={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).create(t,m({},e,{[i]:this.core}))}async patch(t,e,n={}){var i;const{core_path:a}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).patch(t,e,m({},n,{[a]:this.core}))}async update(t,e,n={}){var i;const{core_path:a}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).update(t,e,m({},n,{[a]:this.core}))}async remove(t,e={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).remove(t,m({},e,{[i]:this.core}))}async _get(t,e={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._get(t,m({},e,{[i]:this.core}))}async _find(t={}){var e;const{core_path:n}=this.context.app.get("authentication");return null==(e=this.context.app)?void 0:e.service(this.service)._find(m({},t,{[n]:this.core}))}async _create(t,e={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._create(t,m({},e,{[i]:this.core}))}async _patch(t,e,n={}){var i;const{core_path:a}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._patch(t,e,m({},n,{[a]:this.core}))}async _update(t,e,n={}){var i;const{core_path:a}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._update(t,e,m({},n,{[a]:this.core}))}async _remove(t,e={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._remove(t,m({},e,{[i]:this.core}))}}const j="_exists",$=t=>{const e=t.app.get("existsPath")||j;return i(t.params,`${e}.${t.path}.${t.id}`)||void 0},S=async(t,e)=>{let n=$(t);return!n&&t.id&&(n=await new I(t.path,t,{skipJoins:!1!==(null==e?void 0:e.skipJoins)}).get(t.id,{admin_pass:!0})),n},O=(t,e)=>{const n=t.app.get("existsPath")||j;return t.params=r(t.params,`${n}.${t.path}.${e._id||t.id}`,e),t},C=["ucan"],P="*",A="$",U=async t=>{const e=t.app.get("authentication"),n=i(t,["auth",e.entity]);return n&&(t=r(t,[e.core_path,e.entity],n)),t=await g("jwt")(t).catch(e=>(console.error("got error in no throw auth",e),t))},q=async t=>{const e=t.app.get("authentication"),n=i(t,["auth",e.entity]);return n&&(t=r(t,[e.core_path,e.entity],n)),g("jwt")(t)},N=async t=>{let e={ok:!1,value:[]};const n=async(t,e)=>await c(t,e);for(const a in t){var i;if(null!=(i=e)&&i.ok)break;{const i=t[a],{ucan:s}=i,o=w(i,C);e=await n(s,o)}}return e},J=(t,e,n)=>async a=>{var s;const o=i(a.params,e.client_ucan),r=i(a.params,e.ucan_aud);return o&&r&&null!=n&&null!=(s=n.or)&&s.includes(a.method)?await N((t||[]).map(t=>({ucan:o,audience:r,requiredCapabilities:[t]}))):await c(o,{audience:r,requiredCapabilities:t})},K=(t,e)=>{const n=s({secretKey:e.secret}).did();return(t||[]).map(t=>({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}))},M=(t,e)=>async n=>{var a,s;const o=n.app.get("authentication"),c=null==(a=n.params)||null==(a=a.login)?void 0:a._id;if("$"===t)return c?n:await U(n);if(c||(n=await q(n)),"*"===t)return n;if(((null==e?void 0:e.adminPass)||[]).includes(n.method)&&(i(n.params,"admin_pass")||i(n.params,[o.core_path,"admin_pass"])))return n;let u={ok:!1,value:[]};const l=K(t,o);if(l.length?u=await J(l,o,e)(n):u.ok=!0,null!=(s=u)&&s.ok)return n;{var p;const{loginPass:t}=e||{loginPass:[[["*"],["nonExistentMethod"]]]};if(null!=t&&t.length){let e={},a=!0;const s=async t=>{let s=[];const c="*"===t[1];let l=-1;if(c?l=0:(s=t[1].map(t=>t.split("/")[0]),l=s.indexOf(n.method)),l>-1){const s=await S(n);n=O(n,s);const p=h((t[0]||[]).map(t=>i(s,t)).filter(t=>!!t).map(t=>Array.isArray(t)?t:[t])),d=i(n.params,[o.entity,"_id"]);if(p.map(t=>String(t)).includes(String(d)))if(u.ok=!0,"*"===t[1]||["find","get","remove"].some(e=>t[1].includes(e)))a=!1;else{const s=c?"*":t[1][l];if(s.split("/")[0]!==s){const t=s.split("/").slice(1).join("").split(",")||[];for(const a of t){const t=i(n.data,a);if(t)e=r(e,a,t);else for(const t of["$addToSet","$pull"]){const s=i(n.data,`${t}.${a}`);s&&(e=r(e,`${t}.${a}`,s))}}}else a=!1}}};var d,v=!1,g=!1;try{for(var y,m=function(t){var e,n,i,a=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,i=Symbol.iterator);a--;){if(n&&null!=(e=t[n]))return e.call(t);if(i&&null!=(e=t[i]))return new f(e.call(t));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}(t);v=!(y=await m.next()).done;v=!1){const t=y.value;if(!a)break;await s(t)}}catch(t){g=!0,d=t}finally{try{v&&null!=m.return&&await m.return()}finally{if(g)throw d}}a&&(n=r(n,"data",e))}if(null==(p=u)||!p.ok){let t=!1;l.forEach((e,n)=>{const a=(i(e,"capability.can.namespace")||"").split(":");a[1]&&(e=r(e,"capability.can.namespace",a[0]),t=!0)}),t&&(u=await J(l,o,e)(n))}if(u.ok)return n;throw console.error("Ucan capabilities requirements not met: ",u,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)}},V=(t,e)=>async n=>{const a=n.app.get("authentication"),s=i(n,["auth",a.entity]);if(s&&(n=r(n,[a.core_path,a.entity],s)),"before"===n.type){const{method:i}=n;return t[i]||t.all?await M(t[i]||t.all,e)(n):n}return n},W=()=>async e=>{const{add:r=[],remove:u=[]}=e.data;if(!(null!=r&&r.length||null!=u&&u.length))throw new Error("No new capabilities passed");const{secret:h,ucan_aud:d,entity:v,ucan:g}=e.app.get("authentication"),y=s({secretKey:h}).did(),f=l([...r,...u]),w=await c(i(e.params,[v,g]),{audience:i(e.params,d),requiredCapabilities:f.map(t=>({capability:t,rootIssuer:y}))});if(null==w||!w.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");const x=e.id,_=e.data.service||"logins",b=e.data.path||"ucan",k=await new I(_,e,{skipJoins:!0}).get(x),E=a(i(k,b)),{aud:T,att:j,prf:$}=E.payload;let S=[...j];null!=u&&u.length&&(S=p(u,j)),null!=r&&r.length&&(S=l([...j,...r]));const O=await o(m({issuer:s({secretKey:h}),audience:T,lifetimeInSeconds:5184e3,proofs:$},e.data,{capabilities:S})),C=n(O);if(!await t(C))throw new Error("Invalid ucan generated when updating");const P=await new I(_,e).patch(x,{[b]:C});return e.result={raw:e.data,encoded:C,subject:P},e};export{T as AuthService,I as CoreCall,E as NotAuthError,b as UcanStrategy,V as allUcanAuth,P as anyAuth,q as bareAuth,j as existsPath,$ as getExists,S as loadExists,K as modelCapabilities,A as noThrow,U as noThrowAuth,N as orVerifyLoop,O as setExists,M as ucanAuth,W as updateUcan,J as verifyAgainstReqs};
@@ -1 +1 @@
1
- import{validateUcan as e,_unset as t,ucanToken as r,_get as n,parseUcan as i,encodeKeyPair as o,buildUcan as a,_set as c,verifyUcan as u,genCapability as s,_flatten as l,stackAbilities as f,reduceAbilities as h}from"symbol-ucan";import{AuthenticationBaseStrategy as p,AuthenticationService as v,authenticate as d}from"@feathersjs/authentication";import m from"long-timeout";function y(){return y=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},y.apply(this,arguments)}function g(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,w(e,t)}function P(e){return P=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},P(e)}function w(e,t){return w=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},w(e,t)}function b(e,t,r){return b=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(e){return!1}}()?Reflect.construct.bind():function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&w(i,r.prototype),i},b.apply(null,arguments)}function x(e){var t="function"==typeof Map?new Map:void 0;return x=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return b(e,arguments,P(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),w(r,e)},x(e)}function j(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)t.indexOf(r=o[n])>=0||(i[r]=e[r]);return i}function _(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var k=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return g(t,e),t}(/*#__PURE__*/x(Error)),E=/(\S+)\s+(\S+)/,O=/*#__PURE__*/function(i){function o(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(e=i.call.apply(i,[this].concat(r))||this).expirationTimers=new WeakMap,e}g(o,i);var a,c,u=o.prototype;return u.setAuthentication=function(e){e.verifyAccessToken=function(e){return{}},this.authentication=e},u.handleConnection=function(t,r,n){try{var i=this,o="logout"===t&&r.authentication&&n&&r.authentication.accessToken===n.accessToken,a=(n||{}).accessToken,c=function(){if(a&&"login"===t)return Promise.resolve(e(a).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){var t=1e3*(e||{payload:{exp:0}}).payload.exp-Date.now(),n=m.setTimeout(function(){return i.app.emit("disconnect",r)},t);m.clearTimeout(i.expirationTimers.get(r)),i.expirationTimers.set(r,n),r.authentication={strategy:i.name,accessToken:a}});("disconnect"===t||o)&&(delete r[i.configuration.entity],delete r.authentication,m.clearTimeout(i.expirationTimers.get(r)),i.expirationTimers.delete(r))}();return Promise.resolve(c&&c.then?c.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},u.verifyConfiguration=function(){for(var e=["entity","entityId","service","header","schemes","audience"],t=0,r=Object.keys(this.configuration);t<r.length;t++){var n=r[t];if(!e.includes(n))throw new Error("Invalid ucanStrategy option 'authentication."+this.name+"."+n+"'. 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(e){return Promise.resolve({})},u.getEntity=function(e,r){try{var n=this,i=n.entityService,o=n.configuration.entity;if(null===i)throw new k("Could not find entity service");return Promise.resolve(n.getEntityQuery(r)).then(function(n){var a=Object.assign({},t(r,"provider"),{query:n});return Promise.resolve(i.get(e,a)).then(function(t){var n;return r.provider?i.get(e,y({},r,((n={})[o]=t,n))):t})})}catch(e){return Promise.reject(e)}},u.getEntityId=function(e,t){try{var r=t.query,n=t.loginId;if(n)return Promise.resolve(n);var i,o,a=this.configuration,c=a.service,u=a.core_path,s=void 0===u?"core":u,l=((i={query:y({},r,{$limit:1})})[s]=y({skipJoins:!0},t[s]),i);return Promise.resolve(null==(o=this.app)?void 0:o.service(c).find(y({},l,{skipJoins:!0}))).then(function(e){if(e.total)return e.data[0]._id;throw new k("Could not find login associated with this ucan")})}catch(e){return Promise.reject(e)}},u.authenticate=function(t,i){try{var o=this,a=t.accessToken,c=t.loginId,u=t.ucan,s=o.configuration,l=s.entity,f=s.core_path;if(!a){if(!u)throw new k("Error generating ucan");a=r(u)}return Promise.resolve(e(a).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){function t(){var e;return y({},u,((e={})[l]=r,e))}var r,u={accessToken:a,authentication:{strategy:"jwt",accessToken:a}};if(null===l)return u;var s=n(i,[f,l]),h=function(){if(!s)return Promise.resolve(o.getEntityId(u,y({},i,{loginId:c,query:{did:null==e?void 0:e.payload.aud}}))).then(function(e){return Promise.resolve(o.getEntity(e,i)).then(function(e){r=e})});r=s}();return h&&h.then?h.then(t):t()})}catch(e){return Promise.reject(e)}},u.parse=function(e){try{var t=this.configuration,r=t.schemes,n=e.headers&&e.headers[t.header.toLowerCase()];if(!n||"string"!=typeof n)return Promise.resolve(null);var i=n.match(E)||[],o=i[1],a=i[2],c=o&&r.some(function(e){return new RegExp(e,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:n})}catch(e){return Promise.reject(e)}},a=o,(c=[{key:"configuration",get:function(){var e,t=(null==(e=this.authentication)?void 0:e.configuration)||{service:void 0,entity:void 0,entityId:void 0};return y({service:t.service,entity:t.entity,entityId:t.entityId,header:"Authorization",schemes:["Bearer","JWT"]},i.prototype.configuration)}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,"symbol"==typeof(i=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(n.key))?i:String(i),n)}var i}(a.prototype,c),Object.defineProperty(a,"prototype",{writable:!1}),o}(p),T=["NotAuthenticated"],S=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return g(t,e),t}(/*#__PURE__*/x(Error)),I=/*#__PURE__*/function(t){function c(e,r,n){var i;void 0===r&&(r="authentication"),void 0===n&&(n={});var o=n.NotAuthenticated,a=j(n,T);return(i=t.call(this,e,r,a)||this).options=void 0,i.app=e,i.options={NotAuthenticated:o},i}return g(c,t),c.prototype.create=function(t,c){try{var u,s,l=this,f=(null==(u=l.options)?void 0:u.NotAuthenticated)||S,h=l.app.get("authentication"),p=h.entity,v=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,[t,c].concat(g)).catch(function(e){throw new Error(e.message)})).then(function(u){if(u.accessToken)return u;var s=t.did||n(u,[p,"did"]),f=t.ucan||n(u,[p,"ucan"]);if(!s)throw new Error("No did audience provided");if(!f)throw new Error("No ucan provided to authentication call");return Promise.resolve(e(f).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};return e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),console.warn("Could not validate ucan",f,t.message),null})).then(function(e){function t(){var e=r(f);return y({accessToken:e},u,{authentication:y({},u.authentication,{payload:e})})}var s=function(){if(!e){var t=i(f),s=l.app.get("authentication"),h=o({secretKey:s.secret});return Promise.resolve(a({audience:t.payload.aud,issuer:h,lifetimeInSeconds:5184e3,capabilities:t.payload.att})).then(function(e){var t;return f=e,c.admin_pass=!0,Promise.resolve(l.app.service(v).patch(n(u,[p,"_id"]),(t={},t[m]=r(f),t),y({},c))).then(function(){})})}}();return s&&s.then?s.then(t):t()})})}catch(e){return Promise.reject(e)}},c}(v),A=/*#__PURE__*/function(){function e(e,t,r){var n;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=y({},null==(n=t.params)?void 0:n.core,r)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var r,n,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(r=i.context.app)?void 0:r.service(i.service).get(e,y({},t,((n={})[o]=i.core,n))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,r,n=this,i=n.context.app.get("authentication").core_path;return Promise.resolve(null==(t=n.context.app)?void 0:t.service(n.service).find(y({},e,((r={})[i]=n.core,r))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var r,n,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(r=i.context.app)?void 0:r.service(i.service).create(e,y({},t,((n={})[o]=i.core,n))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r){void 0===r&&(r={});try{var n,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).patch(e,t,y({},r,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,r){void 0===r&&(r={});try{var n,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).update(e,t,y({},r,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var r,n,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(r=i.context.app)?void 0:r.service(i.service).remove(e,y({},t,((n={})[o]=i.core,n))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var r,n,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(r=i.context.app)?void 0:r.service(i.service)._get(e,y({},t,((n={})[o]=i.core,n))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,r,n=this,i=n.context.app.get("authentication").core_path;return Promise.resolve(null==(t=n.context.app)?void 0:t.service(n.service)._find(y({},e,((r={})[i]=n.core,r))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var r,n,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(r=i.context.app)?void 0:r.service(i.service)._create(e,y({},t,((n={})[o]=i.core,n))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,r){void 0===r&&(r={});try{var n,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)._patch(e,t,y({},r,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,r){void 0===r&&(r={});try{var n,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)._update(e,t,y({},r,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var r,n,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(r=i.context.app)?void 0:r.service(i.service)._remove(e,y({},t,((n={})[o]=i.core,n))))}catch(e){return Promise.reject(e)}},e}(),C="_exists",U=function(e){var t=e.app.get("existsPath")||C;return e.params?e.params[t+"_"+e.path]:void 0},q=function(e,t){try{var r=U(e),n=function(){if(!r&&e.id)return Promise.resolve(new A(e.path,e,{skipJoins:!1!==(null==t?void 0:t.skipJoins)}).get(e.id,{admin_pass:!0})).then(function(e){r=e})}();return Promise.resolve(n&&n.then?n.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},N=function(e,t){var r=e.app.get("existsPath")||C;return e.params[r+"_"+e.path]=t,e},J=["ucan"];function M(e,t,r){if(!e.s){if(r instanceof R){if(!r.s)return void(r.o=M.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(M.bind(null,e,t),M.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}const R=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,r){const n=new e,i=this.s;if(i){const e=1&i?t:r;if(e){try{M(n,1,e(this.v))}catch(e){M(n,2,e)}return n}return this}return this.o=function(e){try{const i=e.v;1&e.s?M(n,1,t?t(i):i):r?M(n,1,r(i)):M(n,2,i)}catch(e){M(n,2,e)}},n},e}();var $="*",K="$",B=function(e){try{var t=e.app.get("authentication"),r=n(e,["auth",t.entity]);return r&&(e=c(e,[t.core_path,t.entity],r)),Promise.resolve(d("jwt")(e).catch(function(t){return console.error("got error in no throw auth",t),e})).then(function(t){return e=t})}catch(e){return Promise.reject(e)}},V=function(e){try{var t=e.app.get("authentication"),r=n(e,["auth",t.entity]);return r&&(e=c(e,[t.core_path,t.entity],r)),Promise.resolve(d("jwt")(e))}catch(e){return Promise.reject(e)}},W=function(e){try{var t,r={ok:!1,value:[]},n=function(n,i,o){var a=[];for(var c in n)a.push(c);return function(e,t,r){var n,i,o=-1;return function a(c){try{for(;++o<e.length&&(!r||!r());)if((c=t(o))&&c.then){if(!((u=c)instanceof R&&1&u.s))return void c.then(a,i||(i=M.bind(null,n=new R,2)));c=c.v}n?M(n,1,c):n=c}catch(e){M(n||(n=new R),2,e)}var u}(),n}(a,function(n){return function(n){var i=function(i){if(null==(i=r)||!i.ok){var o=e[n],a=o.ucan,c=j(o,J);return Promise.resolve(function(e,t){try{return Promise.resolve(u(e,t))}catch(e){return Promise.reject(e)}}(a,c)).then(function(e){r=e})}t=1}();if(i&&i.then)return i.then(function(){})}(a[n])},function(){return t})}(e);return Promise.resolve(n&&n.then?n.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},D=function(e,t,r){return function(i){try{var o,a=n(i.params,t.client_ucan),c=n(i.params,t.ucan_aud);return a&&c&&null!=r&&null!=(o=r.or)&&o.includes(i.method)?Promise.resolve(W((e||[]).map(function(e){return{ucan:a,audience:c,requiredCapabilities:[e]}}))):Promise.resolve(u(a,{audience:c,requiredCapabilities:e}))}catch(e){return Promise.reject(e)}}},F=function(e,t){var r=o({secretKey:t.secret}).did();return(e||[]).map(function(e){return{capability:Array.isArray(e)?s({with:{scheme:t.defaultScheme,hierPart:t.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},t):s(e,t),rootIssuer:r}})},Q=function(e,t){return function(r){try{var i,o,a=function(i){if(o)return i;function a(){function i(){var e,i;if(null!=(e=o)&&e.ok)return r;var s=function(e){if(i)return e;function s(){if(o.ok)return r;throw console.error("Ucan capabilities requirements not met: ",o,r.type,r.path),new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)}var l=function(e){if(null==(e=o)||!e.ok){var i=!1,s=[];a.forEach(function(e,t){var r=(n(e,"capability.can.namespace")||"").split(":");r[1]&&(e=c(e,"capability.can.namespace",r[0]),i=!0),s.push(e)});var l=function(){if(i)return Promise.resolve(D(a,u,t)(r)).then(function(e){o=e})}();if(l&&l.then)return l.then(function(){})}}();return l&&l.then?l.then(s):s()},f=(t||{loginPass:[["*"],["nonExistentMethod"]]}).loginPass,h=function(){if(null!=f&&f.length){var e=("*"===f[1]?[r.method]:f[1].map(function(e){return e.split("/")[0]})).indexOf(r.method);return function(){if(e>-1)return Promise.resolve(q(r)).then(function(t){if(r=N(r,t),f){var a=l((f[0]||[]).map(function(e){return n(t,e)}).filter(function(e){return!!e}).map(function(e){return Array.isArray(e)?e:[e]})),s=n(r.params,[u.entity,"_id"]);if(a.map(function(e){return String(e)}).includes(String(s))){if("*"!==f[1]&&!["find","get","remove"].includes(r.method)){for(var h,p={},v=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return _(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_(e,t):void 0}}(e))){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(f[1][e].split(",")||[]);!(h=v()).done;){var d=h.value,m=n(r.data,d);if(m)p=c(p,d,m);else for(var y=0,g=["$addToSet","$pull"];y<g.length;y++){var P=g[y],w=n(r.data,P+"."+d);w&&(p=c(p,P+"."+d,w))}}return r=c(r,"data",p),i=1,r}o.ok=!0}}})}()}}();return h&&h.then?h.then(s):s(h)}if("*"===e)return r;if(((null==t?void 0:t.adminPass)||[]).includes(r.method)&&(n(r.params,"admin_pass")||n(r.params,[u.core_path,"admin_pass"])))return r;var o={ok:!1,value:[]},a=F(e,u),s=function(){if(a.length)return Promise.resolve(D(a,u,t)(r)).then(function(e){o=e});o.ok=!0}();return s&&s.then?s.then(i):i()}var f=function(){if(!s)return Promise.resolve(V(r)).then(function(e){r=e})}();return f&&f.then?f.then(a):a()},u=r.app.get("authentication"),s=null==(i=r.params)||null==(i=i.login)?void 0:i._id,f=function(){if("$"===e){var t=function(e){return o=1,e};return s?t(r):Promise.resolve(B(r)).then(t)}}();return Promise.resolve(f&&f.then?f.then(a):a(f))}catch(e){return Promise.reject(e)}}},z=function(e,t){return function(r){try{var i=r.app.get("authentication"),o=n(r,["auth",i.entity]);if(o&&(r=c(r,[i.core_path,i.entity],o)),"before"===r.type){var a=r.method;return Promise.resolve(e[a]||e.all?Q(e[a]||e.all,t)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},H=function(){return function(t){try{var c=t.data,s=c.add,l=void 0===s?[]:s,p=c.remove,v=void 0===p?[]:p;if(!(null!=l&&l.length||null!=v&&v.length))throw new Error("No new capabilities passed");var d=t.app.get("authentication"),m=d.secret,g=d.ucan_aud,P=d.entity,w=d.ucan,b=o({secretKey:m}).did(),x=f([].concat(l,v));return Promise.resolve(u(n(t.params,[P,w]),{audience:n(t.params,g),requiredCapabilities:x.map(function(e){return{capability:e,rootIssuer:b}})})).then(function(c){if(null==c||!c.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var u=t.id,s=t.data.service||"logins",p=t.data.path||"ucan";return Promise.resolve(new A(s,t,{skipJoins:!0}).get(u)).then(function(c){var d=i(n(c,p)).payload,g=d.aud,P=d.att,w=d.prf,b=[].concat(P);return null!=v&&v.length&&(b=h(v,P)),null!=l&&l.length&&(b=f([].concat(P,l))),Promise.resolve(a(y({issuer:o({secretKey:m}),audience:g,lifetimeInSeconds:5184e3,proofs:w},t.data,{capabilities:b}))).then(function(n){var i=r(n);return Promise.resolve(e(i)).then(function(e){var r;if(!e)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new A(s,t).patch(u,(r={},r[p]=i,r))).then(function(e){return t.result={raw:t.data,encoded:i,subject:e},t})})})})})}catch(e){return Promise.reject(e)}}};export{I as AuthService,A as CoreCall,S as NotAuthError,O as UcanStrategy,z as allUcanAuth,$ as anyAuth,V as bareAuth,C as existsPath,U as getExists,q as loadExists,F as modelCapabilities,K as noThrow,B as noThrowAuth,W as orVerifyLoop,N as setExists,Q as ucanAuth,H as updateUcan,D as verifyAgainstReqs};
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,verifyUcan as u,genCapability as s,_flatten as f,stackAbilities as l,reduceAbilities as h}from"symbol-ucan";import{AuthenticationBaseStrategy as v,AuthenticationService as p,authenticate as d}from"@feathersjs/authentication";import m from"long-timeout";function y(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 y=function(t){this.s=t,this.n=t.next},y.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 y(t)}function g(){return g=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},g.apply(this,arguments)}function P(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,b(t,e)}function w(t){return w=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},w(t)}function b(t,e){return b=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},b(t,e)}function j(t,e,n){return j=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},j.apply(null,arguments)}function x(t){var e="function"==typeof Map?new Map:void 0;return x=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 j(t,arguments,w(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),b(n,t)},x(t)}function _(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 k(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}var E=/*#__PURE__*/function(t){function e(e){return t.call(this,e)||this}return P(e,t),e}(/*#__PURE__*/x(Error)),O=/(\S+)\s+(\S+)/,T=/*#__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}P(o,i);var a,c,u=o.prototype;return u.setAuthentication=function(t){t.verifyAccessToken=function(t){return{}},this.authentication=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: ",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=m.setTimeout(function(){return i.app.emit("disconnect",n)},e);m.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,m.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 E("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,g({},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,f=((i={query:g({},n,{$limit:1})})[s]=g({skipJoins:!0},e[s]),i);return Promise.resolve(null==(o=this.app)?void 0:o.service(c).find(g({},f,{skipJoins:!0}))).then(function(t){if(t.total)return t.data[0]._id;throw new E("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,f=s.entity,l=s.core_path;if(!a){if(!u)throw new E("Error generating ucan");a=n(u)}return Promise.resolve(t(a).catch(function(t){console.log("Could not validate ucan: ",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 g({},u,((t={})[f]=n,t))}var n,u={accessToken:a,authentication:{strategy:"jwt",accessToken:a}};if(null===f)return u;var s=r(i,[l,f]),h=function(){if(!s)return Promise.resolve(o.getEntityId(u,g({},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(O)||[],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 g({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}(v),S=["NotAuthenticated"],I=/*#__PURE__*/function(t){function e(e){return t.call(this,e)||this}return P(e,t),e}(/*#__PURE__*/x(Error)),A=/*#__PURE__*/function(e){function c(t,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=_(r,S);return(i=e.call(this,t,n,a)||this).options=void 0,i.app=t,i.options={NotAuthenticated:o},i}return P(c,e),c.prototype.create=function(e,c){try{var u,s,f=this,l=(null==(u=f.options)?void 0:u.NotAuthenticated)||I,h=f.app.get("authentication"),v=h.entity,p=h.service,d=h.ucan_path,m=void 0===d?"ucan":d,y=(null==(s=c)?void 0:s.authStrategies)||f.configuration.authStrategies;if(c||(c={}),!y.length)throw new l("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(f.authenticate.apply(f,[e,c].concat(y)).catch(function(t){throw new Error(t.message)})).then(function(u){if(u.accessToken)return u;var s=e.did||r(u,[v,"did"]),l=e.ucan||r(u,[v,"ucan"]);if(!s)throw new Error("No did audience provided");if(!l)throw new Error("No ucan provided to authentication call");return Promise.resolve(t(l).catch(function(t){console.log("Could not validate ucan: ",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",l,e.message),null})).then(function(t){function e(){var t=n(l);return g({accessToken:t},u,{authentication:g({},u.authentication,{payload:t})})}var s=function(){if(!t){var e=i(l),s=f.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 l=t,c.admin_pass=!0,Promise.resolve(f.app.service(p).patch(r(u,[v,"_id"]),(e={},e[m]=n(l),e),g({},c))).then(function(){})})}}();return s&&s.then?s.then(e):e()})})}catch(t){return Promise.reject(t)}},c}(p),C=/*#__PURE__*/function(){function t(t,e,n){var r;this.context=void 0,this.service=void 0,this.core=void 0,this.service=t,this.context=e,this.core=g({},null==(r=e.params)?void 0:r.core,n)}var e=t.prototype;return e.get=function(t,e){void 0===e&&(e={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).get(t,g({},e,((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e.find=function(t){void 0===t&&(t={});try{var e,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(e=r.context.app)?void 0:e.service(r.service).find(g({},t,((n={})[i]=r.core,n))))}catch(t){return Promise.reject(t)}},e.create=function(t,e){void 0===e&&(e={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).create(t,g({},e,((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e.patch=function(t,e,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).patch(t,e,g({},n,((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e.update=function(t,e,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).update(t,e,g({},n,((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e.remove=function(t,e){void 0===e&&(e={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).remove(t,g({},e,((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e._get=function(t,e){void 0===e&&(e={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._get(t,g({},e,((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e._find=function(t){void 0===t&&(t={});try{var e,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(e=r.context.app)?void 0:e.service(r.service)._find(g({},t,((n={})[i]=r.core,n))))}catch(t){return Promise.reject(t)}},e._create=function(t,e){void 0===e&&(e={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._create(t,g({},e,((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},e._patch=function(t,e,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._patch(t,e,g({},n,((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e._update=function(t,e,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._update(t,e,g({},n,((i={})[a]=o.core,i))))}catch(t){return Promise.reject(t)}},e._remove=function(t,e){void 0===e&&(e={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._remove(t,g({},e,((r={})[o]=i.core,r))))}catch(t){return Promise.reject(t)}},t}(),U="_exists",q=function(t){var e=t.app.get("existsPath")||U;return r(t.params,e+"."+t.path+"."+t.id)||void 0},N=function(t,e){try{var n=q(t),r=function(){if(!n&&t.id)return Promise.resolve(new C(t.path,t,{skipJoins:!1!==(null==e?void 0:e.skipJoins)}).get(t.id,{admin_pass:!0})).then(function(t){n=t})}();return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(t){return Promise.reject(t)}},J=function(t,e){var n=t.app.get("existsPath")||U;return t.params=c(t.params,n+"."+t.path+"."+(e._id||t.id),e),t},M=["ucan"];function R(t,e,n){if(!t.s){if(n instanceof $){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 $=/*#__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 K(t){return t instanceof $&&1&t.s}function B(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 V="*",W="$",D=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(d("jwt")(t).catch(function(e){return console.error("got error in no throw auth",e),t})).then(function(e){return t=e})}catch(t){return Promise.reject(t)}},F=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(d("jwt")(t))}catch(t){return Promise.reject(t)}},Q=function(t){try{var e,n={ok:!1,value:[]},r=function(r,i,o){var a=[];for(var c in r)a.push(c);return function(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(!K(c))return void c.then(a,i||(i=R.bind(null,r=new $,2)));c=c.v}r?R(r,1,c):r=c}catch(t){R(r||(r=new $),2,t)}}(),r}(a,function(r){return function(r){var i=function(i){if(null==(i=n)||!i.ok){var o=t[r],a=o.ucan,c=_(o,M);return Promise.resolve(function(t,e){try{return Promise.resolve(u(t,e))}catch(t){return Promise.reject(t)}}(a,c)).then(function(t){n=t})}e=1}();if(i&&i.then)return i.then(function(){})}(a[r])},function(){return e})}(t);return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(t){return Promise.reject(t)}},z=function(t,e,n){return function(i){try{var o,a=r(i.params,e.client_ucan),c=r(i.params,e.ucan_aud);return a&&c&&null!=n&&null!=(o=n.or)&&o.includes(i.method)?Promise.resolve(Q((t||[]).map(function(t){return{ucan:a,audience:c,requiredCapabilities:[t]}}))):Promise.resolve(u(a,{audience:c,requiredCapabilities:t}))}catch(t){return Promise.reject(t)}}},H=function(t,e){var n=o({secretKey:e.secret}).did();return(t||[]).map(function(t){return{capability:Array.isArray(t)?s({with:{scheme:e.defaultScheme,hierPart:e.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},e):s(t,e),rootIssuer:n}})},L=function(t,e){return function(n){try{var i,o,a=function(i){if(o)return i;function a(){function i(){var t;if(null!=(t=o)&&t.ok)return n;var i=function(t){function i(){if(o.ok)return n;throw console.error("Ucan capabilities requirements not met: ",o,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)}var s=function(t){if(null==(t=o)||!t.ok){var i=!1,s=[];a.forEach(function(t,e){var n=(r(t,"capability.can.namespace")||"").split(":");n[1]&&(t=c(t,"capability.can.namespace",n[0]),i=!0),s.push(t)});var f=function(){if(i)return Promise.resolve(z(a,u,e)(n)).then(function(t){o=t})}();if(f&&f.then)return f.then(function(){})}}();return s&&s.then?s.then(i):i()},s=(e||{loginPass:[[["*"],["nonExistentMethod"]]]}).loginPass,l=function(){if(null!=s&&s.length){var t,e=function(t){if(_interrupt2)return t;a&&(n=c(n,"data",i))},i={},a=!0,l=!1,h=!1,v=B(function(){return function(t,e){try{var h=function(){var t,e,h=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 y(e.call(t));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(s),v=function(t,e,n){for(var r;;){var i=t();if(K(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!K(o)){r=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!K(a)){r=2;break}}}var c=new $,u=R.bind(null,c,2);return(0===r?i.then(f):1===r?o.then(s):a.then(l)).then(void 0,u),c;function s(r){o=r;do{if(e&&(a=e())&&a.then&&!K(a))return void a.then(l).then(void 0,u);if(!(i=t())||K(i)&&!i.v)return void R(c,1,o);if(i.then)return void i.then(f).then(void 0,u);K(o=n())&&(o=o.v)}while(!o||!o.then);o.then(s).then(void 0,u)}function f(t){t?(o=n())&&o.then?o.then(s).then(void 0,u):s(o):R(c,1,o)}function l(){(i=t())?i.then?i.then(f).then(void 0,u):f(i):R(c,1,o)}}(function(){function n(n){return!t&&(l=!(e=n).done)}return t?!!n(!t&&h.next()):Promise.resolve(!t&&h.next()).then(n)},function(){return!!(l=!1)},function(){var s=e.value,l=function(){if(a)return Promise.resolve(function(t){try{var e=[],s="*"===t[1],l=-1;s?l=0:(e=t[1].map(function(t){return t.split("/")[0]}),l=e.indexOf(n.method));var h=function(){if(l>-1)return Promise.resolve(N(n)).then(function(e){n=J(n,e);var h=f((t[0]||[]).map(function(t){return r(e,t)}).filter(function(t){return!!t}).map(function(t){return Array.isArray(t)?t:[t]})),v=r(n.params,[u.entity,"_id"]);if(h.map(function(t){return String(t)}).includes(String(v)))if(o.ok=!0,"*"===t[1]||["find","get","remove"].some(function(e){return t[1].includes(e)}))a=!1;else{var p=s?"*":t[1][l];if(p.split("/")[0]!==p)for(var d,m=function(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 k(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)?k(t,e):void 0}}(t))){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.")}(p.split("/").slice(1).join("").split(",")||[]);!(d=m()).done;){var y=d.value,g=r(n.data,y);if(g)i=c(i,y,g);else for(var P=0,w=["$addToSet","$pull"];P<w.length;P++){var b=w[P],j=r(n.data,b+"."+y);j&&(i=c(i,b+"."+y,j))}}else a=!1}})}();return Promise.resolve(h&&h.then?h.then(function(){}):void 0)}catch(t){return Promise.reject(t)}}(s)).then(function(){});t=1}();return l&&l.then?l.then(function(){}):void 0});if(v&&v.then)return v.then(function(){})}()}catch(t){return e(t)}return h&&h.then?h.then(void 0,e):h}(0,function(e){h=!0,t=e})},function(e,n){function r(t){if(e)throw n;return n}var i=B(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(h)throw t;if(e)throw n;return n});return i&&i.then?i.then(r):r()});return v&&v.then?v.then(e):e(v)}}();return l&&l.then?l.then(i):i()}if("*"===t)return n;if(((null==e?void 0:e.adminPass)||[]).includes(n.method)&&(r(n.params,"admin_pass")||r(n.params,[u.core_path,"admin_pass"])))return n;var o={ok:!1,value:[]},a=H(t,u),s=function(){if(a.length)return Promise.resolve(z(a,u,e)(n)).then(function(t){o=t});o.ok=!0}();return s&&s.then?s.then(i):i()}var l=function(){if(!s)return Promise.resolve(F(n)).then(function(t){n=t})}();return l&&l.then?l.then(a):a()},u=n.app.get("authentication"),s=null==(i=n.params)||null==(i=i.login)?void 0:i._id,l=function(){if("$"===t){var e=function(t){return o=1,t};return s?e(n):Promise.resolve(D(n)).then(e)}}();return Promise.resolve(l&&l.then?l.then(a):a(l))}catch(t){return Promise.reject(t)}}},Y=function(t,e){return function(n){try{var i=n.app.get("authentication"),o=r(n,["auth",i.entity]);if(o&&(n=c(n,[i.core_path,i.entity],o)),"before"===n.type){var a=n.method;return Promise.resolve(t[a]||t.all?L(t[a]||t.all,e)(n):n)}return Promise.resolve(n)}catch(t){return Promise.reject(t)}}},G=function(){return function(e){try{var c=e.data,s=c.add,f=void 0===s?[]:s,v=c.remove,p=void 0===v?[]:v;if(!(null!=f&&f.length||null!=p&&p.length))throw new Error("No new capabilities passed");var d=e.app.get("authentication"),m=d.secret,y=d.ucan_aud,P=d.entity,w=d.ucan,b=o({secretKey:m}).did(),j=l([].concat(f,p));return Promise.resolve(u(r(e.params,[P,w]),{audience:r(e.params,y),requiredCapabilities:j.map(function(t){return{capability:t,rootIssuer:b}})})).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 C(s,e,{skipJoins:!0}).get(u)).then(function(c){var d=i(r(c,v)).payload,y=d.aud,P=d.att,w=d.prf,b=[].concat(P);return null!=p&&p.length&&(b=h(p,P)),null!=f&&f.length&&(b=l([].concat(P,f))),Promise.resolve(a(g({issuer:o({secretKey:m}),audience:y,lifetimeInSeconds:5184e3,proofs:w},e.data,{capabilities:b}))).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 C(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{A as AuthService,C as CoreCall,I as NotAuthError,T as UcanStrategy,Y as allUcanAuth,V as anyAuth,F as bareAuth,U as existsPath,q as getExists,N as loadExists,H as modelCapabilities,W as noThrow,D as noThrowAuth,Q as orVerifyLoop,J as setExists,L as ucanAuth,G as updateUcan,z as verifyAgainstReqs};
package/lib/index.umd.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("symbol-ucan"),require("@feathersjs/authentication"),require("long-timeout")):"function"==typeof define&&define.amd?define(["exports","symbol-ucan","@feathersjs/authentication","long-timeout"],t):t((e||self).feathersUcan={},e.symbolUcan,e.authentication,e.longTimeout)}(this,function(e,t,n,r){function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/i(r);function a(){return a=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a.apply(this,arguments)}function c(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,s(e,t)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}function s(e,t){return s=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},s(e,t)}function l(e,t,n){return l=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(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&s(i,n.prototype),i},l.apply(null,arguments)}function f(e){var t="function"==typeof Map?new Map:void 0;return f=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return l(e,arguments,u(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),s(n,e)},f(e)}function h(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t.indexOf(n=o[r])>=0||(i[n]=e[n]);return i}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var v=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return c(t,e),t}(/*#__PURE__*/f(Error)),d=/(\S+)\s+(\S+)/,m=/*#__PURE__*/function(e){function n(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=e.call.apply(e,[this].concat(r))||this).expirationTimers=new WeakMap,t}c(n,e);var r,i,u=n.prototype;return u.setAuthentication=function(e){e.verifyAccessToken=function(e){return{}},this.authentication=e},u.handleConnection=function(e,n,r){try{var i=this,a="logout"===e&&n.authentication&&r&&n.authentication.accessToken===r.accessToken,c=(r||{}).accessToken,u=function(){if(c&&"login"===e)return Promise.resolve(t.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){var t=1e3*(e||{payload:{exp:0}}).payload.exp-Date.now(),r=o.default.setTimeout(function(){return i.app.emit("disconnect",n)},t);o.default.clearTimeout(i.expirationTimers.get(n)),i.expirationTimers.set(n,r),n.authentication={strategy:i.name,accessToken:c}});("disconnect"===e||a)&&(delete n[i.configuration.entity],delete n.authentication,o.default.clearTimeout(i.expirationTimers.get(n)),i.expirationTimers.delete(n))}();return Promise.resolve(u&&u.then?u.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},u.verifyConfiguration=function(){for(var e=["entity","entityId","service","header","schemes","audience"],t=0,n=Object.keys(this.configuration);t<n.length;t++){var r=n[t];if(!e.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(e){return Promise.resolve({})},u.getEntity=function(e,n){try{var r=this,i=r.entityService,o=r.configuration.entity;if(null===i)throw new v("Could not find entity service");return Promise.resolve(r.getEntityQuery(n)).then(function(r){var c=Object.assign({},t._unset(n,"provider"),{query:r});return Promise.resolve(i.get(e,c)).then(function(t){var r;return n.provider?i.get(e,a({},n,((r={})[o]=t,r))):t})})}catch(e){return Promise.reject(e)}},u.getEntityId=function(e,t){try{var n=t.query,r=t.loginId;if(r)return Promise.resolve(r);var i,o,c=this.configuration,u=c.service,s=c.core_path,l=void 0===s?"core":s,f=((i={query:a({},n,{$limit:1})})[l]=a({skipJoins:!0},t[l]),i);return Promise.resolve(null==(o=this.app)?void 0:o.service(u).find(a({},f,{skipJoins:!0}))).then(function(e){if(e.total)return e.data[0]._id;throw new v("Could not find login associated with this ucan")})}catch(e){return Promise.reject(e)}},u.authenticate=function(e,n){try{var r=this,i=e.accessToken,o=e.loginId,c=e.ucan,u=r.configuration,s=u.entity,l=u.core_path;if(!i){if(!c)throw new v("Error generating ucan");i=t.ucanToken(c)}return Promise.resolve(t.validateUcan(i).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){function c(){var e;return a({},f,((e={})[s]=u,e))}var u,f={accessToken:i,authentication:{strategy:"jwt",accessToken:i}};if(null===s)return f;var h=t._get(n,[l,s]),p=function(){if(!h)return Promise.resolve(r.getEntityId(f,a({},n,{loginId:o,query:{did:null==e?void 0:e.payload.aud}}))).then(function(e){return Promise.resolve(r.getEntity(e,n)).then(function(e){u=e})});u=h}();return p&&p.then?p.then(c):c()})}catch(e){return Promise.reject(e)}},u.parse=function(e){try{var t=this.configuration,n=t.schemes,r=e.headers&&e.headers[t.header.toLowerCase()];if(!r||"string"!=typeof r)return Promise.resolve(null);var i=r.match(d)||[],o=i[1],a=i[2],c=o&&n.some(function(e){return new RegExp(e,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:r})}catch(e){return Promise.reject(e)}},r=n,(i=[{key:"configuration",get:function(){var t,n=(null==(t=this.authentication)?void 0:t.configuration)||{service:void 0,entity:void 0,entityId:void 0};return a({service:n.service,entity:n.entity,entityId:n.entityId,header:"Authorization",schemes:["Bearer","JWT"]},e.prototype.configuration)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,"symbol"==typeof(i=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(r.key))?i:String(i),r)}var i}(r.prototype,i),Object.defineProperty(r,"prototype",{writable:!1}),n}(n.AuthenticationBaseStrategy),y=["NotAuthenticated"],g=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return c(t,e),t}(/*#__PURE__*/f(Error)),P=/*#__PURE__*/function(e){function n(t,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=h(r,y);return(i=e.call(this,t,n,a)||this).options=void 0,i.app=t,i.options={NotAuthenticated:o},i}return c(n,e),n.prototype.create=function(e,n){try{var r,i,o=this,c=(null==(r=o.options)?void 0:r.NotAuthenticated)||g,u=o.app.get("authentication"),s=u.entity,l=u.service,f=u.ucan_path,h=void 0===f?"ucan":f,p=(null==(i=n)?void 0:i.authStrategies)||o.configuration.authStrategies;if(n||(n={}),!p.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(o.authenticate.apply(o,[e,n].concat(p)).catch(function(e){throw new Error(e.message)})).then(function(r){if(r.accessToken)return r;var i=e.did||t._get(r,[s,"did"]),c=e.ucan||t._get(r,[s,"ucan"]);if(!i)throw new Error("No did audience provided");if(!c)throw new Error("No ucan provided to authentication call");return Promise.resolve(t.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};return e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),console.warn("Could not validate ucan",c,t.message),null})).then(function(e){function i(){var e=t.ucanToken(c);return a({accessToken:e},r,{authentication:a({},r.authentication,{payload:e})})}var u=function(){if(!e){var i=t.parseUcan(c),u=o.app.get("authentication"),f=t.encodeKeyPair({secretKey:u.secret});return Promise.resolve(t.buildUcan({audience:i.payload.aud,issuer:f,lifetimeInSeconds:5184e3,capabilities:i.payload.att})).then(function(e){var i;return c=e,n.admin_pass=!0,Promise.resolve(o.app.service(l).patch(t._get(r,[s,"_id"]),(i={},i[h]=t.ucanToken(c),i),a({},n))).then(function(){})})}}();return u&&u.then?u.then(i):i()})})}catch(e){return Promise.reject(e)}},n}(n.AuthenticationService),_=/*#__PURE__*/function(){function e(e,t,n){var r;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=a({},null==(r=t.params)?void 0:r.core,n)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).get(e,a({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(t=r.context.app)?void 0:t.service(r.service).find(a({},e,((n={})[i]=r.core,n))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).create(e,a({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,c=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).patch(e,t,a({},n,((i={})[c]=o.core,i))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,c=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).update(e,t,a({},n,((i={})[c]=o.core,i))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).remove(e,a({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._get(e,a({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(t=r.context.app)?void 0:t.service(r.service)._find(a({},e,((n={})[i]=r.core,n))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._create(e,a({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,c=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._patch(e,t,a({},n,((i={})[c]=o.core,i))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,c=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._update(e,t,a({},n,((i={})[c]=o.core,i))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._remove(e,a({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},e}(),b="_exists",w=function(e){var t=e.app.get("existsPath")||b;return e.params?e.params[t+"_"+e.path]:void 0},x=function(e,t){try{var n=w(e),r=function(){if(!n&&e.id)return Promise.resolve(new _(e.path,e,{skipJoins:!1!==(null==t?void 0:t.skipJoins)}).get(e.id,{admin_pass:!0})).then(function(e){n=e})}();return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},j=function(e,t){var n=e.app.get("existsPath")||b;return e.params[n+"_"+e.path]=t,e},k=["ucan"];function E(e,t,n){if(!e.s){if(n instanceof T){if(!n.s)return void(n.o=E.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(E.bind(null,e,t),E.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}const T=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{E(r,1,e(this.v))}catch(e){E(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?E(r,1,t?t(i):i):n?E(r,1,n(i)):E(r,2,i)}catch(e){E(r,2,e)}},r},e}();var A=function(e){try{var r=e.app.get("authentication"),i=t._get(e,["auth",r.entity]);return i&&(e=t._set(e,[r.core_path,r.entity],i)),Promise.resolve(n.authenticate("jwt")(e).catch(function(t){return console.error("got error in no throw auth",t),e})).then(function(t){return e=t})}catch(e){return Promise.reject(e)}},O=function(e){try{var r=e.app.get("authentication"),i=t._get(e,["auth",r.entity]);return i&&(e=t._set(e,[r.core_path,r.entity],i)),Promise.resolve(n.authenticate("jwt")(e))}catch(e){return Promise.reject(e)}},S=function(e){try{var n,r={ok:!1,value:[]},i=function(i,o,a){var c=[];for(var u in i)c.push(u);return function(e,t,n){var r,i,o=-1;return function a(c){try{for(;++o<e.length&&(!n||!n());)if((c=t(o))&&c.then){if(!((u=c)instanceof T&&1&u.s))return void c.then(a,i||(i=E.bind(null,r=new T,2)));c=c.v}r?E(r,1,c):r=c}catch(e){E(r||(r=new T),2,e)}var u}(),r}(c,function(i){return function(i){var o=function(o){if(null==(o=r)||!o.ok){var a=e[i],c=a.ucan,u=h(a,k);return Promise.resolve(function(e,n){try{return Promise.resolve(t.verifyUcan(e,n))}catch(e){return Promise.reject(e)}}(c,u)).then(function(e){r=e})}n=1}();if(o&&o.then)return o.then(function(){})}(c[i])},function(){return n})}(e);return Promise.resolve(i&&i.then?i.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},U=function(e,n,r){return function(i){try{var o,a=t._get(i.params,n.client_ucan),c=t._get(i.params,n.ucan_aud);return a&&c&&null!=r&&null!=(o=r.or)&&o.includes(i.method)?Promise.resolve(S((e||[]).map(function(e){return{ucan:a,audience:c,requiredCapabilities:[e]}}))):Promise.resolve(t.verifyUcan(a,{audience:c,requiredCapabilities:e}))}catch(e){return Promise.reject(e)}}},I=function(e,n){var r=t.encodeKeyPair({secretKey:n.secret}).did();return(e||[]).map(function(e){return{capability:Array.isArray(e)?t.genCapability({with:{scheme:n.defaultScheme,hierPart:n.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},n):t.genCapability(e,n),rootIssuer:r}})},C=function(e,n){return function(r){try{var i,o,a=function(i){if(o)return i;function a(){function i(){var e,i;if(null!=(e=o)&&e.ok)return r;var u=function(e){if(i)return e;function u(){if(o.ok)return r;throw console.error("Ucan capabilities requirements not met: ",o,r.type,r.path),new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)}var s=function(e){if(null==(e=o)||!e.ok){var i=!1,u=[];a.forEach(function(e,n){var r=(t._get(e,"capability.can.namespace")||"").split(":");r[1]&&(e=t._set(e,"capability.can.namespace",r[0]),i=!0),u.push(e)});var s=function(){if(i)return Promise.resolve(U(a,c,n)(r)).then(function(e){o=e})}();if(s&&s.then)return s.then(function(){})}}();return s&&s.then?s.then(u):u()},s=(n||{loginPass:[["*"],["nonExistentMethod"]]}).loginPass,l=function(){if(null!=s&&s.length){var e=("*"===s[1]?[r.method]:s[1].map(function(e){return e.split("/")[0]})).indexOf(r.method);return function(){if(e>-1)return Promise.resolve(x(r)).then(function(n){if(r=j(r,n),s){var a=t._flatten((s[0]||[]).map(function(e){return t._get(n,e)}).filter(function(e){return!!e}).map(function(e){return Array.isArray(e)?e:[e]})),u=t._get(r.params,[c.entity,"_id"]);if(a.map(function(e){return String(e)}).includes(String(u))){if("*"!==s[1]&&!["find","get","remove"].includes(r.method)){for(var l,f={},h=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}(e))){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[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.")}(s[1][e].split(",")||[]);!(l=h()).done;){var v=l.value,d=t._get(r.data,v);if(d)f=t._set(f,v,d);else for(var m=0,y=["$addToSet","$pull"];m<y.length;m++){var g=y[m],P=t._get(r.data,g+"."+v);P&&(f=t._set(f,g+"."+v,P))}}return r=t._set(r,"data",f),i=1,r}o.ok=!0}}})}()}}();return l&&l.then?l.then(u):u(l)}if("*"===e)return r;if(((null==n?void 0:n.adminPass)||[]).includes(r.method)&&(t._get(r.params,"admin_pass")||t._get(r.params,[c.core_path,"admin_pass"])))return r;var o={ok:!1,value:[]},a=I(e,c),u=function(){if(a.length)return Promise.resolve(U(a,c,n)(r)).then(function(e){o=e});o.ok=!0}();return u&&u.then?u.then(i):i()}var s=function(){if(!u)return Promise.resolve(O(r)).then(function(e){r=e})}();return s&&s.then?s.then(a):a()},c=r.app.get("authentication"),u=null==(i=r.params)||null==(i=i.login)?void 0:i._id,s=function(){if("$"===e){var t=function(e){return o=1,e};return u?t(r):Promise.resolve(A(r)).then(t)}}();return Promise.resolve(s&&s.then?s.then(a):a(s))}catch(e){return Promise.reject(e)}}};e.AuthService=P,e.CoreCall=_,e.NotAuthError=g,e.UcanStrategy=m,e.allUcanAuth=function(e,n){return function(r){try{var i=r.app.get("authentication"),o=t._get(r,["auth",i.entity]);if(o&&(r=t._set(r,[i.core_path,i.entity],o)),"before"===r.type){var a=r.method;return Promise.resolve(e[a]||e.all?C(e[a]||e.all,n)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},e.anyAuth="*",e.bareAuth=O,e.existsPath=b,e.getExists=w,e.loadExists=x,e.modelCapabilities=I,e.noThrow="$",e.noThrowAuth=A,e.orVerifyLoop=S,e.setExists=j,e.ucanAuth=C,e.updateUcan=function(){return function(e){try{var n=e.data,r=n.add,i=void 0===r?[]:r,o=n.remove,c=void 0===o?[]:o;if(!(null!=i&&i.length||null!=c&&c.length))throw new Error("No new capabilities passed");var u=e.app.get("authentication"),s=u.secret,l=u.ucan_aud,f=u.entity,h=u.ucan,p=t.encodeKeyPair({secretKey:s}).did(),v=t.stackAbilities([].concat(i,c));return Promise.resolve(t.verifyUcan(t._get(e.params,[f,h]),{audience:t._get(e.params,l),requiredCapabilities:v.map(function(e){return{capability:e,rootIssuer:p}})})).then(function(n){if(null==n||!n.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var r=e.id,o=e.data.service||"logins",u=e.data.path||"ucan";return Promise.resolve(new _(o,e,{skipJoins:!0}).get(r)).then(function(n){var l=t.parseUcan(t._get(n,u)).payload,f=l.aud,h=l.att,p=l.prf,v=[].concat(h);return null!=c&&c.length&&(v=t.reduceAbilities(c,h)),null!=i&&i.length&&(v=t.stackAbilities([].concat(h,i))),Promise.resolve(t.buildUcan(a({issuer:t.encodeKeyPair({secretKey:s}),audience:f,lifetimeInSeconds:5184e3,proofs:p},e.data,{capabilities:v}))).then(function(n){var i=t.ucanToken(n);return Promise.resolve(t.validateUcan(i)).then(function(t){var n;if(!t)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new _(o,e).patch(r,(n={},n[u]=i,n))).then(function(t){return e.result={raw:e.data,encoded:i,subject:t},e})})})})})}catch(e){return Promise.reject(e)}}},e.verifyAgainstReqs=U});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("symbol-ucan"),require("@feathersjs/authentication"),require("long-timeout")):"function"==typeof define&&define.amd?define(["exports","symbol-ucan","@feathersjs/authentication","long-timeout"],t):t((e||self).feathersUcan={},e.symbolUcan,e.authentication,e.longTimeout)}(this,function(e,t,n,r){function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/i(r);function a(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return a=function(e){this.s=e,this.n=e.next},a.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new a(e)}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(this,arguments)}function u(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,l(e,t)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function l(e,t){return l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},l(e,t)}function f(e,t,n){return f=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(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&l(i,n.prototype),i},f.apply(null,arguments)}function h(e){var t="function"==typeof Map?new Map:void 0;return h=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return f(e,arguments,s(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),l(n,e)},h(e)}function v(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t.indexOf(n=o[r])>=0||(i[n]=e[n]);return i}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var d=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return u(t,e),t}(/*#__PURE__*/h(Error)),m=/(\S+)\s+(\S+)/,y=/*#__PURE__*/function(e){function n(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=e.call.apply(e,[this].concat(r))||this).expirationTimers=new WeakMap,t}u(n,e);var r,i,a=n.prototype;return a.setAuthentication=function(e){e.verifyAccessToken=function(e){return{}},this.authentication=e},a.handleConnection=function(e,n,r){try{var i=this,a="logout"===e&&n.authentication&&r&&n.authentication.accessToken===r.accessToken,c=(r||{}).accessToken,u=function(){if(c&&"login"===e)return Promise.resolve(t.validateUcan(c).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){var t=1e3*(e||{payload:{exp:0}}).payload.exp-Date.now(),r=o.default.setTimeout(function(){return i.app.emit("disconnect",n)},t);o.default.clearTimeout(i.expirationTimers.get(n)),i.expirationTimers.set(n,r),n.authentication={strategy:i.name,accessToken:c}});("disconnect"===e||a)&&(delete n[i.configuration.entity],delete n.authentication,o.default.clearTimeout(i.expirationTimers.get(n)),i.expirationTimers.delete(n))}();return Promise.resolve(u&&u.then?u.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},a.verifyConfiguration=function(){for(var e=["entity","entityId","service","header","schemes","audience"],t=0,n=Object.keys(this.configuration);t<n.length;t++){var r=n[t];if(!e.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")},a.getEntityQuery=function(e){return Promise.resolve({})},a.getEntity=function(e,n){try{var r=this,i=r.entityService,o=r.configuration.entity;if(null===i)throw new d("Could not find entity service");return Promise.resolve(r.getEntityQuery(n)).then(function(r){var a=Object.assign({},t._unset(n,"provider"),{query:r});return Promise.resolve(i.get(e,a)).then(function(t){var r;return n.provider?i.get(e,c({},n,((r={})[o]=t,r))):t})})}catch(e){return Promise.reject(e)}},a.getEntityId=function(e,t){try{var n=t.query,r=t.loginId;if(r)return Promise.resolve(r);var i,o,a=this.configuration,u=a.service,s=a.core_path,l=void 0===s?"core":s,f=((i={query:c({},n,{$limit:1})})[l]=c({skipJoins:!0},t[l]),i);return Promise.resolve(null==(o=this.app)?void 0:o.service(u).find(c({},f,{skipJoins:!0}))).then(function(e){if(e.total)return e.data[0]._id;throw new d("Could not find login associated with this ucan")})}catch(e){return Promise.reject(e)}},a.authenticate=function(e,n){try{var r=this,i=e.accessToken,o=e.loginId,a=e.ucan,u=r.configuration,s=u.entity,l=u.core_path;if(!i){if(!a)throw new d("Error generating ucan");i=t.ucanToken(a)}return Promise.resolve(t.validateUcan(i).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){function a(){var e;return c({},f,((e={})[s]=u,e))}var u,f={accessToken:i,authentication:{strategy:"jwt",accessToken:i}};if(null===s)return f;var h=t._get(n,[l,s]),v=function(){if(!h)return Promise.resolve(r.getEntityId(f,c({},n,{loginId:o,query:{did:null==e?void 0:e.payload.aud}}))).then(function(e){return Promise.resolve(r.getEntity(e,n)).then(function(e){u=e})});u=h}();return v&&v.then?v.then(a):a()})}catch(e){return Promise.reject(e)}},a.parse=function(e){try{var t=this.configuration,n=t.schemes,r=e.headers&&e.headers[t.header.toLowerCase()];if(!r||"string"!=typeof r)return Promise.resolve(null);var i=r.match(m)||[],o=i[1],a=i[2],c=o&&n.some(function(e){return new RegExp(e,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:r})}catch(e){return Promise.reject(e)}},r=n,(i=[{key:"configuration",get:function(){var t,n=(null==(t=this.authentication)?void 0:t.configuration)||{service:void 0,entity:void 0,entityId:void 0};return c({service:n.service,entity:n.entity,entityId:n.entityId,header:"Authorization",schemes:["Bearer","JWT"]},e.prototype.configuration)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,"symbol"==typeof(i=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(r.key))?i:String(i),r)}var i}(r.prototype,i),Object.defineProperty(r,"prototype",{writable:!1}),n}(n.AuthenticationBaseStrategy),g=["NotAuthenticated"],P=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return u(t,e),t}(/*#__PURE__*/h(Error)),b=/*#__PURE__*/function(e){function n(t,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=v(r,g);return(i=e.call(this,t,n,a)||this).options=void 0,i.app=t,i.options={NotAuthenticated:o},i}return u(n,e),n.prototype.create=function(e,n){try{var r,i,o=this,a=(null==(r=o.options)?void 0:r.NotAuthenticated)||P,u=o.app.get("authentication"),s=u.entity,l=u.service,f=u.ucan_path,h=void 0===f?"ucan":f,v=(null==(i=n)?void 0:i.authStrategies)||o.configuration.authStrategies;if(n||(n={}),!v.length)throw new a("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(o.authenticate.apply(o,[e,n].concat(v)).catch(function(e){throw new Error(e.message)})).then(function(r){if(r.accessToken)return r;var i=e.did||t._get(r,[s,"did"]),a=e.ucan||t._get(r,[s,"ucan"]);if(!i)throw new Error("No did audience provided");if(!a)throw new Error("No ucan provided to authentication call");return Promise.resolve(t.validateUcan(a).catch(function(e){console.log("Could not validate ucan: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};return e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),console.warn("Could not validate ucan",a,t.message),null})).then(function(e){function i(){var e=t.ucanToken(a);return c({accessToken:e},r,{authentication:c({},r.authentication,{payload:e})})}var u=function(){if(!e){var i=t.parseUcan(a),u=o.app.get("authentication"),f=t.encodeKeyPair({secretKey:u.secret});return Promise.resolve(t.buildUcan({audience:i.payload.aud,issuer:f,lifetimeInSeconds:5184e3,capabilities:i.payload.att})).then(function(e){var i;return a=e,n.admin_pass=!0,Promise.resolve(o.app.service(l).patch(t._get(r,[s,"_id"]),(i={},i[h]=t.ucanToken(a),i),c({},n))).then(function(){})})}}();return u&&u.then?u.then(i):i()})})}catch(e){return Promise.reject(e)}},n}(n.AuthenticationService),_=/*#__PURE__*/function(){function e(e,t,n){var r;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=c({},null==(r=t.params)?void 0:r.core,n)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).get(e,c({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(t=r.context.app)?void 0:t.service(r.service).find(c({},e,((n={})[i]=r.core,n))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).create(e,c({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).patch(e,t,c({},n,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).update(e,t,c({},n,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).remove(e,c({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._get(e,c({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,n,r=this,i=r.context.app.get("authentication").core_path;return Promise.resolve(null==(t=r.context.app)?void 0:t.service(r.service)._find(c({},e,((n={})[i]=r.core,n))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._create(e,c({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._patch(e,t,c({},n,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,n){void 0===n&&(n={});try{var r,i,o=this,a=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._update(e,t,c({},n,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var n,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._remove(e,c({},t,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},e}(),w="_exists",x=function(e){var n=e.app.get("existsPath")||w;return t._get(e.params,n+"."+e.path+"."+e.id)||void 0},j=function(e,t){try{var n=x(e),r=function(){if(!n&&e.id)return Promise.resolve(new _(e.path,e,{skipJoins:!1!==(null==t?void 0:t.skipJoins)}).get(e.id,{admin_pass:!0})).then(function(e){n=e})}();return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},k=function(e,n){var r=e.app.get("existsPath")||w;return e.params=t._set(e.params,r+"."+e.path+"."+(n._id||e.id),n),e},E=["ucan"];function T(e,t,n){if(!e.s){if(n instanceof O){if(!n.s)return void(n.o=T.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(T.bind(null,e,t),T.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}const O=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{T(r,1,e(this.v))}catch(e){T(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?T(r,1,t?t(i):i):n?T(r,1,n(i)):T(r,2,i)}catch(e){T(r,2,e)}},r},e}();function A(e){return e instanceof O&&1&e.s}function S(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var U=function(e){try{var r=e.app.get("authentication"),i=t._get(e,["auth",r.entity]);return i&&(e=t._set(e,[r.core_path,r.entity],i)),Promise.resolve(n.authenticate("jwt")(e).catch(function(t){return console.error("got error in no throw auth",t),e})).then(function(t){return e=t})}catch(e){return Promise.reject(e)}},I=function(e){try{var r=e.app.get("authentication"),i=t._get(e,["auth",r.entity]);return i&&(e=t._set(e,[r.core_path,r.entity],i)),Promise.resolve(n.authenticate("jwt")(e))}catch(e){return Promise.reject(e)}},C=function(e){try{var n,r={ok:!1,value:[]},i=function(i,o,a){var c=[];for(var u in i)c.push(u);return function(e,t,n){var r,i,o=-1;return function a(c){try{for(;++o<e.length&&(!n||!n());)if((c=t(o))&&c.then){if(!A(c))return void c.then(a,i||(i=T.bind(null,r=new O,2)));c=c.v}r?T(r,1,c):r=c}catch(e){T(r||(r=new O),2,e)}}(),r}(c,function(i){return function(i){var o=function(o){if(null==(o=r)||!o.ok){var a=e[i],c=a.ucan,u=v(a,E);return Promise.resolve(function(e,n){try{return Promise.resolve(t.verifyUcan(e,n))}catch(e){return Promise.reject(e)}}(c,u)).then(function(e){r=e})}n=1}();if(o&&o.then)return o.then(function(){})}(c[i])},function(){return n})}(e);return Promise.resolve(i&&i.then?i.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},q=function(e,n,r){return function(i){try{var o,a=t._get(i.params,n.client_ucan),c=t._get(i.params,n.ucan_aud);return a&&c&&null!=r&&null!=(o=r.or)&&o.includes(i.method)?Promise.resolve(C((e||[]).map(function(e){return{ucan:a,audience:c,requiredCapabilities:[e]}}))):Promise.resolve(t.verifyUcan(a,{audience:c,requiredCapabilities:e}))}catch(e){return Promise.reject(e)}}},N=function(e,n){var r=t.encodeKeyPair({secretKey:n.secret}).did();return(e||[]).map(function(e){return{capability:Array.isArray(e)?t.genCapability({with:{scheme:n.defaultScheme,hierPart:n.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},n):t.genCapability(e,n),rootIssuer:r}})},K=function(e,n){return function(r){try{var i,o,c=function(i){if(o)return i;function c(){function i(){var e;if(null!=(e=o)&&e.ok)return r;var i=function(e){function i(){if(o.ok)return r;throw console.error("Ucan capabilities requirements not met: ",o,r.type,r.path),new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)}var a=function(e){if(null==(e=o)||!e.ok){var i=!1,a=[];c.forEach(function(e,n){var r=(t._get(e,"capability.can.namespace")||"").split(":");r[1]&&(e=t._set(e,"capability.can.namespace",r[0]),i=!0),a.push(e)});var s=function(){if(i)return Promise.resolve(q(c,u,n)(r)).then(function(e){o=e})}();if(s&&s.then)return s.then(function(){})}}();return a&&a.then?a.then(i):i()},s=(n||{loginPass:[[["*"],["nonExistentMethod"]]]}).loginPass,l=function(){if(null!=s&&s.length){var e,n=function(e){if(_interrupt2)return e;c&&(r=t._set(r,"data",i))},i={},c=!0,l=!1,f=!1,h=S(function(){return function(e,n){try{var f=function(){var e,n,f=function(e){var t,n,r,i=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&null!=(t=e[n]))return t.call(e);if(r&&null!=(t=e[r]))return new a(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(s),h=function(e,t,n){for(var r;;){var i=e();if(A(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!A(o)){r=1;break}o=o.s}if(t){var a=t();if(a&&a.then&&!A(a)){r=2;break}}}var c=new O,u=T.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(t&&(a=t())&&a.then&&!A(a))return void a.then(f).then(void 0,u);if(!(i=e())||A(i)&&!i.v)return void T(c,1,o);if(i.then)return void i.then(l).then(void 0,u);A(o=n())&&(o=o.v)}while(!o||!o.then);o.then(s).then(void 0,u)}function l(e){e?(o=n())&&o.then?o.then(s).then(void 0,u):s(o):T(c,1,o)}function f(){(i=e())?i.then?i.then(l).then(void 0,u):l(i):T(c,1,o)}}(function(){function t(t){return!e&&(l=!(n=t).done)}return e?!!t(!e&&f.next()):Promise.resolve(!e&&f.next()).then(t)},function(){return!!(l=!1)},function(){var a=n.value,s=function(){if(c)return Promise.resolve(function(e){try{var n=[],a="*"===e[1],s=-1;a?s=0:(n=e[1].map(function(e){return e.split("/")[0]}),s=n.indexOf(r.method));var l=function(){if(s>-1)return Promise.resolve(j(r)).then(function(n){r=k(r,n);var l=t._flatten((e[0]||[]).map(function(e){return t._get(n,e)}).filter(function(e){return!!e}).map(function(e){return Array.isArray(e)?e:[e]})),f=t._get(r.params,[u.entity,"_id"]);if(l.map(function(e){return String(e)}).includes(String(f)))if(o.ok=!0,"*"===e[1]||["find","get","remove"].some(function(t){return e[1].includes(t)}))c=!1;else{var h=a?"*":e[1][s];if(h.split("/")[0]!==h)for(var v,d=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}(e))){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[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.")}(h.split("/").slice(1).join("").split(",")||[]);!(v=d()).done;){var m=v.value,y=t._get(r.data,m);if(y)i=t._set(i,m,y);else for(var g=0,P=["$addToSet","$pull"];g<P.length;g++){var b=P[g],_=t._get(r.data,b+"."+m);_&&(i=t._set(i,b+"."+m,_))}}else c=!1}})}();return Promise.resolve(l&&l.then?l.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}(a)).then(function(){});e=1}();return s&&s.then?s.then(function(){}):void 0});if(h&&h.then)return h.then(function(){})}()}catch(e){return n(e)}return f&&f.then?f.then(void 0,n):f}(0,function(t){f=!0,e=t})},function(t,n){function r(e){if(t)throw n;return n}var i=S(function(){var e=function(){if(l&&null!=_iterator.return)return Promise.resolve(_iterator.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(t,n){if(f)throw e;if(t)throw n;return n});return i&&i.then?i.then(r):r()});return h&&h.then?h.then(n):n(h)}}();return l&&l.then?l.then(i):i()}if("*"===e)return r;if(((null==n?void 0:n.adminPass)||[]).includes(r.method)&&(t._get(r.params,"admin_pass")||t._get(r.params,[u.core_path,"admin_pass"])))return r;var o={ok:!1,value:[]},c=N(e,u),s=function(){if(c.length)return Promise.resolve(q(c,u,n)(r)).then(function(e){o=e});o.ok=!0}();return s&&s.then?s.then(i):i()}var l=function(){if(!s)return Promise.resolve(I(r)).then(function(e){r=e})}();return l&&l.then?l.then(c):c()},u=r.app.get("authentication"),s=null==(i=r.params)||null==(i=i.login)?void 0:i._id,l=function(){if("$"===e){var t=function(e){return o=1,e};return s?t(r):Promise.resolve(U(r)).then(t)}}();return Promise.resolve(l&&l.then?l.then(c):c(l))}catch(e){return Promise.reject(e)}}};e.AuthService=b,e.CoreCall=_,e.NotAuthError=P,e.UcanStrategy=y,e.allUcanAuth=function(e,n){return function(r){try{var i=r.app.get("authentication"),o=t._get(r,["auth",i.entity]);if(o&&(r=t._set(r,[i.core_path,i.entity],o)),"before"===r.type){var a=r.method;return Promise.resolve(e[a]||e.all?K(e[a]||e.all,n)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},e.anyAuth="*",e.bareAuth=I,e.existsPath=w,e.getExists=x,e.loadExists=j,e.modelCapabilities=N,e.noThrow="$",e.noThrowAuth=U,e.orVerifyLoop=C,e.setExists=k,e.ucanAuth=K,e.updateUcan=function(){return function(e){try{var n=e.data,r=n.add,i=void 0===r?[]:r,o=n.remove,a=void 0===o?[]:o;if(!(null!=i&&i.length||null!=a&&a.length))throw new Error("No new capabilities passed");var u=e.app.get("authentication"),s=u.secret,l=u.ucan_aud,f=u.entity,h=u.ucan,v=t.encodeKeyPair({secretKey:s}).did(),p=t.stackAbilities([].concat(i,a));return Promise.resolve(t.verifyUcan(t._get(e.params,[f,h]),{audience:t._get(e.params,l),requiredCapabilities:p.map(function(e){return{capability:e,rootIssuer:v}})})).then(function(n){if(null==n||!n.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var r=e.id,o=e.data.service||"logins",u=e.data.path||"ucan";return Promise.resolve(new _(o,e,{skipJoins:!0}).get(r)).then(function(n){var l=t.parseUcan(t._get(n,u)).payload,f=l.aud,h=l.att,v=l.prf,p=[].concat(h);return null!=a&&a.length&&(p=t.reduceAbilities(a,h)),null!=i&&i.length&&(p=t.stackAbilities([].concat(h,i))),Promise.resolve(t.buildUcan(c({issuer:t.encodeKeyPair({secretKey:s}),audience:f,lifetimeInSeconds:5184e3,proofs:v},e.data,{capabilities:p}))).then(function(n){var i=t.ucanToken(n);return Promise.resolve(t.validateUcan(i)).then(function(t){var n;if(!t)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new _(o,e).patch(r,(n={},n[u]=i,n))).then(function(t){return e.result={raw:e.data,encoded:i,subject:t},e})})})})})}catch(e){return Promise.reject(e)}}},e.verifyAgainstReqs=q});
@@ -1,5 +1,5 @@
1
- export declare const existsPath = "_exists";
2
1
  import { HookContext } from '../types';
2
+ export declare const existsPath = "_exists";
3
3
  export declare const getExists: (context: Partial<HookContext>) => any;
4
4
  export declare const loadExists: (context: HookContext, options?: {
5
5
  skipJoins: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feathers-ucan",
3
- "version": "0.0.34",
3
+ "version": "0.0.36",
4
4
  "description": "Ucan extension of feathers jwt auth",
5
5
  "source": "src/index.ts",
6
6
  "unpkg": "lib/index.umd.js",