feathers-ucan 0.0.2 → 0.0.4

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
@@ -75,6 +75,7 @@ Also worth noting is that we expose a `CoreCall` class that allows you to make f
75
75
  "defaultHierPart": "commoncare/*",
76
76
  "core_path": "core",
77
77
  "ucan_path": "ucan",
78
+ "ucan_aud": "core.ucan_aud",
78
79
  "client_ucan": "core.client_ucan",
79
80
  ...
80
81
  }
@@ -103,7 +104,7 @@ const methods = {
103
104
 
104
105
  ******************noThrow:****************** is even looser - because it will not throw an error if the auth fails. It is just useful for having the `login._id` present in the `context.params`
105
106
 
106
- Note: the way ucans works, you cannot simply provide a “greatest ability” and have the verify method filter out lesser abilities. In other words, if you have `WRITE` segment, you’d expect that to be valid for a `READ` requirement. However, ucans is less opinionated than that. You need to reduce the ability yourself, or it will not verify even if you have a greater ability. We have greatest ability functions, but currently the `allUcanAuth` method does not use it. Add only the greatest ability you wish to enforce. The client for adding ucans to users does this already, so only custom scenarios should present a problem at this time. In the future, we will always reduce abilities for the greatest ability.
107
+ Note: the way ucans works, you cannot simply provide a “greatest ability” and have the verify method filter out lesser abilities. In other words, if you have `WRITE` segment, you’d expect that to be valid for a `READ` requirement. However, ucans is less opinionated than that. You need to reduce the ability yourself, or it will not verify even if you have a greater ability. We have greatest ability functions, but currently the `allUcanAuth` method does not use it. Add only the greatest ability you wish to enforce. The UI we use for adding ucans to users does this already, so only custom scenarios should present a problem at this time. In the future, we will always reduce abilities for the greatest ability.
107
108
 
108
109
  ## Options
109
110
 
@@ -118,6 +119,7 @@ declare type UcanAuthOptions = {
118
119
  }
119
120
  ```
120
121
 
122
+ ### This section needs to be reworked to be open-sourcable. This is too specific to our internal material still
121
123
  - **************************creatorPass:************************** allows for a pass if the `login._id` calling the method is the same as the record in question `record.createdBy.login`
122
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.
123
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.
@@ -160,7 +162,7 @@ Then the config is used in a before all hook like this
160
162
 
161
163
  ```jsx
162
164
  const authenticate = async (context:HookContext):Promise<HookContext> => {
163
- return await allUcanAuth(ucanArgs(context), {or: ['patch'], admin: ['remove'] }})(context);
165
+ return await allUcanAuth(ucanArgs(context), {or: ['patch'], adminPass: ['remove'] }})(context);
164
166
  }
165
167
 
166
168
  ...
@@ -1,14 +1,14 @@
1
- import { AuthenticationRequest, AuthenticationParams } from '../types';
1
+ import { AuthenticationService, AuthenticationRequest, AuthenticationParams } from '@feathersjs/authentication';
2
+ import { AnyObj } from '../types';
2
3
  export declare class NotAuthError extends Error {
3
4
  constructor(message?: string);
4
5
  }
5
6
  export type AuthServiceOptions = {
6
7
  NotAuthenticated?: any;
7
8
  };
8
- export declare const genAuthService: (ParentClass: any, options?: AuthServiceOptions) => {
9
- new (app: any, configKey?: string, opts?: {}): {
10
- [x: string]: any;
11
- create(data: AuthenticationRequest, params?: AuthenticationParams): Promise<any>;
12
- };
13
- [x: string]: any;
14
- };
9
+ export * from './ucan-strategy';
10
+ export declare class AuthService extends AuthenticationService {
11
+ options: AuthServiceOptions;
12
+ constructor(app: any, configKey?: string, opts?: AnyObj & AuthServiceOptions);
13
+ create(data: AuthenticationRequest, params?: AuthenticationParams): Promise<import("@feathersjs/authentication").AuthenticationResult>;
14
+ }
@@ -0,0 +1,36 @@
1
+ /// <reference types="node" />
2
+ import { IncomingMessage } from 'http';
3
+ import { AuthenticationBaseStrategy, ConnectionEvent, AuthenticationResult, AuthenticationBase, AuthenticationRequest } from '@feathersjs/authentication';
4
+ export declare class NotAuthError extends Error {
5
+ constructor(message?: string);
6
+ }
7
+ type AnyObj = {
8
+ [key: string]: any;
9
+ };
10
+ export declare class UcanStrategy extends AuthenticationBaseStrategy {
11
+ expirationTimers: WeakMap<object, any>;
12
+ setAuthentication(auth: AuthenticationBase): void;
13
+ get configuration(): any;
14
+ handleConnection(event: ConnectionEvent, connection: any, authResult?: AuthenticationResult): Promise<void>;
15
+ verifyConfiguration(): void;
16
+ getEntityQuery(_params: any): Promise<{}>;
17
+ /**
18
+ * Return the entity for a given id
19
+ * @param id The id to use
20
+ * @param params Service call parameters
21
+ */
22
+ getEntity(id: string, params: any): Promise<any>;
23
+ getEntityId(authResult: AuthenticationResult, _params: AnyObj): Promise<any>;
24
+ authenticate(authentication: AuthenticationRequest, params: AnyObj): Promise<{
25
+ accessToken: any;
26
+ authentication: {
27
+ strategy: string;
28
+ accessToken: any;
29
+ };
30
+ }>;
31
+ parse(req: IncomingMessage): Promise<{
32
+ strategy: string | undefined;
33
+ accessToken: string;
34
+ } | null>;
35
+ }
36
+ export {};
@@ -1 +1 @@
1
- export declare const VERSION = "0.0.2";
1
+ export declare const VERSION = "0.0.4";
package/lib/index.cjs CHANGED
@@ -1 +1 @@
1
- var e=require("symbol-ucan"),t=require("@feathersjs/authentication");function r(){return r=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},r.apply(this,arguments)}function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,i(e,t)}function o(e){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},o(e)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function a(e,t,r){return a=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 o=new(Function.bind.apply(e,n));return r&&i(o,r.prototype),o},a.apply(null,arguments)}function c(e){var t="function"==typeof Map?new Map:void 0;return c=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))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 a(e,arguments,o(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),i(r,e)},c(e)}var u=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return n(t,e),t}(/*#__PURE__*/c(Error)),s=/*#__PURE__*/function(){function e(e,t,n){var o;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=r({},null==(o=t.params)?void 0:o.core,n)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var n,o,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,r({},t,((o={})[a]=i.core,o))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,n,o=this,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(t=o.context.app)?void 0:t.service(o.service).find(r({},e,((n={})[i]=o.core,n))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var n,o,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,r({},t,((o={})[a]=i.core,o))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,n){void 0===n&&(n={});try{var o,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(o=a.context.app)?void 0:o.service(a.service).patch(e,t,r({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,n){void 0===n&&(n={});try{var o,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(o=a.context.app)?void 0:o.service(a.service).update(e,t,r({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var n,o,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,r({},t,((o={})[a]=i.core,o))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var n,o,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,r({},t,((o={})[a]=i.core,o))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,n,o=this,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(t=o.context.app)?void 0:t.service(o.service)._find(r({},e,((n={})[i]=o.core,n))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var n,o,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,r({},t,((o={})[a]=i.core,o))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,n){void 0===n&&(n={});try{var o,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(o=a.context.app)?void 0:o.service(a.service)._patch(e,t,r({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,n){void 0===n&&(n={});try{var o,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(o=a.context.app)?void 0:o.service(a.service)._update(e,t,r({},n,((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var n,o,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,r({},t,((o={})[a]=i.core,o))))}catch(e){return Promise.reject(e)}},e}(),l=["ucan"];function p(e,t,r){if(!e.s){if(r instanceof h){if(!r.s)return void(r.o=p.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(p.bind(null,e,t),p.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}const h=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,r){const n=new e,o=this.s;if(o){const e=1&o?t:r;if(e){try{p(n,1,e(this.v))}catch(e){p(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?p(n,1,t?t(o):o):r?p(n,1,r(o)):p(n,2,o)}catch(e){p(n,2,e)}},n},e}();var v=function(r){try{var n=r.app.get("authentication"),o=e._get(r,["auth",n.entity]);return o&&(r=e._set(r,[n.core_path,n.entity],o)),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)}},f=function(r){try{var n=r.app.get("authentication"),o=e._get(r,["auth",n.entity]);return o&&(r=e._set(r,[n.core_path,n.entity],o)),Promise.resolve(t.authenticate("jwt")(r))}catch(e){return Promise.reject(e)}},d=function(t){try{var r,n={ok:!1,value:[]},o=function(o,i,a){var c=[];for(var u in o)c.push(u);return function(e,t,r){var n,o,i=-1;return function a(c){try{for(;++i<e.length&&(!r||!r());)if((c=t(i))&&c.then){if(!((u=c)instanceof h&&1&u.s))return void c.then(a,o||(o=p.bind(null,n=new h,2)));c=c.v}n?p(n,1,c):n=c}catch(e){p(n||(n=new h),2,e)}var u}(),n}(c,function(o){return function(o){var i=function(){var i;if(null==(i=n)||!i.ok){var a=t[o],c=a.ucan,u=function(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)t.indexOf(r=i[n])>=0||(o[r]=e[r]);return o}(a,l);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(i&&i.then)return i.then(function(){})}(c[o])},function(){return r})}(t);return Promise.resolve(o&&o.then?o.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},m=function(t,r,n,o){return function(i){try{var a;return t&&r&&null!=o&&null!=(a=o.or)&&a.includes(i.method)?Promise.resolve(d((n||[]).map(function(e){return{ucan:t,audience:r,requiredCapabilities:[e]}}))):Promise.resolve(e.verifyUcan(t,{audience:r,requiredCapabilities:n}))}catch(e){return Promise.reject(e)}}},y=function(t,r){return function(n){try{var o,i=function(i){return o?i:Promise.resolve(f(n)).then(function(o){var i;if(n=o,"*"===t)return n;if(null!=r&&r.adminPass&&n.params.admin_pass)return n;var a=n.app.get("authentication"),c={ok:!1,value:[]},u=e.encodeKeyPair({secretKey:a.secret}).did(),l=n.app.get("authentication"),p=(t||[]).map(function(t){var r={defaultScheme:l.defaultScheme,defaultHierPart:l.defaultHierPart};return{capability:Array.isArray(t)?e.genCapability({with:{scheme:l.defaultScheme,hierPart:l.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},r):e.genCapability(t,r),rootIssuer:u}}),h=e._get(n.params,l.client_ucan),v=e._get(n.params,l.ucan_aud);if(p.length?c=m(h,v,p,r):c.ok=!0,null!=(i=c)&&i.ok)return n;var f=function(){var t;if(null==(t=c)||!t.ok){var o=!1,i=[];p.forEach(function(t,r){var n=(e._get(t,"capability.can.namespace")||"").split(":");n[1]&&(t=e._set(t,"capability.can.namespace",n[0]),o=!0),i.push(t)}),o&&(c=m(h,v,p,r))}if(c.ok)return n;throw console.error("Ucan capabilities requirements not met: ",c,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)},d=r||{creatorPass:!1},y=d.creatorPass,g=d.loginPass,P=function(){if(y&&("*"===y||y.includes(n.method))||null!=g&&g.length&&("*"===g[1]||g[1].includes(n.method)))return Promise.resolve(new s(n.path,n,{skipJoins:!0}).get(n.id)).then(function(t){var r,o;if(y)c.ok=(null==t||null==(r=t.createdBy)?void 0:r.login)===((null==(o=n.login)?void 0:o._id)||"***");else if(g){var i,a=e._flatten(g[0].map(function(r){return e._get(t,r)}));c.ok=a.filter(function(e){return!!e}).includes(null==(i=n.login)?void 0:i._id)}})}();return P&&P.then?P.then(f):f()})},a=function(){if("$"===t)return Promise.resolve(v(n)).then(function(e){return o=1,e})}();return Promise.resolve(a&&a.then?a.then(i):i(a))}catch(e){return Promise.reject(e)}}};exports.CoreCall=s,exports.NotAuthError=u,exports.allUcanAuth=function(t,r){return function(n){try{var o=n.app.get("authentication"),i=n.auth[o.entity];if(i&&(n=e._set(n,[o.core_path,o.entity],i)),"before"===n.type){var a=n.method;return Promise.resolve(t[a]||t.all?y(t[a]||t.all,r)(n):n)}return Promise.resolve(n)}catch(e){return Promise.reject(e)}}},exports.anyAuth="*",exports.bareAuth=f,exports.genAuthService=function(t,o){/*#__PURE__*/return function(t){function i(e,r,n){var o;return void 0===r&&(r="authentication"),void 0===n&&(n={}),(o=t.call(this,e,r,n)||this).app=e,o}return n(i,t),i.prototype.create=function(t,n){try{var i,a=this,c=(null==o?void 0:o.NotAuthenticated)||u,s=a.app.get("authentication"),l=s.entity,p=s.service,h=s.ucan_path,v=void 0===h?"ucan":h,f=(null==(i=n)?void 0:i.authStrategies)||a.configuration.authStrategies;if(n||(n={}),!f.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(a.authenticate.apply(a,[t,n].concat(f)).catch(function(e){throw new Error(e.message)})).then(function(o){if(o.accessToken)return o;var i=t.did||e._get(o,[l,"did"]),c=t.ucan||e._get(o,[l,"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 r({accessToken:t},o,{authentication:r({},o.authentication,{payload:t})})}var u=function(){if(!t){var i=e.parseUcan(c),u=a.app.get("authentication"),s=e.encodeKeyPair({secretKey:u.secret});return Promise.resolve(e.buildUcan({audience:i.payload.aud,issuer:s,capabilities:i.payload.att})).then(function(t){var i;return c=t,n.admin_pass=!0,Promise.resolve(a.app.service(p).patch(o[l]._id,(i={},i[v]=e.ucanToken(c),i),r({},n))).then(function(){})})}}();return u&&u.then?u.then(i):i()})})}catch(e){return Promise.reject(e)}},i}(t)},exports.noThrow="$",exports.noThrowAuth=v,exports.orVerifyLoop=d,exports.ucanAuth=y,exports.updateUcan=function(){return function(t){try{var n=t.data,o=n.add,i=void 0===o?[]:o,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"),l=u.secret,p=u.ucan_aud,h=e.encodeKeyPair({secretKey:l}).did(),v=e.stackAbilities([].concat(i,c));return Promise.resolve(e.verifyUcan(t.params.login.ucan,{audience:e._get(t.params,p),requiredCapabilities:v.map(function(e){return{capability:e,rootIssuer:h}})})).then(function(n){if(null==n||!n.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var o=t.id,a=t.data.service||"logins",u=t.data.path||"ucan";return Promise.resolve(new s(a,t,{skipJoins:!0}).get(o)).then(function(n){var p=e.parseUcan(e._get(n,u)).payload,h=p.aud,v=p.att,f=p.prf,d=[].concat(v);return null!=c&&c.length&&(d=e.reduceAbilities(c,v)),null!=i&&i.length&&(d=e.stackAbilities([].concat(v,i))),Promise.resolve(e.buildUcan(r({issuer:e.encodeKeyPair({secretKey:l}),audience:h,proofs:f},t.data,{capabilities:d}))).then(function(r){var n=e.ucanToken(r);return Promise.resolve(e.validateUcan(n)).then(function(e){var r;if(!e)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new s(a,t).patch(o,(r={},r[u]=n,r))).then(function(e){return t.result={raw:t.data,encoded:n,subject:e},t})})})})})}catch(e){return Promise.reject(e)}}},exports.verifyAgainstReqs=m;
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}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+)/,f=/*#__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,p=((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(p)).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({},h,((e={})[s]=u,e))}var u,h={accessToken:o,authentication:{strategy:"jwt",accessToken:o}};if(null===s)return h;var p=e._get(r,[l,s]),f=function(){if(!p)return Promise.resolve(n.getEntityId(h,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=p}();return f&&f.then?f.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),v=["NotAuthenticated"],d=/*#__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,v);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)||d,u=a.app.get("authentication"),s=u.entity,l=u.service,h=u.ucan_path,p=void 0===h?"ucan":h,f=(null==(o=r)?void 0:o.authStrategies)||a.configuration.authStrategies;if(r||(r={}),!f.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(a.authenticate.apply(a,[t,r].concat(f)).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"),h=e.encodeKeyPair({secretKey:u.secret});return Promise.resolve(e.buildUcan({audience:o.payload.aud,issuer:h,capabilities:o.payload.att})).then(function(t){var o;return c=t,r.admin_pass=!0,Promise.resolve(a.app.service(l).patch(n[s]._id,(o={},o[p]=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),m=/*#__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}(),g=["ucan"];function P(e,t,r){if(!e.s){if(r instanceof w){if(!r.s)return void(r.o=P.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(P.bind(null,e,t),P.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}const w=/*#__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{P(n,1,e(this.v))}catch(e){P(n,2,e)}return n}return this}return this.o=function(e){try{const i=e.v;1&e.s?P(n,1,t?t(i):i):r?P(n,1,r(i)):P(n,2,i)}catch(e){P(n,2,e)}},n},e}();var b=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)}},_=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)}},x=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 w&&1&u.s))return void c.then(a,i||(i=P.bind(null,n=new w,2)));c=c.v}n?P(n,1,c):n=c}catch(e){P(n||(n=new w),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,g);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)}},j=function(t,r,n,i){return function(o){try{var a;return t&&r&&null!=i&&null!=(a=i.or)&&a.includes(o.method)?Promise.resolve(x((n||[]).map(function(e){return{ucan:t,audience:r,requiredCapabilities:[e]}}))):Promise.resolve(e.verifyUcan(t,{audience:r,requiredCapabilities:n}))}catch(e){return Promise.reject(e)}}},k=function(t,r){return function(n){try{var i,o=function(o){return i?o:Promise.resolve(_(n)).then(function(i){var o;if(n=i,"*"===t)return n;if(null!=r&&r.adminPass&&n.params.admin_pass)return n;var a=n.app.get("authentication"),c={ok:!1,value:[]},u=e.encodeKeyPair({secretKey:a.secret}).did(),s=n.app.get("authentication"),l=(t||[]).map(function(t){var r={defaultScheme:s.defaultScheme,defaultHierPart:s.defaultHierPart};return{capability:Array.isArray(t)?e.genCapability({with:{scheme:s.defaultScheme,hierPart:s.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},r):e.genCapability(t,r),rootIssuer:u}}),h=e._get(n.params,s.client_ucan),p=e._get(n.params,s.ucan_aud);if(l.length?c=j(h,p,l,r):c.ok=!0,null!=(o=c)&&o.ok)return n;var f=function(){var t;if(null==(t=c)||!t.ok){var i=!1,o=[];l.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),o.push(t)}),i&&(c=j(h,p,l,r))}if(c.ok)return n;throw console.error("Ucan capabilities requirements not met: ",c,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)},v=r||{creatorPass:!1},d=v.creatorPass,y=v.loginPass,g=function(){if(d&&("*"===d||d.includes(n.method))||null!=y&&y.length&&("*"===y[1]||y[1].includes(n.method)))return Promise.resolve(new m(n.path,n,{skipJoins:!0}).get(n.id)).then(function(t){var r,i;if(d)c.ok=(null==t||null==(r=t.createdBy)?void 0:r.login)===((null==(i=n.login)?void 0:i._id)||"***");else if(y){var o,a=e._flatten(y[0].map(function(r){return e._get(t,r)}));c.ok=a.filter(function(e){return!!e}).includes(null==(o=n.login)?void 0:o._id)}})}();return g&&g.then?g.then(f):f()})},a=function(){if("$"===t)return Promise.resolve(b(n)).then(function(e){return i=1,e})}();return Promise.resolve(a&&a.then?a.then(o):o(a))}catch(e){return Promise.reject(e)}}};exports.AuthService=y,exports.CoreCall=m,exports.NotAuthError=d,exports.UcanStrategy=f,exports.allUcanAuth=function(t,r){return function(n){try{var i=n.app.get("authentication"),o=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?k(t[a]||t.all,r)(n):n)}return Promise.resolve(n)}catch(e){return Promise.reject(e)}}},exports.anyAuth="*",exports.bareAuth=_,exports.noThrow="$",exports.noThrowAuth=b,exports.orVerifyLoop=x,exports.ucanAuth=k,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,h=e.encodeKeyPair({secretKey:s}).did(),p=e.stackAbilities([].concat(o,c));return Promise.resolve(e.verifyUcan(t.params.login.ucan,{audience:e._get(t.params,l),requiredCapabilities:p.map(function(e){return{capability:e,rootIssuer:h}})})).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 m(a,t,{skipJoins:!0}).get(n)).then(function(r){var l=e.parseUcan(e._get(r,u)).payload,h=l.aud,p=l.att,f=l.prf,v=[].concat(p);return null!=c&&c.length&&(v=e.reduceAbilities(c,p)),null!=o&&o.length&&(v=e.stackAbilities([].concat(p,o))),Promise.resolve(e.buildUcan(i({issuer:e.encodeKeyPair({secretKey:s}),audience:h,proofs:f},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 m(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=j;
package/lib/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{_get as e,validateUcan as t,ucanToken as r,parseUcan as n,encodeKeyPair as o,buildUcan as i,_set as c,verifyUcan as a,genCapability as u,_flatten as s,stackAbilities as l,reduceAbilities as p}from"symbol-ucan";import{authenticate as h}from"@feathersjs/authentication";function v(){return v=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},v.apply(this,arguments)}function f(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,m(e,t)}function d(e){return d=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},d(e)}function m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}function y(e,t,r){return y=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 o=new(Function.bind.apply(e,n));return r&&m(o,r.prototype),o},y.apply(null,arguments)}function g(e){var t="function"==typeof Map?new Map:void 0;return g=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))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 y(e,arguments,d(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),m(r,e)},g(e)}var P=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return f(t,e),t}(/*#__PURE__*/g(Error)),_=function(c,a){/*#__PURE__*/return function(c){function u(e,t,r){var n;return void 0===t&&(t="authentication"),void 0===r&&(r={}),(n=c.call(this,e,t,r)||this).app=e,n}return f(u,c),u.prototype.create=function(c,u){try{var s,l=this,p=(null==a?void 0:a.NotAuthenticated)||P,h=l.app.get("authentication"),f=h.entity,d=h.service,m=h.ucan_path,y=void 0===m?"ucan":m,g=(null==(s=u)?void 0:s.authStrategies)||l.configuration.authStrategies;if(u||(u={}),!g.length)throw new p("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(l.authenticate.apply(l,[c,u].concat(g)).catch(function(e){throw new Error(e.message)})).then(function(a){if(a.accessToken)return a;var s=c.did||e(a,[f,"did"]),p=c.ucan||e(a,[f,"ucan"]);if(!s)throw new Error("No did audience provided");if(!p)throw new Error("No ucan provided to authentication call");return Promise.resolve(t(p).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",p,t.message),null})).then(function(e){function t(){var e=r(p);return v({accessToken:e},a,{authentication:v({},a.authentication,{payload:e})})}var c=function(){if(!e){var t=n(p),c=l.app.get("authentication"),s=o({secretKey:c.secret});return Promise.resolve(i({audience:t.payload.aud,issuer:s,capabilities:t.payload.att})).then(function(e){var t;return p=e,u.admin_pass=!0,Promise.resolve(l.app.service(d).patch(a[f]._id,(t={},t[y]=r(p),t),v({},u))).then(function(){})})}}();return c&&c.then?c.then(t):t()})})}catch(e){return Promise.reject(e)}},u}(c)},b=/*#__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=v({},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,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).get(e,v({},t,((n={})[i]=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(v({},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,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).create(e,v({},t,((n={})[i]=o.core,n))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r){void 0===r&&(r={});try{var n,o,i=this,c=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).patch(e,t,v({},r,((o={})[c]=i.core,o))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,r){void 0===r&&(r={});try{var n,o,i=this,c=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service).update(e,t,v({},r,((o={})[c]=i.core,o))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var r,n,o=this,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service).remove(e,v({},t,((n={})[i]=o.core,n))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var r,n,o=this,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._get(e,v({},t,((n={})[i]=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(v({},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,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._create(e,v({},t,((n={})[i]=o.core,n))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,r){void 0===r&&(r={});try{var n,o,i=this,c=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._patch(e,t,v({},r,((o={})[c]=i.core,o))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,r){void 0===r&&(r={});try{var n,o,i=this,c=i.context.app.get("authentication").core_path;return Promise.resolve(null==(n=i.context.app)?void 0:n.service(i.service)._update(e,t,v({},r,((o={})[c]=i.core,o))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var r,n,o=this,i=o.context.app.get("authentication").core_path;return Promise.resolve(null==(r=o.context.app)?void 0:r.service(o.service)._remove(e,v({},t,((n={})[i]=o.core,n))))}catch(e){return Promise.reject(e)}},e}(),w=["ucan"];function j(e,t,r){if(!e.s){if(r instanceof x){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 x=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,r){const n=new e,o=this.s;if(o){const e=1&o?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 o=e.v;1&e.s?j(n,1,t?t(o):o):r?j(n,1,r(o)):j(n,2,o)}catch(e){j(n,2,e)}},n},e}();var O="*",k="$",E=function(t){try{var r=t.app.get("authentication"),n=e(t,["auth",r.entity]);return n&&(t=c(t,[r.core_path,r.entity],n)),Promise.resolve(h("jwt")(t).catch(function(e){return console.error("got error in no throw auth",e),t})).then(function(e){return t=e})}catch(e){return Promise.reject(e)}},S=function(t){try{var r=t.app.get("authentication"),n=e(t,["auth",r.entity]);return n&&(t=c(t,[r.core_path,r.entity],n)),Promise.resolve(h("jwt")(t))}catch(e){return Promise.reject(e)}},C=function(e){try{var t,r={ok:!1,value:[]},n=function(n,o,i){var c=[];for(var u in n)c.push(u);return function(e,t,r){var n,o,i=-1;return function c(a){try{for(;++i<e.length&&(!r||!r());)if((a=t(i))&&a.then){if(!((u=a)instanceof x&&1&u.s))return void a.then(c,o||(o=j.bind(null,n=new x,2)));a=a.v}n?j(n,1,a):n=a}catch(e){j(n||(n=new x),2,e)}var u}(),n}(c,function(n){return function(n){var o=function(){var o;if(null==(o=r)||!o.ok){var i=e[n],c=i.ucan,u=function(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)t.indexOf(r=i[n])>=0||(o[r]=e[r]);return o}(i,w);return Promise.resolve(function(e,t){try{return Promise.resolve(a(e,t))}catch(e){return Promise.reject(e)}}(c,u)).then(function(e){r=e})}t=1}();if(o&&o.then)return o.then(function(){})}(c[n])},function(){return t})}(e);return Promise.resolve(n&&n.then?n.then(function(){return r}):r)}catch(e){return Promise.reject(e)}},N=function(e,t,r,n){return function(o){try{var i;return e&&t&&null!=n&&null!=(i=n.or)&&i.includes(o.method)?Promise.resolve(C((r||[]).map(function(r){return{ucan:e,audience:t,requiredCapabilities:[r]}}))):Promise.resolve(a(e,{audience:t,requiredCapabilities:r}))}catch(e){return Promise.reject(e)}}},R=function(t,r){return function(n){try{var i,a=function(a){return i?a:Promise.resolve(S(n)).then(function(i){var a;if(n=i,"*"===t)return n;if(null!=r&&r.adminPass&&n.params.admin_pass)return n;var l=n.app.get("authentication"),p={ok:!1,value:[]},h=o({secretKey:l.secret}).did(),v=n.app.get("authentication"),f=(t||[]).map(function(e){var t={defaultScheme:v.defaultScheme,defaultHierPart:v.defaultHierPart};return{capability:Array.isArray(e)?u({with:{scheme:v.defaultScheme,hierPart:v.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},t):u(e,t),rootIssuer:h}}),d=e(n.params,v.client_ucan),m=e(n.params,v.ucan_aud);if(f.length?p=N(d,m,f,r):p.ok=!0,null!=(a=p)&&a.ok)return n;var y=function(){var t;if(null==(t=p)||!t.ok){var o=!1,i=[];f.forEach(function(t,r){var n=(e(t,"capability.can.namespace")||"").split(":");n[1]&&(t=c(t,"capability.can.namespace",n[0]),o=!0),i.push(t)}),o&&(p=N(d,m,f,r))}if(p.ok)return n;throw console.error("Ucan capabilities requirements not met: ",p,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)},g=r||{creatorPass:!1},P=g.creatorPass,_=g.loginPass,w=function(){if(P&&("*"===P||P.includes(n.method))||null!=_&&_.length&&("*"===_[1]||_[1].includes(n.method)))return Promise.resolve(new b(n.path,n,{skipJoins:!0}).get(n.id)).then(function(t){var r,o;if(P)p.ok=(null==t||null==(r=t.createdBy)?void 0:r.login)===((null==(o=n.login)?void 0:o._id)||"***");else if(_){var i,c=s(_[0].map(function(r){return e(t,r)}));p.ok=c.filter(function(e){return!!e}).includes(null==(i=n.login)?void 0:i._id)}})}();return w&&w.then?w.then(y):y()})},l=function(){if("$"===t)return Promise.resolve(E(n)).then(function(e){return i=1,e})}();return Promise.resolve(l&&l.then?l.then(a):a(l))}catch(e){return Promise.reject(e)}}},q=function(e,t){return function(r){try{var n=r.app.get("authentication"),o=r.auth[n.entity];if(o&&(r=c(r,[n.core_path,n.entity],o)),"before"===r.type){var i=r.method;return Promise.resolve(e[i]||e.all?R(e[i]||e.all,t)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},I=function(){return function(c){try{var u=c.data,s=u.add,h=void 0===s?[]:s,f=u.remove,d=void 0===f?[]:f;if(!(null!=h&&h.length||null!=d&&d.length))throw new Error("No new capabilities passed");var m=c.app.get("authentication"),y=m.secret,g=m.ucan_aud,P=o({secretKey:y}).did(),_=l([].concat(h,d));return Promise.resolve(a(c.params.login.ucan,{audience:e(c.params,g),requiredCapabilities:_.map(function(e){return{capability:e,rootIssuer:P}})})).then(function(a){if(null==a||!a.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var u=c.id,s=c.data.service||"logins",f=c.data.path||"ucan";return Promise.resolve(new b(s,c,{skipJoins:!0}).get(u)).then(function(a){var m=n(e(a,f)).payload,g=m.aud,P=m.att,_=m.prf,w=[].concat(P);return null!=d&&d.length&&(w=p(d,P)),null!=h&&h.length&&(w=l([].concat(P,h))),Promise.resolve(i(v({issuer:o({secretKey:y}),audience:g,proofs:_},c.data,{capabilities:w}))).then(function(e){var n=r(e);return Promise.resolve(t(n)).then(function(e){var t;if(!e)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new b(s,c).patch(u,(t={},t[f]=n,t))).then(function(e){return c.result={raw:c.data,encoded:n,subject:e},c})})})})})}catch(e){return Promise.reject(e)}}};export{b as CoreCall,P as NotAuthError,q as allUcanAuth,O as anyAuth,S as bareAuth,_ as genAuthService,k as noThrow,E as noThrowAuth,C as orVerifyLoop,R as ucanAuth,I as updateUcan,N as verifyAgainstReqs};
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 h,reduceAbilities as f}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 j(e){var t="function"==typeof Map?new Map:void 0;return j=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)},j(e)}function x(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}var _=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return g(t,e),t}(/*#__PURE__*/j(Error)),k=/(\S+)\s+(\S+)/,E=/*#__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 _("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(l)).then(function(e){if(e.total)return e.data[0]._id;throw new _("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,h=s.core_path;if(!a){if(!u)throw new _("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,[h,l]),f=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 f&&f.then?f.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(k)||[],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),O=["NotAuthenticated"],T=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return g(t,e),t}(/*#__PURE__*/j(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=x(n,O);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,h=(null==(u=l.options)?void 0:u.NotAuthenticated)||T,f=l.app.get("authentication"),p=f.entity,v=f.service,d=f.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 h("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"]),h=t.ucan||n(u,[p,"ucan"]);if(!s)throw new Error("No did audience provided");if(!h)throw new Error("No ucan provided to authentication call");return Promise.resolve(e(h).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",h,t.message),null})).then(function(e){function t(){var e=r(h);return y({accessToken:e},u,{authentication:y({},u.authentication,{payload:e})})}var n=function(){if(!e){var t=i(h),n=l.app.get("authentication"),s=o({secretKey:n.secret});return Promise.resolve(a({audience:t.payload.aud,issuer:s,capabilities:t.payload.att})).then(function(e){var t;return h=e,c.admin_pass=!0,Promise.resolve(l.app.service(v).patch(u[p]._id,(t={},t[m]=r(h),t),y({},c))).then(function(){})})}}();return n&&n.then?n.then(t):t()})})}catch(e){return Promise.reject(e)}},c}(v),S=/*#__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=["ucan"];function A(e,t,r){if(!e.s){if(r instanceof U){if(!r.s)return void(r.o=A.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(A.bind(null,e,t),A.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}const U=/*#__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{A(n,1,e(this.v))}catch(e){A(n,2,e)}return n}return this}return this.o=function(e){try{const i=e.v;1&e.s?A(n,1,t?t(i):i):r?A(n,1,r(i)):A(n,2,i)}catch(e){A(n,2,e)}},n},e}();var q="*",N="$",R=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)}},J=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)}},B=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 U&&1&u.s))return void c.then(a,i||(i=A.bind(null,n=new U,2)));c=c.v}n?A(n,1,c):n=c}catch(e){A(n||(n=new U),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=x(o,C);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)}},K=function(e,t,r,n){return function(i){try{var o;return e&&t&&null!=n&&null!=(o=n.or)&&o.includes(i.method)?Promise.resolve(B((r||[]).map(function(r){return{ucan:e,audience:t,requiredCapabilities:[r]}}))):Promise.resolve(u(e,{audience:t,requiredCapabilities:r}))}catch(e){return Promise.reject(e)}}},M=function(e,t){return function(r){try{var i,a=function(a){return i?a:Promise.resolve(J(r)).then(function(i){var a;if(r=i,"*"===e)return r;if(null!=t&&t.adminPass&&r.params.admin_pass)return r;var u=r.app.get("authentication"),h={ok:!1,value:[]},f=o({secretKey:u.secret}).did(),p=r.app.get("authentication"),v=(e||[]).map(function(e){var t={defaultScheme:p.defaultScheme,defaultHierPart:p.defaultHierPart};return{capability:Array.isArray(e)?s({with:{scheme:p.defaultScheme,hierPart:p.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},t):s(e,t),rootIssuer:f}}),d=n(r.params,p.client_ucan),m=n(r.params,p.ucan_aud);if(v.length?h=K(d,m,v,t):h.ok=!0,null!=(a=h)&&a.ok)return r;var y=function(){var e;if(null==(e=h)||!e.ok){var i=!1,o=[];v.forEach(function(e,t){var r=(n(e,"capability.can.namespace")||"").split(":");r[1]&&(e=c(e,"capability.can.namespace",r[0]),i=!0),o.push(e)}),i&&(h=K(d,m,v,t))}if(h.ok)return r;throw console.error("Ucan capabilities requirements not met: ",h,r.type,r.path),new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)},g=t||{creatorPass:!1},P=g.creatorPass,w=g.loginPass,b=function(){if(P&&("*"===P||P.includes(r.method))||null!=w&&w.length&&("*"===w[1]||w[1].includes(r.method)))return Promise.resolve(new S(r.path,r,{skipJoins:!0}).get(r.id)).then(function(e){var t,i;if(P)h.ok=(null==e||null==(t=e.createdBy)?void 0:t.login)===((null==(i=r.login)?void 0:i._id)||"***");else if(w){var o,a=l(w[0].map(function(t){return n(e,t)}));h.ok=a.filter(function(e){return!!e}).includes(null==(o=r.login)?void 0:o._id)}})}();return b&&b.then?b.then(y):y()})},u=function(){if("$"===e)return Promise.resolve(R(r)).then(function(e){return i=1,e})}();return Promise.resolve(u&&u.then?u.then(a):a(u))}catch(e){return Promise.reject(e)}}},H=function(e,t){return function(r){try{var n=r.app.get("authentication"),i=r.auth[n.entity];if(i&&(r=c(r,[n.core_path,n.entity],i)),"before"===r.type){var o=r.method;return Promise.resolve(e[o]||e.all?M(e[o]||e.all,t)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},V=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=o({secretKey:m}).did(),w=h([].concat(l,v));return Promise.resolve(u(t.params.login.ucan,{audience:n(t.params,g),requiredCapabilities:w.map(function(e){return{capability:e,rootIssuer:P}})})).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 S(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=f(v,P)),null!=l&&l.length&&(b=h([].concat(P,l))),Promise.resolve(a(y({issuer:o({secretKey:m}),audience:g,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 S(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,S as CoreCall,T as NotAuthError,E as UcanStrategy,H as allUcanAuth,q as anyAuth,J as bareAuth,N as noThrow,R as noThrowAuth,B as orVerifyLoop,M as ucanAuth,V as updateUcan,K as verifyAgainstReqs};
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- import{_get as t,validateUcan as e,parseUcan as a,encodeKeyPair as n,buildUcan as i,ucanToken as r,_set as c,verifyUcan as s,genCapability as o,_flatten as u,stackAbilities as h,reduceAbilities as p}from"symbol-ucan";import{authenticate as l}from"@feathersjs/authentication";function d(){return d=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t},d.apply(this,arguments)}function v(t,e){if(null==t)return{};var a,n,i={},r=Object.keys(t);for(n=0;n<r.length;n++)e.indexOf(a=r[n])>=0||(i[a]=t[a]);return i}class g extends Error{constructor(t){super(t)}}const f=(c,s)=>class extends c{constructor(t,e="authentication",a={}){super(t,e,a),this.app=t}async create(c,o){var u;const h=(null==s?void 0:s.NotAuthenticated)||g,{entity:p,service:l,ucan_path:v="ucan"}=this.app.get("authentication"),f=(null==(u=o)?void 0:u.authStrategies)||this.configuration.authStrategies;if(o||(o={}),!f.length)throw new h("No authentication strategies allowed for creating a JWT (`authStrategies`)");const y=await this.authenticate(c,o,...f).catch(t=>{throw new Error(t.message)});if(y.accessToken)return y;const w=c.did||t(y,[p,"did"]);let m=c.ucan||t(y,[p,"ucan"]);if(!w)throw new Error("No did audience provided");if(!m)throw new Error("No ucan provided to authentication call");if(!await e(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=a(m);let{secret:e}=this.app.get("authentication");const c=n({secretKey:e});m=await i({audience:t.payload.aud,issuer:c,capabilities:t.payload.att}),o.admin_pass=!0,await this.app.service(l).patch(y[p]._id,{[v]:r(m)},d({},o))}const _=r(m);return d({accessToken:_},y,{authentication:d({},y.authentication,{payload:_})})}};class y{constructor(t,e,a){var n;this.context=void 0,this.service=void 0,this.core=void 0,this.service=t,this.context=e,this.core=d({},null==(n=e.params)?void 0:n.core,a)}async get(t,e={}){var a;const{core_path:n}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service).get(t,d({},e,{[n]: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(d({},t,{[a]:this.core}))}async create(t,e={}){var a;const{core_path:n}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service).create(t,d({},e,{[n]:this.core}))}async patch(t,e,a={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).patch(t,e,d({},a,{[i]:this.core}))}async update(t,e,a={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).update(t,e,d({},a,{[i]:this.core}))}async remove(t,e={}){var a;const{core_path:n}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service).remove(t,d({},e,{[n]:this.core}))}async _get(t,e={}){var a;const{core_path:n}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service)._get(t,d({},e,{[n]: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(d({},t,{[a]:this.core}))}async _create(t,e={}){var a;const{core_path:n}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service)._create(t,d({},e,{[n]:this.core}))}async _patch(t,e,a={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._patch(t,e,d({},a,{[i]:this.core}))}async _update(t,e,a={}){var n;const{core_path:i}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._update(t,e,d({},a,{[i]:this.core}))}async _remove(t,e={}){var a;const{core_path:n}=this.context.app.get("authentication");return null==(a=this.context.app)?void 0:a.service(this.service)._remove(t,d({},e,{[n]:this.core}))}}const w=["ucan"],m="*",_="$",x=async e=>{const a=e.app.get("authentication"),n=t(e,["auth",a.entity]);return n&&(e=c(e,[a.core_path,a.entity],n)),e=await l("jwt")(e).catch(t=>(console.error("got error in no throw auth",t),e))},b=async e=>{const a=e.app.get("authentication"),n=t(e,["auth",a.entity]);return n&&(e=c(e,[a.core_path,a.entity],n)),l("jwt")(e)},k=async t=>{let e={ok:!1,value:[]};const a=async(t,e)=>await s(t,e);for(const i in t){var n;if(null!=(n=e)&&n.ok)break;{const n=t[i],{ucan:r}=n,c=v(n,w);e=await a(r,c)}}return e},E=(t,e,a,n)=>async i=>{var r;return t&&e&&null!=n&&null!=(r=n.or)&&r.includes(i.method)?await k((a||[]).map(a=>({ucan:t,audience:e,requiredCapabilities:[a]}))):await s(t,{audience:e,requiredCapabilities:a})},P=(e,a)=>async i=>{var r;if("$"===e)return await x(i);if(i=await b(i),"*"===e)return i;if(null!=a&&a.adminPass&&i.params.admin_pass)return i;const{secret:s}=i.app.get("authentication");let h={ok:!1,value:[]};const p=n({secretKey:s}).did(),l=i.app.get("authentication"),d=(e||[]).map(t=>{const e={defaultScheme:l.defaultScheme,defaultHierPart:l.defaultHierPart};return{capability:Array.isArray(t)?o({with:{scheme:l.defaultScheme,hierPart:l.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},e):o(t,e),rootIssuer:p}}),v=t(i.params,l.client_ucan),g=t(i.params,l.ucan_aud);if(d.length?h=E(v,g,d,a):h.ok=!0,null!=(r=h)&&r.ok)return i;{var f;const{creatorPass:e,loginPass:n}=a||{creatorPass:!1};if(e&&("*"===e||e.includes(i.method))||null!=n&&n.length&&("*"===n[1]||n[1].includes(i.method))){const a=await new y(i.path,i,{skipJoins:!0}).get(i.id);var w,m;if(e)h.ok=(null==a||null==(w=a.createdBy)?void 0:w.login)===((null==(m=i.login)?void 0:m._id)||"***");else if(n){var _;const e=u(n[0].map(e=>t(a,e)));h.ok=e.filter(t=>!!t).includes(null==(_=i.login)?void 0:_._id)}}if(null==(f=h)||!f.ok){let e=!1;d.forEach((a,n)=>{const i=(t(a,"capability.can.namespace")||"").split(":");i[1]&&(a=c(a,"capability.can.namespace",i[0]),e=!0)}),e&&(h=E(v,g,d,a))}if(h.ok)return i;throw console.error("Ucan capabilities requirements not met: ",h,i.type,i.path),new Error("Missing proper capabilities for this action: "+i.type+": "+i.path+" - "+i.method)}},j=(t,e)=>async a=>{const n=a.app.get("authentication"),i=a.auth[n.entity];if(i&&(a=c(a,[n.core_path,n.entity],i)),"before"===a.type){const{method:n}=a;return t[n]||t.all?P(t[n]||t.all,e)(a):a}return a},O=()=>async c=>{const{add:o=[],remove:u=[]}=c.data;if(!(null!=o&&o.length||null!=u&&u.length))throw new Error("No new capabilities passed");const{secret:l,ucan_aud:v}=c.app.get("authentication"),g=n({secretKey:l}).did(),f=h([...o,...u]),w=await s(c.params.login.ucan,{audience:t(c.params,v),requiredCapabilities:f.map(t=>({capability:t,rootIssuer:g}))});if(null==w||!w.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");const m=c.id,_=c.data.service||"logins",x=c.data.path||"ucan",b=await new y(_,c,{skipJoins:!0}).get(m),k=a(t(b,x)),{aud:E,att:P,prf:j}=k.payload;let O=[...P];null!=u&&u.length&&(O=p(u,P)),null!=o&&o.length&&(O=h([...P,...o]));const S=await i(d({issuer:n({secretKey:l}),audience:E,proofs:j},c.data,{capabilities:O})),C=r(S);if(!await e(C))throw new Error("Invalid ucan generated when updating");const N=await new y(_,c).patch(m,{[x]:C});return c.result={raw:c.data,encoded:C,subject:N},c};export{y as CoreCall,g as NotAuthError,j as allUcanAuth,m as anyAuth,b as bareAuth,f as genAuthService,_ as noThrow,x as noThrowAuth,k as orVerifyLoop,P as ucanAuth,O as updateUcan,E as verifyAgainstReqs};
1
+ import{validateUcan as t,_unset as e,ucanToken as a,_get as i,parseUcan as n,encodeKeyPair as o,buildUcan as s,_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 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={},o=Object.keys(t);for(i=0;i<o.length;i++)e.indexOf(a=o[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:o}=i||{};if(o&&"login"===e){const e=await t(o).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(),s=y.setTimeout(()=>this.app.emit("disconnect",a),n);y.clearTimeout(this.expirationTimers.get(a)),this.expirationTimers.set(a,s),a.authentication={strategy:this.name,accessToken:o}}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 o=await this.getEntityQuery(a),s=Object.assign({},e(a,"provider"),{query:o}),r=await i.get(t,s);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,o={query:f({},a,{$limit:1}),[i]:f({skipJoins:!0},e[i])},s=await(null==(n=this.app)?void 0:n.service(t).find(o));if(s.total)return s.data[0]._id;throw new w("Could not find login associated with this ucan")}}async authenticate(e,n){let{accessToken:o,loginId:s,ucan:r}=e;const{entity:c,core_path:u}=this.configuration;if(!o){if(!r)throw new w("Error generating ucan");o=a(r)}const h=await t(o).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:o,authentication:{strategy:"jwt",accessToken:o}};if(null===c)return l;let p;const d=i(n,[u,c]);if(d)p=d;else{const t=await this.getEntityId(l,f({},n,{loginId:s,query:{did:null==h?void 0:h.payload.aud}}));p=await this.getEntity(t,n)}return f({},l,{[c]:p})}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,o]=i.match(x)||[],s=n&&a.some(t=>new RegExp(t,"i").test(n));return n&&!s?null:{strategy:this.name,accessToken:s?o: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:l,service:p,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,[l,"did"]);let m=e.ucan||i(v,[l,"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 i=o({secretKey:e});m=await s({audience:t.payload.aud,issuer:i,capabilities:t.payload.att}),r.admin_pass=!0,await this.app.service(p).patch(v[l]._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=["ucan"],j="*",C="$",O=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))},S=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)},U=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:o}=i,s=m(i,I);e=await a(o,s)}}return e},A=(t,e,a,i)=>async n=>{var o;return t&&e&&null!=i&&null!=(o=i.or)&&o.includes(n.method)?await U((a||[]).map(a=>({ucan:t,audience:e,requiredCapabilities:[a]}))):await c(t,{audience:e,requiredCapabilities:a})},P=(t,e)=>async a=>{var n;if("$"===t)return await O(a);if(a=await S(a),"*"===t)return a;if(null!=e&&e.adminPass&&a.params.admin_pass)return a;const{secret:s}=a.app.get("authentication");let c={ok:!1,value:[]};const l=o({secretKey:s}).did(),p=a.app.get("authentication"),d=(t||[]).map(t=>{const e={defaultScheme:p.defaultScheme,defaultHierPart:p.defaultHierPart};return{capability:Array.isArray(t)?u({with:{scheme:p.defaultScheme,hierPart:p.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},e):u(t,e),rootIssuer:l}}),g=i(a.params,p.client_ucan),v=i(a.params,p.ucan_aud);if(d.length?c=A(g,v,d,e):c.ok=!0,null!=(n=c)&&n.ok)return a;{var y;const{creatorPass:t,loginPass:n}=e||{creatorPass:!1};if(t&&("*"===t||t.includes(a.method))||null!=n&&n.length&&("*"===n[1]||n[1].includes(a.method))){const e=await new T(a.path,a,{skipJoins:!0}).get(a.id);var f,m;if(t)c.ok=(null==e||null==(f=e.createdBy)?void 0:f.login)===((null==(m=a.login)?void 0:m._id)||"***");else if(n){var w;const t=h(n[0].map(t=>i(e,t)));c.ok=t.filter(t=>!!t).includes(null==(w=a.login)?void 0:w._id)}}if(null==(y=c)||!y.ok){let t=!1;d.forEach((e,a)=>{const n=(i(e,"capability.can.namespace")||"").split(":");n[1]&&(e=r(e,"capability.can.namespace",n[0]),t=!0)}),t&&(c=A(g,v,d,e))}if(c.ok)return a;throw console.error("Ucan capabilities requirements not met: ",c,a.type,a.path),new Error("Missing proper capabilities for this action: "+a.type+": "+a.path+" - "+a.method)}},q=(t,e)=>async a=>{const i=a.app.get("authentication"),n=a.auth[i.entity];if(n&&(a=r(a,[i.core_path,i.entity],n)),"before"===a.type){const{method:i}=a;return t[i]||t.all?P(t[i]||t.all,e)(a):a}return a},N=()=>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}=e.app.get("authentication"),g=o({secretKey:h}).did(),v=l([...r,...u]),y=await c(e.params.login.ucan,{audience:i(e.params,d),requiredCapabilities:v.map(t=>({capability:t,rootIssuer:g}))});if(null==y||!y.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");const m=e.id,w=e.data.service||"logins",x=e.data.path||"ucan",_=await new T(w,e,{skipJoins:!0}).get(m),k=n(i(_,x)),{aud:E,att:b,prf:I}=k.payload;let j=[...b];null!=u&&u.length&&(j=p(u,b)),null!=r&&r.length&&(j=l([...b,...r]));const C=await s(f({issuer:o({secretKey:h}),audience:E,proofs:I},e.data,{capabilities:j})),O=a(C);if(!await t(O))throw new Error("Invalid ucan generated when updating");const S=await new T(w,e).patch(m,{[x]:O});return e.result={raw:e.data,encoded:O,subject:S},e};export{b as AuthService,T as CoreCall,E as NotAuthError,_ as UcanStrategy,q as allUcanAuth,j as anyAuth,S as bareAuth,C as noThrow,O as noThrowAuth,U as orVerifyLoop,P as ucanAuth,N as updateUcan,A 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")):"function"==typeof define&&define.amd?define(["exports","symbol-ucan","@feathersjs/authentication"],t):t((e||self).feathersUcan={},e.symbolUcan,e.authentication)}(this,function(e,t,r){function n(){return n=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},n.apply(this,arguments)}function i(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,a(e,t)}function o(e){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},o(e)}function a(e,t){return a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},a(e,t)}function c(e,t,r){return c=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&&a(i,r.prototype),i},c.apply(null,arguments)}function u(e){var t="function"==typeof Map?new Map:void 0;return u=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))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 c(e,arguments,o(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),a(r,e)},u(e)}var s=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return i(t,e),t}(/*#__PURE__*/u(Error)),l=/*#__PURE__*/function(){function e(e,t,r){var i;this.context=void 0,this.service=void 0,this.core=void 0,this.service=e,this.context=t,this.core=n({},null==(i=t.params)?void 0:i.core,r)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});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).get(e,n({},t,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(t=i.context.app)?void 0:t.service(i.service).find(n({},e,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});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).create(e,n({},t,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r){void 0===r&&(r={});try{var i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(i=a.context.app)?void 0:i.service(a.service).patch(e,t,n({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,r){void 0===r&&(r={});try{var i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(i=a.context.app)?void 0:i.service(a.service).update(e,t,n({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});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).remove(e,n({},t,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});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)._get(e,n({},t,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,r,i=this,o=i.context.app.get("authentication").core_path;return Promise.resolve(null==(t=i.context.app)?void 0:t.service(i.service)._find(n({},e,((r={})[o]=i.core,r))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});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)._create(e,n({},t,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,r){void 0===r&&(r={});try{var i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(i=a.context.app)?void 0:i.service(a.service)._patch(e,t,n({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,r){void 0===r&&(r={});try{var i,o,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(i=a.context.app)?void 0:i.service(a.service)._update(e,t,n({},r,((o={})[c]=a.core,o))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});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)._remove(e,n({},t,((i={})[a]=o.core,i))))}catch(e){return Promise.reject(e)}},e}(),p=["ucan"];function h(e,t,r){if(!e.s){if(r instanceof f){if(!r.s)return void(r.o=h.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(h.bind(null,e,t),h.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}const f=/*#__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{h(n,1,e(this.v))}catch(e){h(n,2,e)}return n}return this}return this.o=function(e){try{const i=e.v;1&e.s?h(n,1,t?t(i):i):r?h(n,1,r(i)):h(n,2,i)}catch(e){h(n,2,e)}},n},e}();var v=function(e){try{var n=e.app.get("authentication"),i=t._get(e,["auth",n.entity]);return i&&(e=t._set(e,[n.core_path,n.entity],i)),Promise.resolve(r.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)}},d=function(e){try{var n=e.app.get("authentication"),i=t._get(e,["auth",n.entity]);return i&&(e=t._set(e,[n.core_path,n.entity],i)),Promise.resolve(r.authenticate("jwt")(e))}catch(e){return Promise.reject(e)}},m=function(e){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 f&&1&u.s))return void c.then(a,i||(i=h.bind(null,n=new f,2)));c=c.v}n?h(n,1,c):n=c}catch(e){h(n||(n=new f),2,e)}var u}(),n}(c,function(i){return function(i){var o=function(){var o;if(null==(o=n)||!o.ok){var a=e[i],c=a.ucan,u=function(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}(a,p);return Promise.resolve(function(e,r){try{return Promise.resolve(t.verifyUcan(e,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})}(e);return Promise.resolve(i&&i.then?i.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},y=function(e,r,n,i){return function(o){try{var a;return e&&r&&null!=i&&null!=(a=i.or)&&a.includes(o.method)?Promise.resolve(m((n||[]).map(function(t){return{ucan:e,audience:r,requiredCapabilities:[t]}}))):Promise.resolve(t.verifyUcan(e,{audience:r,requiredCapabilities:n}))}catch(e){return Promise.reject(e)}}},g=function(e,r){return function(n){try{var i,o=function(o){return i?o:Promise.resolve(d(n)).then(function(i){var o;if(n=i,"*"===e)return n;if(null!=r&&r.adminPass&&n.params.admin_pass)return n;var a=n.app.get("authentication"),c={ok:!1,value:[]},u=t.encodeKeyPair({secretKey:a.secret}).did(),s=n.app.get("authentication"),p=(e||[]).map(function(e){var r={defaultScheme:s.defaultScheme,defaultHierPart:s.defaultHierPart};return{capability:Array.isArray(e)?t.genCapability({with:{scheme:s.defaultScheme,hierPart:s.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},r):t.genCapability(e,r),rootIssuer:u}}),h=t._get(n.params,s.client_ucan),f=t._get(n.params,s.ucan_aud);if(p.length?c=y(h,f,p,r):c.ok=!0,null!=(o=c)&&o.ok)return n;var v=function(){var e;if(null==(e=c)||!e.ok){var i=!1,o=[];p.forEach(function(e,r){var n=(t._get(e,"capability.can.namespace")||"").split(":");n[1]&&(e=t._set(e,"capability.can.namespace",n[0]),i=!0),o.push(e)}),i&&(c=y(h,f,p,r))}if(c.ok)return n;throw console.error("Ucan capabilities requirements not met: ",c,n.type,n.path),new Error("Missing proper capabilities for this action: "+n.type+": "+n.path+" - "+n.method)},d=r||{creatorPass:!1},m=d.creatorPass,g=d.loginPass,P=function(){if(m&&("*"===m||m.includes(n.method))||null!=g&&g.length&&("*"===g[1]||g[1].includes(n.method)))return Promise.resolve(new l(n.path,n,{skipJoins:!0}).get(n.id)).then(function(e){var r,i;if(m)c.ok=(null==e||null==(r=e.createdBy)?void 0:r.login)===((null==(i=n.login)?void 0:i._id)||"***");else if(g){var o,a=t._flatten(g[0].map(function(r){return t._get(e,r)}));c.ok=a.filter(function(e){return!!e}).includes(null==(o=n.login)?void 0:o._id)}})}();return P&&P.then?P.then(v):v()})},a=function(){if("$"===e)return Promise.resolve(v(n)).then(function(e){return i=1,e})}();return Promise.resolve(a&&a.then?a.then(o):o(a))}catch(e){return Promise.reject(e)}}};e.CoreCall=l,e.NotAuthError=s,e.allUcanAuth=function(e,r){return function(n){try{var i=n.app.get("authentication"),o=n.auth[i.entity];if(o&&(n=t._set(n,[i.core_path,i.entity],o)),"before"===n.type){var a=n.method;return Promise.resolve(e[a]||e.all?g(e[a]||e.all,r)(n):n)}return Promise.resolve(n)}catch(e){return Promise.reject(e)}}},e.anyAuth="*",e.bareAuth=d,e.genAuthService=function(e,r){/*#__PURE__*/return function(e){function o(t,r,n){var i;return void 0===r&&(r="authentication"),void 0===n&&(n={}),(i=e.call(this,t,r,n)||this).app=t,i}return i(o,e),o.prototype.create=function(e,i){try{var o,a=this,c=(null==r?void 0:r.NotAuthenticated)||s,u=a.app.get("authentication"),l=u.entity,p=u.service,h=u.ucan_path,f=void 0===h?"ucan":h,v=(null==(o=i)?void 0:o.authStrategies)||a.configuration.authStrategies;if(i||(i={}),!v.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(a.authenticate.apply(a,[e,i].concat(v)).catch(function(e){throw new Error(e.message)})).then(function(r){if(r.accessToken)return r;var o=e.did||t._get(r,[l,"did"]),c=e.ucan||t._get(r,[l,"ucan"]);if(!o)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 o(){var e=t.ucanToken(c);return n({accessToken:e},r,{authentication:n({},r.authentication,{payload:e})})}var u=function(){if(!e){var o=t.parseUcan(c),u=a.app.get("authentication"),s=t.encodeKeyPair({secretKey:u.secret});return Promise.resolve(t.buildUcan({audience:o.payload.aud,issuer:s,capabilities:o.payload.att})).then(function(e){var o;return c=e,i.admin_pass=!0,Promise.resolve(a.app.service(p).patch(r[l]._id,(o={},o[f]=t.ucanToken(c),o),n({},i))).then(function(){})})}}();return u&&u.then?u.then(o):o()})})}catch(e){return Promise.reject(e)}},o}(e)},e.noThrow="$",e.noThrowAuth=v,e.orVerifyLoop=m,e.ucanAuth=g,e.updateUcan=function(){return function(e){try{var r=e.data,i=r.add,o=void 0===i?[]:i,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=e.app.get("authentication"),s=u.secret,p=u.ucan_aud,h=t.encodeKeyPair({secretKey:s}).did(),f=t.stackAbilities([].concat(o,c));return Promise.resolve(t.verifyUcan(e.params.login.ucan,{audience:t._get(e.params,p),requiredCapabilities:f.map(function(e){return{capability:e,rootIssuer:h}})})).then(function(r){if(null==r||!r.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var i=e.id,a=e.data.service||"logins",u=e.data.path||"ucan";return Promise.resolve(new l(a,e,{skipJoins:!0}).get(i)).then(function(r){var p=t.parseUcan(t._get(r,u)).payload,h=p.aud,f=p.att,v=p.prf,d=[].concat(f);return null!=c&&c.length&&(d=t.reduceAbilities(c,f)),null!=o&&o.length&&(d=t.stackAbilities([].concat(f,o))),Promise.resolve(t.buildUcan(n({issuer:t.encodeKeyPair({secretKey:s}),audience:h,proofs:v},e.data,{capabilities:d}))).then(function(r){var n=t.ucanToken(r);return Promise.resolve(t.validateUcan(n)).then(function(t){var r;if(!t)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new l(a,e).patch(i,(r={},r[u]=n,r))).then(function(t){return e.result={raw:e.data,encoded:n,subject:t},e})})})})})}catch(e){return Promise.reject(e)}}},e.verifyAgainstReqs=y});
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 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 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)},h(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}var p=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return c(t,e),t}(/*#__PURE__*/h(Error)),v=/(\S+)\s+(\S+)/,d=/*#__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 p("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,h=((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(h)).then(function(e){if(e.total)return e.data[0]._id;throw new p("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 p("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({},h,((e={})[s]=u,e))}var u,h={accessToken:i,authentication:{strategy:"jwt",accessToken:i}};if(null===s)return h;var f=t._get(n,[l,s]),p=function(){if(!f)return Promise.resolve(r.getEntityId(h,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=f}();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(v)||[],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"],m=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return c(t,e),t}(/*#__PURE__*/h(Error)),g=/*#__PURE__*/function(e){function n(t,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=f(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)||m,u=o.app.get("authentication"),s=u.entity,l=u.service,h=u.ucan_path,f=void 0===h?"ucan":h,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"),h=t.encodeKeyPair({secretKey:u.secret});return Promise.resolve(t.buildUcan({audience:i.payload.aud,issuer:h,capabilities:i.payload.att})).then(function(e){var i;return c=e,n.admin_pass=!0,Promise.resolve(o.app.service(l).patch(r[s]._id,(i={},i[f]=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),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=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=["ucan"];function w(e,t,n){if(!e.s){if(n instanceof _){if(!n.s)return void(n.o=w.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(w.bind(null,e,t),w.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}const _=/*#__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{w(r,1,e(this.v))}catch(e){w(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?w(r,1,t?t(i):i):n?w(r,1,n(i)):w(r,2,i)}catch(e){w(r,2,e)}},r},e}();var j=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)}},x=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)}},k=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 _&&1&u.s))return void c.then(a,i||(i=w.bind(null,r=new _,2)));c=c.v}r?w(r,1,c):r=c}catch(e){w(r||(r=new _),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=f(a,b);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)}},T=function(e,n,r,i){return function(o){try{var a;return e&&n&&null!=i&&null!=(a=i.or)&&a.includes(o.method)?Promise.resolve(k((r||[]).map(function(t){return{ucan:e,audience:n,requiredCapabilities:[t]}}))):Promise.resolve(t.verifyUcan(e,{audience:n,requiredCapabilities:r}))}catch(e){return Promise.reject(e)}}},E=function(e,n){return function(r){try{var i,o=function(o){return i?o:Promise.resolve(x(r)).then(function(i){var o;if(r=i,"*"===e)return r;if(null!=n&&n.adminPass&&r.params.admin_pass)return r;var a=r.app.get("authentication"),c={ok:!1,value:[]},u=t.encodeKeyPair({secretKey:a.secret}).did(),s=r.app.get("authentication"),l=(e||[]).map(function(e){var n={defaultScheme:s.defaultScheme,defaultHierPart:s.defaultHierPart};return{capability:Array.isArray(e)?t.genCapability({with:{scheme:s.defaultScheme,hierPart:s.defaultHierPart},can:{namespace:e[0],segments:"string"==typeof e[1]?[e[1]]:e[1]}},n):t.genCapability(e,n),rootIssuer:u}}),h=t._get(r.params,s.client_ucan),f=t._get(r.params,s.ucan_aud);if(l.length?c=T(h,f,l,n):c.ok=!0,null!=(o=c)&&o.ok)return r;var p=function(){var e;if(null==(e=c)||!e.ok){var i=!1,o=[];l.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),o.push(e)}),i&&(c=T(h,f,l,n))}if(c.ok)return r;throw console.error("Ucan capabilities requirements not met: ",c,r.type,r.path),new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)},v=n||{creatorPass:!1},d=v.creatorPass,y=v.loginPass,m=function(){if(d&&("*"===d||d.includes(r.method))||null!=y&&y.length&&("*"===y[1]||y[1].includes(r.method)))return Promise.resolve(new P(r.path,r,{skipJoins:!0}).get(r.id)).then(function(e){var n,i;if(d)c.ok=(null==e||null==(n=e.createdBy)?void 0:n.login)===((null==(i=r.login)?void 0:i._id)||"***");else if(y){var o,a=t._flatten(y[0].map(function(n){return t._get(e,n)}));c.ok=a.filter(function(e){return!!e}).includes(null==(o=r.login)?void 0:o._id)}})}();return m&&m.then?m.then(p):p()})},a=function(){if("$"===e)return Promise.resolve(j(r)).then(function(e){return i=1,e})}();return Promise.resolve(a&&a.then?a.then(o):o(a))}catch(e){return Promise.reject(e)}}};e.AuthService=g,e.CoreCall=P,e.NotAuthError=m,e.UcanStrategy=d,e.allUcanAuth=function(e,n){return function(r){try{var i=r.app.get("authentication"),o=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?E(e[a]||e.all,n)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},e.anyAuth="*",e.bareAuth=x,e.noThrow="$",e.noThrowAuth=j,e.orVerifyLoop=k,e.ucanAuth=E,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,h=t.encodeKeyPair({secretKey:s}).did(),f=t.stackAbilities([].concat(i,c));return Promise.resolve(t.verifyUcan(e.params.login.ucan,{audience:t._get(e.params,l),requiredCapabilities:f.map(function(e){return{capability:e,rootIssuer:h}})})).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 P(o,e,{skipJoins:!0}).get(r)).then(function(n){var l=t.parseUcan(t._get(n,u)).payload,h=l.aud,f=l.att,p=l.prf,v=[].concat(f);return null!=c&&c.length&&(v=t.reduceAbilities(c,f)),null!=i&&i.length&&(v=t.stackAbilities([].concat(f,i))),Promise.resolve(t.buildUcan(a({issuer:t.encodeKeyPair({secretKey:s}),audience:h,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 P(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=T});
@@ -4,72 +4,3 @@ export type AnyObj = {
4
4
  export type HookContext<S = any> = {
5
5
  [key: string]: any;
6
6
  } & S;
7
- export interface AuthenticationRequest {
8
- strategy?: string;
9
- [key: string]: any;
10
- }
11
- export interface JwtHeader {
12
- alg: string | Algorithm;
13
- typ?: string | undefined;
14
- cty?: string | undefined;
15
- crit?: Array<string | Exclude<keyof JwtHeader, 'crit'>> | undefined;
16
- kid?: string | undefined;
17
- jku?: string | undefined;
18
- x5u?: string | string[] | undefined;
19
- 'x5t#S256'?: string | undefined;
20
- x5t?: string | undefined;
21
- x5c?: string | string[] | undefined;
22
- }
23
- export interface SignOptions {
24
- /**
25
- * Signature algorithm. Could be one of these values :
26
- * - HS256: HMAC using SHA-256 hash algorithm (default)
27
- * - HS384: HMAC using SHA-384 hash algorithm
28
- * - HS512: HMAC using SHA-512 hash algorithm
29
- * - RS256: RSASSA using SHA-256 hash algorithm
30
- * - RS384: RSASSA using SHA-384 hash algorithm
31
- * - RS512: RSASSA using SHA-512 hash algorithm
32
- * - ES256: ECDSA using P-256 curve and SHA-256 hash algorithm
33
- * - ES384: ECDSA using P-384 curve and SHA-384 hash algorithm
34
- * - ES512: ECDSA using P-521 curve and SHA-512 hash algorithm
35
- * - none: No digital signature or MAC value included
36
- */
37
- algorithm?: Algorithm | undefined;
38
- keyid?: string | undefined;
39
- /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */
40
- expiresIn?: string | number | undefined;
41
- /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */
42
- notBefore?: string | number | undefined;
43
- audience?: string | string[] | undefined;
44
- subject?: string | undefined;
45
- issuer?: string | undefined;
46
- jwtid?: string | undefined;
47
- mutatePayload?: boolean | undefined;
48
- noTimestamp?: boolean | undefined;
49
- header?: JwtHeader | undefined;
50
- encoding?: string | undefined;
51
- allowInsecureKeySizes?: boolean | undefined;
52
- allowInvalidAsymmetricKeyTypes?: boolean | undefined;
53
- }
54
- export interface Query {
55
- [key: string]: any;
56
- }
57
- export interface Params<Q = Query> {
58
- query?: Q;
59
- provider?: string;
60
- route?: {
61
- [key: string]: any;
62
- };
63
- headers?: {
64
- [key: string]: any;
65
- };
66
- }
67
- export interface AuthenticationParams extends Params {
68
- payload?: {
69
- [key: string]: any;
70
- };
71
- jwtOptions?: SignOptions;
72
- authStrategies?: string[];
73
- secret?: string;
74
- [key: string]: any;
75
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feathers-ucan",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "Ucan extension of feathers jwt auth",
5
5
  "source": "src/index.ts",
6
6
  "unpkg": "lib/index.umd.js",
@@ -30,7 +30,6 @@
30
30
  },
31
31
  "homepage": "https://github.com/ha6755ad/symbol-utils#readme",
32
32
  "devDependencies": {
33
- "@types/ua-parser-js": "^0.7.36",
34
33
  "@typescript-eslint/eslint-plugin": "^5.10.0",
35
34
  "@typescript-eslint/parser": "^5.10.0",
36
35
  "eslint": "^8.10.0",
@@ -42,6 +41,7 @@
42
41
  "dependencies": {
43
42
  "@feathersjs/authentication": "^5.0.11",
44
43
  "@ucans/ucans": "^0.12.0",
44
+ "long-timeout": "^0.1.1",
45
45
  "radash": "^11.0.0",
46
46
  "symbol-ucan": "^0.0.0"
47
47
  }