feathers-ucan 0.1.7 → 0.1.8
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 +2 -0
- package/package.json +1 -1
- package/lib/auth-service/index.d.ts +0 -14
- package/lib/auth-service/index.js +0 -3
- package/lib/auth-service/ucan-strategy.d.ts +0 -36
- package/lib/auth-service.cjs +0 -2
- package/lib/auth-service.js +0 -1
- package/lib/core/index.d.ts +0 -1
- package/lib/core/index.js +0 -3
- package/lib/core/methods.d.ts +0 -34
- package/lib/core.cjs +0 -2
- package/lib/core.js +0 -1
- package/lib/env/version.d.ts +0 -1
- package/lib/hooks/index.d.ts +0 -2
- package/lib/hooks/index.js +0 -19
- package/lib/hooks/ucan-auth.d.ts +0 -75
- package/lib/hooks/update-ucan.d.ts +0 -1
- package/lib/hooks.cjs +0 -2
- package/lib/hooks.js +0 -1
- package/lib/index.cjs +0 -2
- package/lib/index.cjs.map +0 -1
- package/lib/index.d.ts +0 -5
- package/lib/index.modern.js +0 -2
- package/lib/index.modern.js.map +0 -1
- package/lib/index.module.js +0 -2
- package/lib/index.module.js.map +0 -1
- package/lib/index.umd.js +0 -2
- package/lib/index.umd.js.map +0 -1
- package/lib/scripts/gen-version.d.ts +0 -1
- package/lib/types/index.d.ts +0 -6
- package/lib/types/index.js +0 -4
- package/lib/types.cjs +0 -2
- package/lib/types.js +0 -1
- package/lib/utils/check-exists.d.ts +0 -8
- package/lib/utils/index.d.ts +0 -1
- package/lib/utils/index.js +0 -3
- package/lib/utils.cjs +0 -2
- package/lib/utils.js +0 -1
package/README.md
CHANGED
|
@@ -62,6 +62,8 @@ You'll need the following config options under `default.json` `authentication` s
|
|
|
62
62
|
|
|
63
63
|
**core:** Our chosen implementation is to pass what we label `core` params - the path to "core" is configurable in the app configuration as well. This allows us to pass along key authentication data from call to call internally so we don't lose our ucan context as we go.
|
|
64
64
|
|
|
65
|
+
**channels upgrade to core** Since params are passed along on a per-call basis, optionally your application can store the user object at the configured [user] path (same as the path used for core params) on the connection object. This allows the same user to be used across multiple calls without needing to refresh params and reauthenticate/call the users service. We found often our users service was being called dozens of time from a single client view due to fresh params being used for many simple database calls requiring authentication.
|
|
66
|
+
|
|
65
67
|
It's worth noting that the `client_ucan` is typically the calling user's `ucan` token - so it would be accessible in vanilla feathers under `context.auth.user[ucan_path]`. The `ucan_aud` is a `did` and we also save this on the user - so it too would be accessible there. We simply use the core options to avoid redundant calls to authentication on internal calls.
|
|
66
68
|
|
|
67
69
|
Also worth noting is that we expose a `CoreCall` class that allows you to make feathers service calls and automatically pass core params along in the call. We have found this to be extensible and useful over time.
|
package/package.json
CHANGED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { AuthenticationParams, AuthenticationRequest, AuthenticationService } from '@feathersjs/authentication';
|
|
2
|
-
import { AnyObj } from '../types';
|
|
3
|
-
export declare class NotAuthError extends Error {
|
|
4
|
-
constructor(message?: string);
|
|
5
|
-
}
|
|
6
|
-
export type AuthServiceOptions = {
|
|
7
|
-
NotAuthenticated?: any;
|
|
8
|
-
};
|
|
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
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import { IncomingMessage } from 'http';
|
|
3
|
-
import { AuthenticationBase, AuthenticationBaseStrategy, AuthenticationRequest, AuthenticationResult, ConnectionEvent } 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 {};
|
package/lib/auth-service.cjs
DELETED
package/lib/auth-service.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './auth-service/index.js';
|
package/lib/core/index.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './methods';
|
package/lib/core/index.js
DELETED
package/lib/core/methods.d.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { AnyObj } from '../types';
|
|
2
|
-
export type Id = number | string;
|
|
3
|
-
export type NullableId = Id | null;
|
|
4
|
-
export type CallFindResult<T = AnyObj> = {
|
|
5
|
-
total: number;
|
|
6
|
-
limit: number;
|
|
7
|
-
skip: number;
|
|
8
|
-
data: Array<T>;
|
|
9
|
-
};
|
|
10
|
-
export type AnyParams = Iterable<AnyObj>;
|
|
11
|
-
declare type CoreOpts = {
|
|
12
|
-
skipJoins?: boolean;
|
|
13
|
-
admin_pass?: boolean;
|
|
14
|
-
};
|
|
15
|
-
export declare class CoreCall {
|
|
16
|
-
context: any;
|
|
17
|
-
service: string;
|
|
18
|
-
core: AnyObj;
|
|
19
|
-
entity: string;
|
|
20
|
-
constructor(service: string, context: any, coreOptions?: CoreOpts);
|
|
21
|
-
get(id: NullableId, params?: AnyObj): Promise<any>;
|
|
22
|
-
find(params?: AnyObj): Promise<any>;
|
|
23
|
-
create(data: AnyObj, params?: AnyObj): Promise<any>;
|
|
24
|
-
patch(id: NullableId, data: AnyObj, params?: AnyObj): Promise<any>;
|
|
25
|
-
update(id: NullableId, data: AnyObj, params?: AnyObj): Promise<any>;
|
|
26
|
-
remove(id: NullableId, params?: AnyObj): Promise<any>;
|
|
27
|
-
_get(id: NullableId, params?: AnyObj): Promise<any>;
|
|
28
|
-
_find(params?: AnyObj): Promise<any>;
|
|
29
|
-
_create(data: AnyObj, params?: AnyObj): Promise<any>;
|
|
30
|
-
_patch(id: NullableId, data: AnyObj, params?: AnyObj): Promise<any>;
|
|
31
|
-
_update(id: NullableId, data: AnyObj, params?: AnyObj): Promise<any>;
|
|
32
|
-
_remove(id: NullableId, params?: AnyObj): Promise<any>;
|
|
33
|
-
}
|
|
34
|
-
export {};
|
package/lib/core.cjs
DELETED
package/lib/core.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './core/index.js';
|
package/lib/env/version.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const VERSION = "0.1.7";
|
package/lib/hooks/index.d.ts
DELETED
package/lib/hooks/index.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
// Hooks Module
|
|
2
|
-
import {
|
|
3
|
-
ucanAuth,
|
|
4
|
-
allUcanAuth,
|
|
5
|
-
noThrowAuth,
|
|
6
|
-
bareAuth,
|
|
7
|
-
updateUcan,
|
|
8
|
-
anyAuth,
|
|
9
|
-
noThrow
|
|
10
|
-
} from '../index.module.js';
|
|
11
|
-
export {
|
|
12
|
-
ucanAuth,
|
|
13
|
-
allUcanAuth,
|
|
14
|
-
noThrowAuth,
|
|
15
|
-
bareAuth,
|
|
16
|
-
updateUcan,
|
|
17
|
-
anyAuth,
|
|
18
|
-
noThrow
|
|
19
|
-
};
|
package/lib/hooks/ucan-auth.d.ts
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { AnyObj, HookContext } from '../types';
|
|
2
|
-
import { Capability, VerifyOptions } from 'symbol-ucan';
|
|
3
|
-
export type UcanAuthConfig = {
|
|
4
|
-
entity: string;
|
|
5
|
-
service: string;
|
|
6
|
-
client_ucan: string;
|
|
7
|
-
ucan_aud: string;
|
|
8
|
-
ucan_path: string;
|
|
9
|
-
core_path: string;
|
|
10
|
-
defaultHierPart: string;
|
|
11
|
-
defaultScheme: string;
|
|
12
|
-
};
|
|
13
|
-
type AnyAuth = '*';
|
|
14
|
-
export declare const anyAuth: AnyAuth;
|
|
15
|
-
type NoThrow = '$';
|
|
16
|
-
export declare const noThrow: NoThrow;
|
|
17
|
-
export type CapabilityParts = Partial<Capability> | [string, Array<string> | string];
|
|
18
|
-
export declare type LoginPassOption = [Array<string>, Array<string> | '*'];
|
|
19
|
-
export declare type UcanAuthOptions = {
|
|
20
|
-
creatorPass?: '*' | Array<string>;
|
|
21
|
-
loginPass?: Array<LoginPassOption>;
|
|
22
|
-
or?: '*' | Array<string>;
|
|
23
|
-
adminPass?: Array<string>;
|
|
24
|
-
noThrow?: boolean;
|
|
25
|
-
log?: boolean;
|
|
26
|
-
existingParams?: AnyObj;
|
|
27
|
-
specialChange?: Array<string> | AnyAuth;
|
|
28
|
-
cap_subjects?: Array<string>;
|
|
29
|
-
audience?: string;
|
|
30
|
-
};
|
|
31
|
-
type RequiredCapability = {
|
|
32
|
-
capability: Capability;
|
|
33
|
-
rootIssuer: string;
|
|
34
|
-
};
|
|
35
|
-
export type UcanCap = Array<CapabilityParts> | AnyAuth | NoThrow;
|
|
36
|
-
export type UcanAllArgs = {
|
|
37
|
-
all?: UcanCap;
|
|
38
|
-
get?: UcanCap;
|
|
39
|
-
find?: UcanCap;
|
|
40
|
-
create?: UcanCap;
|
|
41
|
-
patch?: UcanCap;
|
|
42
|
-
update?: UcanCap;
|
|
43
|
-
remove?: UcanCap;
|
|
44
|
-
};
|
|
45
|
-
type VerifyOne = {
|
|
46
|
-
ucan: string;
|
|
47
|
-
} & VerifyOptions;
|
|
48
|
-
type VerifyRes = {
|
|
49
|
-
ok: boolean;
|
|
50
|
-
value?: Array<any>;
|
|
51
|
-
err?: Array<any>;
|
|
52
|
-
};
|
|
53
|
-
export declare const noThrowAuth: <S>(context: HookContext<S>) => Promise<HookContext<S>>;
|
|
54
|
-
export declare const bareAuth: <S>(context: HookContext<S>) => Promise<HookContext<S>>;
|
|
55
|
-
export declare const orVerifyLoop: (arr: Array<VerifyOne>, log?: boolean) => Promise<VerifyRes>;
|
|
56
|
-
export type VerifyConfig = {
|
|
57
|
-
client_ucan: string;
|
|
58
|
-
ucan_aud: string;
|
|
59
|
-
[key: string]: any;
|
|
60
|
-
};
|
|
61
|
-
export declare const verifyAgainstReqs: <S>(reqs: Array<RequiredCapability>, config: VerifyConfig, options?: UcanAuthOptions) => (context: HookContext<S>) => Promise<VerifyRes>;
|
|
62
|
-
export type CapabilityModelConfig = {
|
|
63
|
-
defaultScheme: string;
|
|
64
|
-
defaultHierPart: string;
|
|
65
|
-
secret: string;
|
|
66
|
-
[key: string]: any;
|
|
67
|
-
};
|
|
68
|
-
export declare const modelCapabilities: (reqs: Array<CapabilityParts>, config: CapabilityModelConfig) => Array<RequiredCapability>;
|
|
69
|
-
export declare type PassConfig = {
|
|
70
|
-
loginConfig?: VerifyConfig;
|
|
71
|
-
};
|
|
72
|
-
export declare const checkUcan: (requiredCapabilities: UcanCap, options?: UcanAuthOptions & PassConfig) => (context: HookContext) => Promise<HookContext>;
|
|
73
|
-
export declare const ucanAuth: <S>(requiredCapabilities?: UcanCap, options?: UcanAuthOptions) => (context: HookContext<S>) => Promise<HookContext<S>>;
|
|
74
|
-
export declare const allUcanAuth: <S>(methods: UcanAllArgs, options?: UcanAuthOptions) => (context: HookContext<S>) => Promise<HookContext<S>>;
|
|
75
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const updateUcan: () => (context: any) => Promise<any>;
|
package/lib/hooks.cjs
DELETED
package/lib/hooks.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './hooks/index.js';
|
package/lib/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var e=require("symbol-ucan"),t=require("@feathersjs/authentication");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=/*#__PURE__*/n(require("long-timeout"));function i(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return i=function(e){this.s=e,this.n=e.next},i.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new i(e)}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o.apply(this,arguments)}function a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,u(e,t)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function u(e,t){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},u(e,t)}function s(e,t,n){return s=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&u(i,n.prototype),i},s.apply(null,arguments)}function l(e){var t="function"==typeof Map?new Map:void 0;return l=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return s(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),u(n,e)},l(e)}function f(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t.indexOf(n=o[r])>=0||(i[n]=e[n]);return i}function h(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function p(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return h(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?h(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var v=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return a(t,e),t}(/*#__PURE__*/l(Error)),d=/(\S+)\s+(\S+)/,y=/*#__PURE__*/function(t){function n(){for(var e,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(e=t.call.apply(t,[this].concat(r))||this).expirationTimers=new WeakMap,e}a(n,t);var i,c,u=n.prototype;return u.setAuthentication=function(e){e.verifyAccessToken=function(e){return{}},t.prototype.setAuthentication.call(this,e)},u.handleConnection=function(t,n,i){try{var o=this,a="logout"===t&&n.authentication&&i&&n.authentication.accessToken===i.accessToken,c=(i||{}).accessToken,u=function(){if(c&&"login"===t)return Promise.resolve(e.validateUcan(c).catch(function(e){console.log("Could not validate ucan in connection: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(e){var t=1e3*(e||{payload:{exp:0}}).payload.exp-Date.now(),i=r.default.setTimeout(function(){return o.app.emit("disconnect",n)},t);r.default.clearTimeout(o.expirationTimers.get(n)),o.expirationTimers.set(n,i),n.authentication={strategy:o.name,accessToken:c}});("disconnect"===t||a)&&(delete n[o.configuration.entity],delete n.authentication,r.default.clearTimeout(o.expirationTimers.get(n)),o.expirationTimers.delete(n))}();return Promise.resolve(u&&u.then?u.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},u.verifyConfiguration=function(){for(var e=["entity","entityId","service","header","schemes","audience"],t=0,n=Object.keys(this.configuration);t<n.length;t++){var r=n[t];if(!e.includes(r))throw new Error("Invalid ucanStrategy option 'authentication."+this.name+"."+r+"'. Did you mean to set it in 'authentication.jwtOptions'?")}if("string"!=typeof this.configuration.header)throw new Error("The 'header' option for the "+this.name+" strategy must be a string")},u.getEntityQuery=function(e){return Promise.resolve({})},u.getEntity=function(t,n){try{var r=this,i=r.entityService,a=r.configuration.entity;if(null===i)throw new v("Could not find entity service");return Promise.resolve(r.getEntityQuery(n)).then(function(r){var c=Object.assign({},e._unset(n,"provider"),{query:r});return Promise.resolve(i.get(t,c)).then(function(e){var r;return n.provider?i.get(t,o({},n,((r={})[a]=e,r))):e})})}catch(e){return Promise.reject(e)}},u.getEntityId=function(e,t){try{var n=t.query,r=t.loginId;if(r)return Promise.resolve(r);var i,a,c=this.configuration,u=c.service,s=c.core_path,l=void 0===s?"core":s,f=((i={query:o({},n,{$limit:1})})[l]=o({skipJoins:!0},t[l]),i);return Promise.resolve(null==(a=this.app)?void 0:a.service(u).find(o({},f,{skipJoins:!0,skip_hooks:!0,admin_pass:!0}))).then(function(e){if(e.total)return e.data[0]._id;throw new v("Could not find login associated with this ucan")})}catch(e){return Promise.reject(e)}},u.authenticate=function(t,n){try{var r=this,i=t.accessToken,a=t.loginId,c=t.ucan,u=r.configuration,s=u.entity,l=u.core_path;if(!i){if(!c)throw new v("Error generating ucan");i=e.ucanToken(c)}return Promise.resolve(e.validateUcan(i).catch(function(e){console.log("Could not validate ucan during authentication: ",e.message);var t={code:0,message:"Unknown Issue Validating Ucan"};throw e.message.indexOf("Expired.")>-1&&(t.code=1,t.message="Expired Ucan"),new Error(t.message)})).then(function(t){function c(){var e;return o({},f,((e={})[s]=u,e))}var u,f={accessToken:i,authentication:{strategy:"jwt",accessToken:i}};if(null===s)return f;var h=e._get(n,[l,s]),p=function(){if(!h)return Promise.resolve(r.getEntityId(f,o({},n,{loginId:a,query:{did:null==t?void 0:t.payload.aud}}))).then(function(e){return Promise.resolve(r.getEntity(e,n)).then(function(e){u=e})});u=h}();return p&&p.then?p.then(c):c()})}catch(e){return Promise.reject(e)}},u.parse=function(e){try{var t=this.configuration,n=t.schemes,r=e.headers&&e.headers[t.header.toLowerCase()];if(!r||"string"!=typeof r)return Promise.resolve(null);var i=r.match(d)||[],o=i[1],a=i[2],c=o&&n.some(function(e){return new RegExp(e,"i").test(o)});return Promise.resolve(o&&!c?null:{strategy:this.name,accessToken:c?a:r})}catch(e){return Promise.reject(e)}},i=n,(c=[{key:"configuration",get:function(){var e,n=(null==(e=this.authentication)?void 0:e.configuration)||{service:void 0,entity:void 0,entityId:void 0};return o({service:n.service,entity:n.entity,entityId:n.entityId,header:"Authorization",schemes:["Bearer","JWT"]},t.prototype.configuration)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,"symbol"==typeof(i=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(r.key))?i:String(i),r)}var i}(i.prototype,c),Object.defineProperty(i,"prototype",{writable:!1}),n}(t.AuthenticationBaseStrategy),g=["NotAuthenticated"],m=/*#__PURE__*/function(e){function t(t){return e.call(this,t)||this}return a(t,e),t}(/*#__PURE__*/l(Error)),P=/*#__PURE__*/function(t){function n(e,n,r){var i;void 0===n&&(n="authentication"),void 0===r&&(r={});var o=r.NotAuthenticated,a=f(r,g);return(i=t.call(this,e,n,a)||this).options=void 0,i.app=e,i.options={NotAuthenticated:o},i}return a(n,t),n.prototype.create=function(t,n){try{var r,i,a=this,c=(null==(r=a.options)?void 0:r.NotAuthenticated)||m,u=a.app.get("authentication"),s=u.entity,l=u.service,f=u.ucan_path,h=void 0===f?"ucan":f,p=(null==(i=n)?void 0:i.authStrategies)||a.configuration.authStrategies;if(n||(n={}),!p.length)throw new c("No authentication strategies allowed for creating a JWT (`authStrategies`)");return Promise.resolve(a.authenticate.apply(a,[t,n].concat(p)).catch(function(e){throw new Error(e.message)})).then(function(r){if(r.accessToken)return r;var i=t.did||e._get(r,[s,"did"]),c=t.ucan||e._get(r,[s,"ucan"]);if(!i)throw new Error("No did audience provided");if(!c)throw new Error("No ucan provided to authentication call");return Promise.resolve(e.validateUcan(c).catch(function(e){console.log("Could not validate ucan creating authentication: ",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 creating authentication",c,t.message),null})).then(function(t){function i(){var t=e.ucanToken(c);return o({accessToken:t},r,{authentication:o({},r.authentication,{payload:t})})}var u=function(){if(!t){var i=e.parseUcan(c),u=a.app.get("authentication"),f=e.encodeKeyPair({secretKey:u.secret});return Promise.resolve(e.buildUcan({audience:i.payload.aud,issuer:f,lifetimeInSeconds:5184e3,capabilities:i.payload.att})).then(function(t){var i;return c=t,n.admin_pass=!0,Promise.resolve(a.app.service(l).patch(e._get(r,[s,"_id"]),(i={},i[h]=e.ucanToken(c),i),o({},n))).then(function(){})})}}();return u&&u.then?u.then(i):i()})})}catch(e){return Promise.reject(e)}},n}(t.AuthenticationService),_=/*#__PURE__*/function(){function e(e,t,n){var r;this.context=void 0,this.service=void 0,this.core=void 0,this.entity=void 0,this.service=e,this.context=t;var i=(t.app.get("authentication")||{entity:"login"}).entity||"login";this.entity=i;var a=(null==(r=t.params)?void 0:r.core)||{};a[i]||(a[i]=t.params[i]),this.core=o({},a,n)}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t={});try{var n,r,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service).get(e,o({},t,((r={})[a.entity]=t[a.entity],r),((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t.find=function(e){void 0===e&&(e={});try{var t,n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(t=i.context.app)?void 0:t.service(i.service).find(o({},e,((n={})[i.entity]=e[i.entity],n.skip_hooks=!0,n.admin_pass=!0,n),((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t.create=function(e,t){void 0===t&&(t={});try{var n,r,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service).create(e,o({},t,((r={})[a.entity]=t[a.entity],r),((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t.patch=function(e,t,n){void 0===n&&(n={});try{var r,i,a,c=this,u=c.context.app.get("authentication").core_path;return Promise.resolve(null==(r=c.context.app)?void 0:r.service(c.service).patch(e,t,o({},n,((i={})[c.entity]=n[c.entity],i),((a={})[u]=c.core,a))))}catch(e){return Promise.reject(e)}},t.update=function(e,t,n){void 0===n&&(n={});try{var r,i,a,c=this,u=c.context.app.get("authentication").core_path;return Promise.resolve(null==(r=c.context.app)?void 0:r.service(c.service).update(e,t,o({},n,((i={})[c.entity]=n[c.entity],i),((a={})[u]=c.core,a))))}catch(e){return Promise.reject(e)}},t.remove=function(e,t){void 0===t&&(t={});try{var n,r,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service).remove(e,o({},t,((r={})[a.entity]=t[a.entity],r),((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._get=function(e,t){void 0===t&&(t={});try{var n,r,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service)._get(e,o({},t,((r={})[a.entity]=t[a.entity],r),((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._find=function(e){void 0===e&&(e={});try{var t,n,r,i=this,a=i.context.app.get("authentication").core_path;return Promise.resolve(null==(t=i.context.app)?void 0:t.service(i.service)._find(o({},e,((n={})[i.entity]=e[i.entity],n),((r={})[a]=i.core,r))))}catch(e){return Promise.reject(e)}},t._create=function(e,t){void 0===t&&(t={});try{var n,r,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service)._create(e,o({},t,((r={})[a.entity]=t[a.entity],r),((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},t._patch=function(e,t,n){void 0===n&&(n={});try{var r,i,a,c=this,u=c.context.app.get("authentication").core_path;return Promise.resolve(null==(r=c.context.app)?void 0:r.service(c.service)._patch(e,t,o({},n,((i={})[c.entity]=n[c.entity],i),((a={})[u]=c.core,a))))}catch(e){return Promise.reject(e)}},t._update=function(e,t,n){void 0===n&&(n={});try{var r,i,a,c=this,u=c.context.app.get("authentication").core_path;return Promise.resolve(null==(r=c.context.app)?void 0:r.service(c.service)._update(e,t,o({},n,((i={})[c.entity]=n[c.entity],i),((a={})[u]=c.core,a))))}catch(e){return Promise.reject(e)}},t._remove=function(e,t){void 0===t&&(t={});try{var n,r,i,a=this,c=a.context.app.get("authentication").core_path;return Promise.resolve(null==(n=a.context.app)?void 0:n.service(a.service)._remove(e,o({},t,((r={})[a.entity]=t[a.entity],r),((i={})[c]=a.core,i))))}catch(e){return Promise.reject(e)}},e}(),b="_exists",w=function(t){var n=t.app.get("existsPath")||b;return e._get(t.params,"core."+n+"."+t.path+"."+t.id)||void 0},x=function(e,t){try{var n=w(e),r=function(){if(!n&&e.id)return Promise.resolve(new _(e.path,e,{skipJoins:!1!==(null==t?void 0:t.skipJoins)}).get(e.id,o({exists_check:!0,admin_pass:!0,skip_hooks:!0},(null==t?void 0:t.params)||{}))).then(function(e){n=e})}();return Promise.resolve(r&&r.then?r.then(function(){return n}):n)}catch(e){return Promise.reject(e)}},j=function(t,n){var r=t.app.get("existsPath")||b;return t.params=e._set(t.params,"core."+r+"."+t.path+"."+((null==n?void 0:n._id)||t.id),n),t},k=["ucan"];function S(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function A(e,t,n){if(!e.s){if(n instanceof E){if(!n.s)return void(n.o=A.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(A.bind(null,e,t),A.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}const E=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{A(r,1,e(this.v))}catch(e){A(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?A(r,1,t?t(i):i):n?A(r,1,n(i)):A(r,2,i)}catch(e){A(r,2,e)}},r},e}();function T(e){return e instanceof E&&1&e.s}function O(e,t,n){var r,i,o=-1;return function a(c){try{for(;++o<e.length&&(!n||!n());)if((c=t(o))&&c.then){if(!T(c))return void c.then(a,i||(i=A.bind(null,r=new E,2)));c=c.v}r?A(r,1,c):r=c}catch(e){A(r||(r=new E),2,e)}}(),r}function U(e,t,n){var r=[];for(var i in e)r.push(i);return O(r,function(e){return t(r[e])},n)}var C="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function I(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var q=function(n){try{var r,i=n.app.get("authentication"),o=e._get(n,["auth",i.entity]);o&&(n=e._set(n,[i.core_path,i.entity],o));var a=S(function(){return Promise.resolve(t.authenticate("jwt")(n).catch(function(){return n})).then(function(e){n=e})},function(){return r=1,n});return Promise.resolve(a&&a.then?a.then(function(e){return r?e:n}):r?a:n)}catch(e){return Promise.reject(e)}},$=function(n){try{var r=n.app.get("authentication"),i=e._get(n,["auth",r.entity]);return i&&(n=e._set(n,[r.core_path,r.entity],i)),Promise.resolve(t.authenticate("jwt")(n))}catch(e){return Promise.reject(e)}},N=function(t,n,r){try{return Promise.resolve(S(function(){return Promise.resolve(e.verifyUcan(t,n)).then(function(i){var a=function(a){if((null==(a=i)||!a.ok)&&n.requiredCapabilities){var c=n.requiredCapabilities.map(function(e){return"*"!==e.capability.can&&(e.capability.can.segments=["*"]),e});return r&&console.log("set new req capabilities",c,e.parseUcan(t)),Promise.resolve(e.verifyUcan(t,o({},n,{requiredCapabilities:c}))).then(function(e){i=e,r&&console.log("Second verification result:",i)})}}();return a&&a.then?a.then(function(){return i}):i})},function(e){return{ok:!1,err:[e.message]}}))}catch(e){return Promise.reject(e)}},K=function(t,n){try{var r={ok:!1,value:[]};return Promise.resolve(S(function(){var i,o=U(t,function(o){n&&console.log("or verify loop",t[o],e.parseUcan(t[o].ucan));var a=function(e){if(null==(e=r)||!e.ok){var a=t[o],c=a.ucan,u=f(a,k);return Promise.resolve(N(c,u,n)).then(function(e){r=e,n&&console.log("got in verify loop",r)})}i=1}();if(a&&a.then)return a.then(function(){})},function(){return i});return o&&o.then?o.then(function(){return r}):r},function(e){return{ok:!1,err:[e.message]}}))}catch(e){return Promise.reject(e)}},J=function(t,n,r){return function(i){try{var o,a=null==r?void 0:r.log,c=e._get(i.params,n.client_ucan),u=(null==r?void 0:r.audience)||e._get(i.params,n.ucan_aud);a&&console.log("verify against reqs",t);var s=(null==r?void 0:r.or)||[];return o=c&&("*"===s||s.includes(i.method))?function(e,n){return K((t||[]).map(function(t){return{ucan:e||c,audience:(null==n?void 0:n.aud)||u,requiredCapabilities:[t]}}),a)}:function(e,n){return N(e||c,{audience:(null==n?void 0:n.aud)||u,requiredCapabilities:t},a)},Promise.resolve(o()).then(function(t){var c,u;if(a&&console.log("first verify try",t),null!=(c=t)&&c.ok)return t;var s=((null==r?void 0:r.cap_subjects)||[]).filter(function(e){return!!e});a&&console.log("check cap_subjects",s);var l=function(){if(s){var c=(null==n?void 0:n.loginConfig)||i.app.get("authentication"),l=String(e._get(i.params,c.entity+"._id"||""));return Promise.resolve(new _(c.capability_service||"caps",i).find({query:{$limit:s.length,subject:{$in:s}},skip_hooks:!0,admin_pass:!0}).catch(function(e){return console.log("Error finding caps in ucan auth: "+e.message)})).then(function(n){var i;return a&&console.log("caps",n),function(){if(null!=n&&n.data)return function(e,t,n){if("function"==typeof e[C]){var r,i,o,a=e[C]();if(function e(c){try{for(;!((r=a.next()).done||n&&n());)if((c=t(r.value))&&c.then){if(!T(c))return void c.then(e,o||(o=A.bind(null,i=new E,2)));c=c.v}i?A(i,1,c):i=c}catch(e){A(i||(i=new E),2,e)}}(),a.return){var c=function(e){try{r.done||a.return()}catch(e){}return e};if(i&&i.then)return i.then(c,function(e){throw c(e)});c()}return i}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],s=0;s<e.length;s++)u.push(e[s]);return O(u,function(e){return t(u[e])},n)}(n.data,function(n){return U(n.caps||{},function(i){return a&&console.log("check cap",i,n.caps[i].logins,l),function(){if((n.caps[i].logins||[]).map(function(e){return String(e)}).includes(l)){var c=function(){var e;if(null!=r&&r.log&&console.log("tried v on cap",t),null!=(e=t)&&e.ok)return u=1,t},s=S(function(){var r=e.ucanToken(n.caps[i].ucan);a&&console.log("got ucan string",r);var c=function(){if(r)return Promise.resolve(o(r,{aud:n.did})).then(function(e){t=e,a&&console.log("tried v on cap",t)})}();if(c&&c.then)return c.then(function(){})},function(e){console.log("Error verifying ucan from cap: "+n._id+". Err:"+e.message)});return s&&s.then?s.then(c):c()}}()},function(){return i})},function(){return i})}()})}}();return l&&l.then?l.then(function(e){return u?e:t}):u?l:t})}catch(e){return Promise.reject(e)}}},R=function(t,n){var r=e.encodeKeyPair({secretKey:n.secret}).did();return Array.isArray(t)?t.map(function(t){return{capability:Array.isArray(t)?e.genCapability({with:{scheme:n.defaultScheme,hierPart:n.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},n):e.genCapability(t,n),rootIssuer:r}}):[]},M=function(t,n){return function(r){try{var o=function(){var t,o;if(null!=(t=c)&&t.ok)return r.params.authenticated=!0,r.params.canU=!0,r;if(null!=n&&n.log&&console.log("checking special change",null==n?void 0:n.specialChange),null!=n&&n.specialChange){if("*"===n.specialChange)return r.params.canU=!0,r;if(Array.isArray(n.specialChange)&&["create","patch","update"].includes(r.method)){if(Array.isArray(r.data))throw new Error("No multi data allowed with special change");for(var u in r.data||{})if(["$set","$unset","$addToSet","$pull","$push"].includes(u)){for(var s in r.data[u]||{})if(!n.specialChange.includes(s)){var l=s.split(".");1===l.length?delete r.data[u][s]:n.specialChange.includes(l[0])||delete r.data[u][s]}}else n.specialChange.includes(u)||delete r.data[u];return r.params.canU=!0,r}}if(null!=(o=c)&&o.ok)return r.params.authenticated=!0,r.params.canU=!0,r;var f=function(e){var t;if(null!=(t=c)&&t.ok)return r.params.authenticated=!0,r.params.canU=!0,r;if(null!=n&&n.log&&console.error("Ucan capabilities requirements not met: ",c,r.type,r.path),null!=n&&n.noThrow)return r.params._no_throw_error={type:r.type,method:r.method,path:r.path},r;throw new Error("Missing proper capabilities for this action: "+r.type+": "+r.path+" - "+r.method)},h=(n||{loginPass:[[["*"],["nonExistentMethod"]]]}).loginPass,v=function(){if(null!=h&&h.length){var t,o=function(t){if(_interrupt2)return t;s&&(r=e._set(r,"data",u))},u={},s=!0,l=!1,f=!1,v=I(function(){return S(function(){var t,o,f=function(e){var t,n,r,o=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);o--;){if(n&&null!=(t=e[n]))return t.call(e);if(r&&null!=(t=e[r]))return new i(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(h),v=function(e,t,n){for(var r;;){var i=e();if(T(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!T(o)){r=1;break}o=o.s}if(t){var a=t();if(a&&a.then&&!T(a)){r=2;break}}}var c=new E,u=A.bind(null,c,2);return(0===r?i.then(l):1===r?o.then(s):a.then(f)).then(void 0,u),c;function s(r){o=r;do{if(t&&(a=t())&&a.then&&!T(a))return void a.then(f).then(void 0,u);if(!(i=e())||T(i)&&!i.v)return void A(c,1,o);if(i.then)return void i.then(l).then(void 0,u);T(o=n())&&(o=o.v)}while(!o||!o.then);o.then(s).then(void 0,u)}function l(e){e?(o=n())&&o.then?o.then(s).then(void 0,u):s(o):A(c,1,o)}function f(){(i=e())?i.then?i.then(l).then(void 0,u):l(i):A(c,1,o)}}(function(){function e(e){return!t&&(l=!(o=e).done)}return t?!!e(!t&&f.next()):Promise.resolve(!t&&f.next()).then(e)},function(){return!!(l=!1)},function(){var i=o.value,l=function(){if(s)return Promise.resolve(function(t){try{var i=[],o="*"===t[1],l=-1;o?l=0:(i=t[1].map(function(e){return e.split("/")[0]}),l=i.indexOf(r.method));var f=function(){if(l>-1)return Promise.resolve(x(r,{params:null==n?void 0:n.existingParams})).then(function(n){var i=!1,f=function(t,n){void 0===n&&(n="_id");var o=e._get(r.params,a.entity+"."+n);if(o&&t){var c=Array.isArray(o)?o.map(function(e){return String(e)}):[String(o)];if(Array.isArray(t))for(var u=0;u<c.length;u++){for(var s=String(c[u]),l=0;l<t.length;)String(t[l])===s?i=!0:l++;if(i)return}else if(c.includes(String(t)))return i=!0}};if(n){r=j(r,n);for(var h,v=p(t[0]||[]);!(h=v()).done;){var d=String(h.value).split("/");if(d[0].includes("*")){var y=d[0].split("*"),g=e._get(n,y[0]);if(g&&"object"==typeof g)if(Array.isArray(g))for(var m,P=p(g);!(m=P()).done&&(f(e._get(m.value,y[1]),d[1]||"_id"),!i););else for(var _ in g)if(f(e._get(g,_+"."+y[1]),d[1]||"_id"),i)break}else f(e._get(n,d[0]),d[1]||"_id")}}if(i)if(c.ok=!0,"*"===t[1]||["find","get","remove"].some(function(e){return t[1].includes(e)}))s=!1;else{var b=o?"*":t[1][l];if(b.split("/")[0]!==b)for(var w,x=p(b.split("/").slice(1).join("").split(",")||[]);!(w=x()).done;){var k=w.value,S=e._get(r.data,k);if(S)u=e._set(u,k,S);else for(var A=0,E=["$addToSet","$pull"];A<E.length;A++){var T=E[A],O=e._get(r.data,T+"."+k);O&&(u=e._set(u,T+"."+k,O))}}else s=!1}})}();return Promise.resolve(f&&f.then?f.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}(i)).then(function(){});t=1}();return l&&l.then?l.then(function(){}):void 0});if(v&&v.then)return v.then(function(){})},function(e){f=!0,t=e})},function(e,n){function r(t){if(e)throw n;return n}var i=I(function(){var e=function(){if(l&&null!=_iterator.return)return Promise.resolve(_iterator.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,n){if(f)throw t;if(e)throw n;return n});return i&&i.then?i.then(r):r()});return v&&v.then?v.then(o):o(v)}}();return v&&v.then?v.then(f):f()},a=(null==n?void 0:n.loginConfig)||r.app.get("authentication"),c={ok:!1,value:[]},u=R(t,a),s=function(){if(u.length)return Promise.resolve(J(u,a,n)(r)).then(function(e){c=e});"*"!==t&&(c.ok=!0)}();return Promise.resolve(s&&s.then?s.then(o):o())}catch(e){return Promise.reject(e)}}},B=function(t,n){return function(r){try{var i,o,a=function(i){if(o)return i;function a(){return"*"!==t||null!=n&&n.specialChange?u?r:t?Promise.resolve(M(t,n)(r)):r:(r.params.authenticated=!!r.params[s],r)}var u=((null==n?void 0:n.adminPass)||[]).includes(r.method)&&(e._get(r.params,"admin_pass")||e._get(r.params,[c.core_path,"admin_pass"])),f=function(){if(!l)return Promise.resolve(u||null!=n&&n.specialChange?q(r):$(r)).then(function(e){r=e})}();return f&&f.then?f.then(a):a()},c=r.app.get("authentication"),u=c.core_path||"core",s=c.entity||"login",l=(e._get(r.params,[u,s])||(null==(i=r.params)?void 0:i.login)||{_id:void 0})._id;null!=n&&n.log&&console.log("ucan auth","loginId",l,"core_path",u,"entity",s,"core",r.params[u],"params login",r.params.login,"required capabilities",t);var f=function(){if("$"===t||t&&"$"===t[r.method]){var e=function(e){return o=1,e};return l?e(r):Promise.resolve(q(r)).then(e)}}();return Promise.resolve(f&&f.then?f.then(a):a(f))}catch(e){return Promise.reject(e)}}};exports.AuthService=P,exports.CoreCall=_,exports.NotAuthError=m,exports.UcanStrategy=y,exports.allUcanAuth=function(t,n){return function(r){try{var i=r.app.get("authentication"),o=e._get(r,["auth",i.entity]);if(o&&(r=e._set(r,[i.core_path,i.entity],o)),"before"===r.type){var a=r.method;return Promise.resolve(t[a]||t.all?B(t[a]||t.all,n)(r):r)}return Promise.resolve(r)}catch(e){return Promise.reject(e)}}},exports.anyAuth="*",exports.bareAuth=$,exports.checkUcan=M,exports.existsPath=b,exports.getExists=w,exports.loadExists=x,exports.modelCapabilities=R,exports.noThrow="$",exports.noThrowAuth=q,exports.orVerifyLoop=K,exports.setExists=j,exports.ucanAuth=B,exports.updateUcan=function(){return function(t){try{var n=t.data,r=n.add,i=void 0===r?[]:r,a=n.remove,c=void 0===a?[]:a;if(!(null!=i&&i.length||null!=c&&c.length))throw new Error("No new capabilities passed");var u=t.app.get("authentication"),s=u.secret,l=u.ucan_aud,f=u.entity,h=u.ucan,p=e.encodeKeyPair({secretKey:s}).did(),v=e.stackAbilities([].concat(i,c));return Promise.resolve(e.verifyUcan(e._get(t.params,[f,h]),{audience:e._get(t.params,l),requiredCapabilities:v.map(function(e){return{capability:e,rootIssuer:p}})})).then(function(n){if(null==n||!n.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");var r=t.id,a=t.data.service||"logins",u=t.data.path||"ucan";return Promise.resolve(new _(a,t,{skipJoins:!0}).get(r)).then(function(n){var l=e.parseUcan(e._get(n,u)).payload,f=l.aud,h=l.att,p=l.prf,v=[].concat(h);return null!=c&&c.length&&(v=e.reduceAbilities(c,h)),null!=i&&i.length&&(v=e.stackAbilities([].concat(h,i))),Promise.resolve(e.buildUcan(o({issuer:e.encodeKeyPair({secretKey:s}),audience:f,lifetimeInSeconds:5184e3,proofs:p},t.data,{capabilities:v}))).then(function(n){var i=e.ucanToken(n);return Promise.resolve(e.validateUcan(i)).then(function(e){var n;if(!e)throw new Error("Invalid ucan generated when updating");return Promise.resolve(new _(a,t).patch(r,(n={},n[u]=i,n))).then(function(e){return t.result={raw:t.data,encoded:i,subject:e},t})})})})})}catch(e){return Promise.reject(e)}}},exports.verifyAgainstReqs=J;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
package/lib/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/auth-service/ucan-strategy.ts","../src/auth-service/index.ts","../src/core/methods.ts","../src/utils/check-exists.ts","../src/hooks/ucan-auth.ts","../src/hooks/update-ucan.ts"],"sourcesContent":["import {IncomingMessage} from 'http';\nimport {\n AuthenticationBase,\n AuthenticationBaseStrategy,\n AuthenticationRequest,\n AuthenticationResult,\n ConnectionEvent\n} from '@feathersjs/authentication';\n// @ts-ignore\nimport lt from 'long-timeout';\nimport {_get, _unset, ucanToken, validateUcan} from 'symbol-ucan';\n\nexport class NotAuthError extends Error {\n constructor(message?: string) {\n super(message)\n }\n}\nconst SPLIT_HEADER = /(\\S+)\\s+(\\S+)/;\n\ntype AnyObj = { [key: string]: any };\n\nexport class UcanStrategy extends AuthenticationBaseStrategy {\n expirationTimers = new WeakMap();\n\n setAuthentication(auth: AuthenticationBase) {\n // console.log('set authentication', auth);\n auth.verifyAccessToken = (accessToken: string) => {\n return {} as any;\n };\n super.setAuthentication(auth);\n }\n\n get configuration() {\n const authConfig = this.authentication?.configuration || {\n service: undefined,\n entity: undefined,\n entityId: undefined\n };\n const config = super.configuration;\n\n return {\n service: authConfig.service,\n entity: authConfig.entity,\n entityId: authConfig.entityId,\n header: 'Authorization',\n schemes: ['Bearer', 'JWT'],\n ...config\n };\n }\n\n async handleConnection(event: ConnectionEvent, connection: any, authResult?: AuthenticationResult) {\n const isValidLogout = event === 'logout' && connection.authentication && authResult &&\n connection.authentication.accessToken === authResult.accessToken;\n\n const {accessToken, entity} = authResult || {};\n\n if (accessToken && event === 'login') {\n const validUcan = await validateUcan(accessToken)\n .catch(err => {\n console.log('Could not validate ucan in connection: ', err.message);\n const errObj = {\n code: 0,\n message: 'Unknown Issue Validating Ucan'\n };\n if (err.message.indexOf('Expired.') > -1) {\n errObj.code = 1;\n errObj.message = 'Expired Ucan'\n }\n throw new Error(errObj.message);\n });\n const {payload: {exp}} = validUcan || {payload: {exp: 0}}\n // The time (in ms) until the token expires\n const duration = (exp * 1000) - Date.now();\n // This may have to be a `logout` event but right now we don't want\n // the whole context object lingering around until the timer is gone\n const timer = lt.setTimeout(() => (this.app as any).emit('disconnect', connection), duration);\n\n lt.clearTimeout(this.expirationTimers.get(connection));\n this.expirationTimers.set(connection, timer);\n\n connection.authentication = {\n strategy: this.name,\n accessToken\n };\n } else if (event === 'disconnect' || isValidLogout) {\n const {entity} = this.configuration;\n\n delete connection[entity];\n delete connection.authentication;\n\n lt.clearTimeout(this.expirationTimers.get(connection));\n this.expirationTimers.delete(connection);\n }\n }\n\n verifyConfiguration() {\n const allowedKeys = ['entity', 'entityId', 'service', 'header', 'schemes', 'audience'];\n\n for (const key of Object.keys(this.configuration)) {\n if (!allowedKeys.includes(key)) {\n throw new Error(`Invalid ucanStrategy option 'authentication.${this.name}.${key}'. Did you mean to set it in 'authentication.jwtOptions'?`);\n }\n }\n\n if (typeof this.configuration.header !== 'string') {\n throw new Error(`The 'header' option for the ${this.name} strategy must be a string`);\n }\n }\n\n // eslint-disable-next-line no-unused-vars\n async getEntityQuery(_params: any) {\n return {};\n }\n\n /**\n * Return the entity for a given id\n * @param id The id to use\n * @param params Service call parameters\n */\n async getEntity(id: string, params: any) {\n const entityService = this.entityService;\n const {entity} = this.configuration;\n\n if (entityService === null) {\n throw new NotAuthError('Could not find entity service');\n }\n\n const query = await this.getEntityQuery(params);\n const getParams = Object.assign({}, _unset(params, 'provider'), {query});\n const result = await entityService.get(id, getParams);\n\n if (!params.provider) {\n return result;\n }\n\n return entityService.get(id, {...params, [entity]: result});\n }\n\n async getEntityId(authResult: AuthenticationResult, _params: AnyObj) {\n let {query, loginId} = _params;\n if (loginId) return loginId;\n else {\n const {service, core_path = 'core'} = this.configuration;\n const pms = {\n query: {...query, $limit: 1},\n [core_path]: {skipJoins: true, ..._params[core_path]}\n }\n const entities = await this.app?.service(service).find({...pms, skipJoins: true, skip_hooks: true, admin_pass: true} as any);\n if (entities.total) return entities.data[0]._id;\n else throw new NotAuthError('Could not find login associated with this ucan');\n }\n }\n\n async authenticate(authentication: AuthenticationRequest, params: AnyObj) {\n let {accessToken, loginId, ucan} = authentication;\n const {entity, core_path} = this.configuration;\n if (!accessToken) {\n\n if (ucan) accessToken = ucanToken(ucan);\n else throw new NotAuthError('Error generating ucan');\n // } else throw new NotAuthenticated('No access token');\n }\n //\n // await verifyUcan(accessToken, {audience: ucan_audience || params.ucan_aud, requiredCapabilities})\n // .catch(err => {\n // console.error('error verifying ucan', err);\n // throw new NotAuthenticated('Could not verify ucan: ' + err.message);\n // });\n\n const decodedUcan = await validateUcan(accessToken)\n .catch(err => {\n console.log('Could not validate ucan during authentication: ', err.message);\n const errObj = {\n code: 0,\n message: 'Unknown Issue Validating Ucan'\n };\n if (err.message.indexOf('Expired.') > -1) {\n errObj.code = 1;\n errObj.message = 'Expired Ucan'\n }\n throw new Error(errObj.message);\n });\n\n const result = {\n accessToken,\n authentication: {\n strategy: 'jwt',\n accessToken\n }\n };\n\n if (entity === null) {\n return result;\n }\n\n let value;\n const coreEntity = _get(params, [core_path, entity]);\n if (!coreEntity) {\n const entityId = await this.getEntityId(result, {\n ...params,\n loginId,\n query: {did: decodedUcan?.payload.aud}\n });\n value = await this.getEntity(entityId, params);\n } else value = coreEntity;\n return {\n ...result,\n [entity]: value\n };\n\n }\n\n async parse(req: IncomingMessage) {\n const {header, schemes} = this.configuration;\n const headerValue = req.headers && req.headers[header.toLowerCase()];\n\n if (!headerValue || typeof headerValue !== 'string') {\n return null;\n }\n\n const [, scheme, schemeValue] = headerValue.match(SPLIT_HEADER) || [];\n const hasScheme = scheme && schemes.some(\n (current: any) => new RegExp(current, 'i').test(scheme)\n );\n\n if (scheme && !hasScheme) {\n return null;\n }\n\n return {\n strategy: this.name,\n accessToken: hasScheme ? schemeValue : headerValue\n };\n }\n}\n\n\n","import {_get, buildUcan, encodeKeyPair, parseUcan, ucanToken, validateUcan} from 'symbol-ucan';\nimport {AuthenticationParams, AuthenticationRequest, AuthenticationService} from '@feathersjs/authentication';\nimport {AnyObj} from '../types';\nimport {NullableId} from '../core';\n\nexport class NotAuthError extends Error {\n constructor(message?: string) {\n super(message)\n }\n}\nexport type AuthServiceOptions = {\n NotAuthenticated?: any\n}\nexport * from './ucan-strategy';\n\nexport class AuthService extends AuthenticationService {\n options: AuthServiceOptions\n constructor(app: any, configKey = 'authentication', opts:AnyObj&AuthServiceOptions = {}) {\n const { NotAuthenticated, ...rest } = opts\n super(app, configKey, rest)\n this.app = app;\n this.options = { NotAuthenticated }\n };\n\n async create(data: AuthenticationRequest, params?: AuthenticationParams) {\n const NotAuth = this.options?.NotAuthenticated || NotAuthError;\n\n const {entity, service, ucan_path = 'ucan'} = this.app.get('authentication');\n\n const authStrategies = params?.authStrategies || this.configuration.authStrategies\n\n if (!params) params = {}\n\n if (!authStrategies.length) {\n throw new NotAuth('No authentication strategies allowed for creating a JWT (`authStrategies`)')\n }\n\n const authResult = await this.authenticate(data, params, ...authStrategies)\n .catch((err: any) => {\n throw new Error(err.message)\n })\n\n if (authResult.accessToken) {\n return authResult\n }\n const did = data.did || _get(authResult, [entity, 'did']);\n let ucan = data.ucan || _get(authResult, [entity, 'ucan']);\n\n if (!did) throw new Error('No did audience provided');\n if (!ucan) throw new Error('No ucan provided to authentication call');\n // const {secret} = this.configuration;\n\n const validatedUcan = await validateUcan(ucan)\n .catch(err => {\n console.log('Could not validate ucan creating authentication: ', err.message);\n const errObj = {\n code: 0,\n message: 'Unknown Issue Validating Ucan'\n };\n if (err.message.indexOf('Expired.') > -1) {\n errObj.code = 1;\n errObj.message = 'Expired Ucan'\n }\n console.warn('Could not validate ucan creating authentication', ucan, errObj.message);\n return null;\n });\n if (!validatedUcan) {\n const parsed = parseUcan(ucan);\n let {secret} = this.app.get('authentication');\n\n const issuer = encodeKeyPair({secretKey: secret});\n ucan = await buildUcan({\n audience: parsed.payload.aud,\n issuer,\n lifetimeInSeconds: 60 * 60 * 24 * 60,\n capabilities: parsed.payload.att\n })\n params.admin_pass = true;\n await this.app.service(service).patch(_get(authResult, [entity, '_id']) as NullableId, {[ucan_path]: ucanToken(ucan)}, {...params})\n }\n\n\n const accessToken = ucanToken(ucan);\n\n return {\n accessToken,\n ...authResult,\n authentication: {\n ...authResult.authentication,\n payload: accessToken\n }\n }\n }\n}\n\n","import {AnyObj} from '../types';\n\nexport type Id = number | string\nexport type NullableId = Id | null\n\nexport type CallFindResult<T = AnyObj> = {\n total:number,\n limit: number,\n skip:number,\n data: Array<T>\n}\nexport type AnyParams = Iterable<AnyObj>\n\ndeclare type CoreOpts = {\n skipJoins?: boolean,\n admin_pass?: boolean\n}\nexport class CoreCall {\n context:any;\n service:string;\n core:AnyObj;\n entity:string;\n constructor(service:string, context:any, coreOptions?:CoreOpts){\n this.service = service\n this.context = context\n const entity = (context.app.get('authentication') || { entity: 'login' }).entity || 'login';\n this.entity = entity;\n const core = context.params?.core || {};\n if(!core[entity]) core[entity] = context.params[entity];\n this.core = { ...core, ...coreOptions }\n }\n\n async get(id:NullableId, params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service).get(id, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async find (params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service).find({...params as AnyParams, [this.entity]: params[this.entity], skip_hooks:true, admin_pass:true, ...{ [core_path]: this.core }})\n }\n async create (data:AnyObj, params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service).create(data, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async patch (id:NullableId, data:AnyObj, params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service).patch(id, data, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async update (id:NullableId, data:AnyObj, params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service).update(id, data, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async remove (id:NullableId, params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service).remove(id, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n\n async _get(id:NullableId, params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service)._get(id, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async _find (params:AnyObj = {}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service)._find({...params as AnyParams, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async _create (data:AnyObj, params:AnyObj ={}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service)._create(data, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async _patch (id:NullableId, data:AnyObj, params:AnyObj ={}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service)._patch(id, data, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async _update (id:NullableId, data:AnyObj, params:AnyObj ={}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service)._update(id, data, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n async _remove (id:NullableId, params:AnyObj ={}){\n const {core_path} = this.context.app.get('authentication');\n return this.context.app?.service(this.service)._remove(id, {...params, [this.entity]: params[this.entity], ...{ [core_path]: this.core }})\n }\n\n}\n\n","import {_get, _set} from 'symbol-ucan';\nimport {AnyObj, HookContext} from '../types';\nimport {CoreCall} from '../core';\n\nexport const existsPath = '_exists';\n\nexport const getExists = (context:Partial<HookContext>):any => {\n const path = context.app.get('existsPath') || existsPath;\n return _get(context.params, `core.${path}.${context.path}.${context.id}`) || undefined;\n}\n\nexport const loadExists = async (context:HookContext, options?:{ skipJoins?: boolean, params?: AnyObj }):Promise<any> => {\n let ex = getExists(context);\n if(!ex && context.id) {\n ex = await new CoreCall(context.path, context, { skipJoins: options?.skipJoins !== false }).get(context.id, { exists_check: true, admin_pass: true, skip_hooks: true, ...options?.params || {} })\n }\n return ex;\n}\n\nexport const setExists = (context:HookContext, val:any):HookContext => {\n const path = context.app.get('existsPath') || existsPath;\n context.params = _set(context.params, `core.${path}.${context.path}.${val?._id || context.id}`, val)\n return context;\n};\n","import {AnyObj, HookContext} from '../types';\nimport {authenticate} from '@feathersjs/authentication';\nimport {\n _get,\n _set,\n Capability,\n encodeKeyPair,\n genCapability,\n parseUcan,\n ucanToken,\n VerifyOptions,\n verifyUcan\n} from 'symbol-ucan';\nimport {loadExists, setExists} from '../utils';\nimport {CoreCall} from '../core';\n\nconst SUPERUSER = '*'\n\nexport type UcanAuthConfig = {\n entity: string,\n service: string,\n client_ucan: string,\n ucan_aud: string,\n ucan_path: string,\n core_path: string,\n defaultHierPart: string,\n defaultScheme: string\n}\n\ntype AuthConfig = {\n [key: string]: string\n}\n\ntype AnyAuth = '*'\nexport const anyAuth: AnyAuth = '*' as AnyAuth;\ntype NoThrow = '$'\nexport const noThrow: NoThrow = '$' as NoThrow;\n\n\nexport type CapabilityParts = Partial<Capability> | [string, Array<string> | string];\n\nexport declare type LoginPassOption = [Array<string>, Array<string> | '*']\nexport declare type UcanAuthOptions = {\n creatorPass?: '*' | Array<string>,\n loginPass?: Array<LoginPassOption>,\n or?: '*' | Array<string>\n adminPass?: Array<string>,\n noThrow?: boolean,\n log?: boolean,\n existingParams?: AnyObj,\n specialChange?: Array<string> | AnyAuth,\n cap_subjects?: Array<string>,\n audience?: string\n\n}\ntype RequiredCapability = { capability: Capability, rootIssuer: string }\nexport type UcanCap = Array<CapabilityParts> | AnyAuth | NoThrow;\nexport type UcanAllArgs = {\n all?: UcanCap,\n get?: UcanCap,\n find?: UcanCap,\n create?: UcanCap,\n patch?: UcanCap,\n update?: UcanCap,\n remove?: UcanCap\n};\n\ntype VerifyOne = { ucan: string } & VerifyOptions;\n\ntype Auth = <S>(method: string) => (context: HookContext<S>) => Promise<HookContext<S>>\ntype Config = { entity: string, service: string, defaultScheme: string, defaultHierPart: string };\ntype VerifyRes = { ok: boolean, value?: Array<any>, err?: Array<any> };\n\nexport const noThrowAuth = async <S>(context: HookContext<S>): Promise<HookContext<S>> => {\n const config = context.app.get('authentication') as AuthConfig;\n const entity = _get(context, ['auth', config.entity]);\n if (entity) {\n context = _set(context, [config.core_path, config.entity], entity)\n }\n try {\n context = await authenticate('jwt')(context as any)\n .catch(() => {\n return context;\n })\n } catch (e) {\n return context;\n }\n return context;\n}\n\nexport const bareAuth = async <S>(context: HookContext<S>): Promise<HookContext<S>> => {\n const config = context.app.get('authentication') as AuthConfig;\n const entity = _get(context, ['auth', config.entity]);\n if (entity) context = _set(context, [config.core_path, config.entity], entity)\n return authenticate('jwt')(context as any);\n}\n\nconst verifyOne = async (ucan: string, options: VerifyOptions, log?: boolean) => {\n try {\n let v = await verifyUcan(ucan, options);\n if (!v?.ok && options.requiredCapabilities) {\n const newCapabilities = options.requiredCapabilities.map(a => {\n if (a.capability.can !== SUPERUSER) a.capability.can.segments = ['*']\n return a\n })\n if (log) console.log('set new req capabilities', newCapabilities, parseUcan(ucan))\n v = await verifyUcan(ucan, {\n ...options, requiredCapabilities: newCapabilities\n })\n if (log) console.log('Second verification result:', v);\n }\n return v;\n } catch (e: any) {\n return {ok: false, err: [e.message]}\n }\n};\nexport const orVerifyLoop = async (arr: Array<VerifyOne>, log?: boolean): Promise<VerifyRes> => {\n let v: any = {ok: false, value: []};\n\n try {\n for (const i in arr) {\n if (log) console.log('or verify loop', arr[i], parseUcan(arr[i].ucan));\n if (!v?.ok) {\n const {ucan, ...options} = arr[i];\n v = await verifyOne(ucan, options, log)\n if (log) console.log('got in verify loop', v);\n } else break;\n }\n return v;\n } catch (e: any) {\n return {ok: false, err: [e.message]}\n }\n}\n\nexport type VerifyConfig = {\n client_ucan: string,\n ucan_aud: string,\n [key: string]: any\n};\n\ntype MethodOpts = { aud?: string }\nexport const verifyAgainstReqs = <S>(reqs: Array<RequiredCapability>, config: VerifyConfig, options?: UcanAuthOptions) => {\n return async (context: HookContext<S>): Promise<VerifyRes> => {\n const log = options?.log\n const ucan = _get(context.params, config.client_ucan) as string;\n const audience = options?.audience || _get(context.params, config.ucan_aud) as string;\n if (log) console.log('verify against reqs', reqs)\n let vMethod: (uc?: string, methodOpts?: MethodOpts) => Promise<VerifyRes>\n const or = options?.or || []\n if (ucan && (or === '*' || or.includes(context.method))) vMethod = (uc?: string, methodOpts?: MethodOpts) => orVerifyLoop((reqs || []).map(a => {\n return {\n ucan: uc || ucan,\n audience: methodOpts?.aud || audience,\n requiredCapabilities: [a]\n }\n }), log)\n else vMethod = (uc?: string, methodOpts?: MethodOpts) => verifyOne(uc || ucan, {\n audience: methodOpts?.aud || audience,\n requiredCapabilities: reqs\n }, log) as Promise<VerifyRes>\n let v = await vMethod()\n if (log) console.log('first verify try', v);\n if (v?.ok) return v;\n const cs = (options?.cap_subjects || []).filter(a => !!a)\n if (log) console.log('check cap_subjects', cs);\n if (cs) {\n const configuration = config?.loginConfig || context.app.get('authentication') as AnyObj;\n const loginCheckId = String(_get(context.params, `${configuration.entity}._id` || '')) as any;\n const caps = await new CoreCall(configuration.capability_service || 'caps', context).find({\n query: {\n $limit: cs.length,\n subject: {$in: cs}\n },\n skip_hooks: true,\n admin_pass: true\n })\n .catch(err => console.log(`Error finding caps in ucan auth: ${err.message}`))\n if (log) console.log('caps', caps);\n if (caps?.data) {\n for (const cap of caps.data) {\n for (const k in cap.caps || {}) {\n if (log) console.log('check cap', k, cap.caps[k].logins, loginCheckId);\n if ((cap.caps[k].logins || []).map((a: any) => String(a)).includes(loginCheckId)) {\n try {\n const ucanString = ucanToken(cap.caps[k].ucan)\n if (log) console.log('got ucan string', ucanString);\n if (ucanString) {\n v = await vMethod(ucanString, {aud: cap.did})\n if (log) console.log('tried v on cap', v);\n }\n } catch (e: any) {\n console.log(`Error verifying ucan from cap: ${cap._id}. Err:${e.message}`)\n }\n if (options?.log) console.log('tried v on cap', v);\n if (v?.ok) return v;\n }\n }\n }\n }\n }\n return v;\n }\n}\n\nexport type CapabilityModelConfig = {\n defaultScheme: string,\n defaultHierPart: string,\n secret: string,\n [key: string]: any\n};\n\nexport const modelCapabilities = (reqs: Array<CapabilityParts>, config: CapabilityModelConfig): Array<RequiredCapability> => {\n\n const rootIssuer = encodeKeyPair({secretKey: config.secret}).did();\n if (!Array.isArray(reqs)) return []\n return reqs.map(a => {\n return {\n capability: Array.isArray(a) ? genCapability({\n with: {scheme: config.defaultScheme, hierPart: config.defaultHierPart},\n can: {namespace: a[0], segments: typeof a[1] === 'string' ? [a[1]] : a[1]}\n }, config) : genCapability(a, config),\n rootIssuer\n };\n }) as Array<RequiredCapability>\n};\n\nexport declare type PassConfig = {\n loginConfig?: VerifyConfig\n}\nexport const checkUcan = (requiredCapabilities: UcanCap, options?: UcanAuthOptions & PassConfig) => {\n return async (context: HookContext): Promise<HookContext> => {\n const configuration = options?.loginConfig || context.app.get('authentication') as AnyObj;\n\n let v: any = {ok: false, value: []};\n\n const reqs: Array<RequiredCapability> = modelCapabilities(requiredCapabilities as Array<CapabilityParts>, configuration as CapabilityModelConfig);\n\n if (reqs.length) {\n v = await verifyAgainstReqs(reqs, configuration as VerifyConfig, options)(context)\n\n /** if the anyAuth setting is used along with specialChange, a user could get through to this point despite not being authenticated, so this step does not allow a pass for anyAuth setting even though no requiredCapabilities are present - because it was intended to throw if not authenticated unless special change conditions are met */\n } else if (requiredCapabilities !== '*') v.ok = true;\n if (v?.ok) {\n context.params.authenticated = true;\n context.params.canU = true;\n return context\n } else {\n\n // if (!v?.ok) {\n // let hasSplitNamespace = false;\n // const reducedReqs: Array<RequiredCapability> = [];\n // reqs.forEach((req, i) => {\n // const splt = (_get<RequiredCapability, string>(req, 'capability.can.namespace') || '').split(':')\n // if (splt[1]) {\n // req = _set(req, 'capability.can.namespace', splt[0]);\n // hasSplitNamespace = true;\n // }\n // reducedReqs.push(req)\n // })\n // if (hasSplitNamespace) v = await verifyAgainstReqs(reqs, configuration as VerifyConfig, options)(context);\n // }\n\n\n if (options?.log) console.log('checking special change', options?.specialChange);\n if (options?.specialChange) {\n if (options.specialChange === anyAuth) {\n context.params.canU = true;\n return context;\n } else if (Array.isArray(options.specialChange)) {\n if (['create', 'patch', 'update'].includes(context.method)) {\n if (Array.isArray(context.data)) throw new Error('No multi data allowed with special change')\n for (const k in context.data || {}) {\n if (['$set', '$unset', '$addToSet', '$pull', '$push'].includes(k)) {\n for (const sk in context.data[k] || {}) {\n if (!options.specialChange.includes(sk)) {\n const spl = sk.split('.');\n if (spl.length === 1) delete context.data[k][sk];\n else if (!options.specialChange.includes(spl[0])) delete context.data[k][sk]\n }\n }\n } else if (!options.specialChange.includes(k)) delete context.data[k];\n }\n context.params.canU = true;\n return context;\n }\n }\n }\n if (v?.ok) {\n context.params.authenticated = true;\n context.params.canU = true;\n return context;\n } else {\n\n //If creator pass enabled, check to see if the auth login is the creator of the record\n const {loginPass} = options || {loginPass: [[['*'], ['nonExistentMethod']]]}\n if (loginPass?.length) {\n //object of scrubbed data object for pass that includes only limited access or full context.data object if no limits were present\n let scrubbedData: AnyObj = {};\n //scruData defaults to true - is only set to false\n let scrubData = true;\n const checkLoginPass = async (lpass: LoginPassOption) => {\n let methodsOnly = [];\n const allMethods = lpass[1] === '*';\n let methodIdx = -1;\n if (allMethods) methodIdx = 0;\n else {\n //separate out any field specific methods e.g. patch/name,avatar\n methodsOnly = (lpass[1] as string[]).map(a => a.split('/')[0]);\n methodIdx = methodsOnly.indexOf(context.method);\n }\n /**ensure loginPass is allowed for this method*/\n if (methodIdx > -1) {\n /**retrieve existing record to check ids for login id*/\n const existing = await loadExists(context, {params: options?.existingParams});\n let loginOk = false;\n\n /** function for comparing record login id with context login*/\n const checkLogin = (recordLoginPassId: string, loginIdPath: string = '_id') => {\n const loginCheckId = _get(context.params, `${configuration.entity}.${loginIdPath}`) as any;\n /**Make sure both are present to avoid pass on undefined*/\n if (loginCheckId && recordLoginPassId) {\n /** change login path result to array no matter what */\n const checkArr = Array.isArray(loginCheckId) ? loginCheckId.map(a => String(a)) : [String(loginCheckId)];\n if (Array.isArray(recordLoginPassId)) {\n /**loop through to see if there is a match present use for loops for performance instead of some*/\n for (let i = 0; i < checkArr.length; i++) {\n const checkId = String(checkArr[i])\n for (let rl = 0; rl < recordLoginPassId.length;) {\n const rlId = String(recordLoginPassId[rl]);\n if (rlId === checkId) loginOk = true;\n else rl++;\n }\n if (loginOk) return;\n }\n } else if (checkArr.includes(String(recordLoginPassId))) {\n return loginOk = true;\n }\n } else return\n }\n\n if (existing) {\n context = setExists(context, existing);\n /**perform the check*/\n let recordLoginPassId;\n for (const passPath of lpass[0] || []) {\n const spl = String(passPath).split('/');\n if (spl[0].includes('*')) {\n const spl2 = spl[0].split('*');\n const obj = _get(existing, spl2[0]);\n if (obj && typeof obj === 'object') {\n if (Array.isArray(obj)) {\n /** IF array, iterate through array and check the sub-path */\n for (const o of obj) {\n checkLogin(_get(o, spl2[1]) as string, spl[1] || '_id');\n if (loginOk) break;\n }\n } else {\n /** IF object, iterate through object and check the sub-path */\n for (const k in obj) {\n checkLogin(_get(obj, `${k}.${spl2[1]}`) as string, spl[1] || '_id')\n if (loginOk) break;\n }\n }\n }\n\n } else checkLogin(_get(existing, spl[0]) as string, spl[1] || '_id');\n\n }\n }\n\n if (loginOk) {\n v.ok = true\n /**loginPass is true - but check for granular field permissions such as patch/owner,color,status that imply limited permission*/\n //TODO: possibly a throw option here. If loginPass is ok, it will go forward, but could send an empty or modified patch object\n if (lpass[1] !== '*' && !['find', 'get', 'remove'].some(a => lpass[1].includes(a))) {\n const currentMethod = allMethods ? '*' : lpass[1][methodIdx];\n const splitMethod = currentMethod.split('/')[0];\n //check if current method contains a split '/' signaling limited permission check\n if (splitMethod !== currentMethod) {\n //get an array of the allowed fields\n const fields = currentMethod.split('/').slice(1).join('').split(',') || [];\n\n for (const field of fields) {\n const topLevel = _get(context.data, field);\n if (topLevel) scrubbedData = _set(scrubbedData, field, topLevel);\n else {\n for (const operator of ['$addToSet', '$pull']) {\n const operatorLevel = _get(context.data, `${operator}.${field}`);\n if (operatorLevel) scrubbedData = _set(scrubbedData, `${operator}.${field}`, operatorLevel);\n }\n }\n }\n } else scrubData = false;\n } else scrubData = false;\n }\n }\n }\n\n for await (const lpass of loginPass) {\n if (scrubData) await checkLoginPass(lpass);\n else break;\n }\n if (scrubData) context = _set(context, 'data', scrubbedData);\n }\n\n if (v?.ok) {\n context.params.authenticated = true;\n context.params.canU = true;\n return context;\n } else {\n\n if (options?.log) console.error('Ucan capabilities requirements not met: ', v, context.type, context.path);\n if (!options?.noThrow) throw new Error('Missing proper capabilities for this action: ' + context.type + ': ' + context.path + ' - ' + context.method);\n else {\n context.params._no_throw_error = {\n type: context.type,\n method: context.method,\n path: context.path\n }\n return context;\n }\n }\n }\n }\n }\n}\n\nexport const ucanAuth = <S>(requiredCapabilities?: UcanCap, options?: UcanAuthOptions) => {\n return async (context: HookContext<S>): Promise<HookContext<S>> => {\n const configuration = context.app.get('authentication') as AnyObj;\n const core_path = configuration.core_path || 'core';\n const entity = configuration.entity || 'login';\n\n const {_id: loginId} = _get(context.params, [core_path, entity]) || context.params?.login || {_id: undefined}\n if (options?.log) console.log('ucan auth', 'loginId', loginId, 'core_path', core_path, 'entity', entity, 'core', context.params[core_path], 'params login', context.params.login, 'required capabilities', requiredCapabilities);\n //Below for passing through auth with no required capabilities\n if (requiredCapabilities === noThrow || (requiredCapabilities && requiredCapabilities[context.method] === noThrow)) return loginId ? context : await noThrowAuth(context);\n const adminPass = (options?.adminPass || []).includes(context.method) && (_get(context.params, 'admin_pass') || _get(context.params, [configuration.core_path, 'admin_pass'])) as any\n if (!loginId) context = (adminPass || options?.specialChange) ? await noThrowAuth(context) : await bareAuth(context);\n if (requiredCapabilities === anyAuth && !options?.specialChange) {\n context.params.authenticated = !!context.params[entity];\n return context;\n }\n if (adminPass) return context;\n if (!requiredCapabilities) return context;\n return await checkUcan(requiredCapabilities, options)(context)\n }\n}\n\nexport const allUcanAuth = <S>(methods: UcanAllArgs, options?: UcanAuthOptions) => {\n return async (context: HookContext<S>): Promise<HookContext<S>> => {\n const config = context.app.get('authentication') as AuthConfig;\n const entity = _get(context, ['auth', config.entity]);\n if (entity) context = _set(context, [config.core_path, config.entity], entity)\n if (context.type === 'before') {\n const {method} = context as { method: keyof UcanAllArgs } & HookContext<S>;\n if (methods[method as keyof UcanAllArgs] || methods['all']) {\n return await ucanAuth(methods[method] || methods['all'], options)(context) as any;\n } else return context;\n } else return context;\n }\n}\n","import {\n buildUcan,\n encodeKeyPair,\n parseUcan,\n ucanToken,\n validateUcan,\n stackAbilities,\n verifyUcan,\n reduceAbilities,\n _get\n} from 'symbol-ucan';\nimport { CoreCall } from '../core'\n\n\nexport const updateUcan = () => {\n return async (context:any) => {\n\n const { add = [], remove = [] } = context.data;\n //ensure capabilities were passed\n if(!add?.length && !remove?.length) throw new Error('No new capabilities passed');\n\n //check ability to edit the affected capabilities\n const {secret, ucan_aud, entity, ucan} = context.app.get('authentication');\n const rootIssuer = encodeKeyPair({secretKey: secret}).did();\n\n const checkAbilities = stackAbilities([...add, ...remove]);\n\n const canEdit = await verifyUcan(_get(context.params, [entity, ucan]) as string, {\n audience: _get(context.params, ucan_aud) as string,\n requiredCapabilities: checkAbilities.map(a => {\n return {\n //TODO: possibly READ shouldn't have the ability to allow others to READ\n capability: a,\n rootIssuer\n }\n })\n })\n\n if(!canEdit?.ok) throw new Error('You don\\'t have sufficient capabilities to grant those capabilities')\n\n //prep edited ucan\n const subjectId = context.id;\n const service = context.data.service || 'logins';\n const path = context.data.path || 'ucan';\n const subject = await new CoreCall(service, context, { skipJoins: true }).get(subjectId);\n\n const decoded = parseUcan(_get(subject, path) as string);\n const {aud, att, fct, nbf, prf} = decoded.payload;\n\n let capabilities = [...att];\n if(remove?.length) capabilities = reduceAbilities(remove, att);\n if(add?.length) capabilities = stackAbilities([...att, ...add]);\n\n\n const raw = await buildUcan({\n issuer: encodeKeyPair({secretKey: secret}),\n audience: aud,\n lifetimeInSeconds: 60 * 60 * 24 * 60,\n proofs: prf,\n ...context.data,\n capabilities\n });\n\n const encoded = ucanToken(raw);\n const isValid = await validateUcan(encoded);\n if (!isValid) throw new Error('Invalid ucan generated when updating');\n const patched = await new CoreCall(service, context).patch(subjectId, { [path]: encoded });\n context.result = {raw: context.data, encoded, subject: patched};\n return context;\n }\n};\n"],"names":["NotAuthError","_Error","message","call","_inheritsLoose","_wrapNativeSuper","Error","SPLIT_HEADER","UcanStrategy","_AuthenticationBaseSt","_this","_len","arguments","length","args","Array","_key","apply","this","concat","expirationTimers","WeakMap","_proto","prototype","setAuthentication","auth","verifyAccessToken","accessToken","handleConnection","event","connection","authResult","_this2","isValidLogout","authentication","_temp","Promise","resolve","validateUcan","err","console","log","errObj","code","indexOf","then","validUcan","duration","payload","exp","Date","now","timer","lt","setTimeout","app","emit","clearTimeout","get","set","strategy","name","configuration","entity","e","reject","verifyConfiguration","allowedKeys","_i","_Object$keys","Object","keys","key","includes","header","getEntityQuery","_params","getEntity","id","params","_this3","entityService","query","getParams","assign","_unset","result","_extends2","provider","_extends","getEntityId","loginId","_pms","_this4$app","_this4$configuration","service","_this4$configuration$","core_path","pms","$limit","skipJoins","find","skip_hooks","admin_pass","entities","total","data","_id","authenticate","_this5","ucan","_this5$configuration","ucanToken","decodedUcan","_temp3","_extends3","value","coreEntity","_get","_temp2","did","aud","entityId","_this5$getEntity","parse","req","_this6$configuration","schemes","headerValue","headers","toLowerCase","_ref3","match","scheme","schemeValue","hasScheme","some","current","RegExp","test","_this$authentication","authConfig","undefined","AuthenticationBaseStrategy","_excluded","AuthService","_AuthenticationServic","configKey","opts","NotAuthenticated","rest","_objectWithoutPropertiesLoose","options","create","_this2$options","NotAuth","_this2$app$get","_this2$app$get$ucan_p","ucan_path","authStrategies","warn","validatedUcan","parsed","parseUcan","_this2$app$get2","issuer","encodeKeyPair","secretKey","secret","buildUcan","audience","lifetimeInSeconds","capabilities","att","_buildUcan","_this2$app$service$pa","patch","AuthenticationService","CoreCall","context","coreOptions","_context$params","core","_this$context$app","_this2$context$app","_extends4","_extends5","_this3$context$app","_extends6","_extends7","_this4$context$app","_extends8","_extends9","_this4","update","_this5$context$app","_extends10","_extends11","remove","_this6$context$app","_extends12","_extends13","_this6","_this7$context$app","_extends14","_extends15","_this7","_find","_this8$context$app","_extends16","_extends17","_this8","_create","_this9$context$app","_extends18","_extends19","_this9","_patch","_this10$context$app","_extends20","_extends21","_this10","_update","_this11$context$app","_extends22","_extends23","_this11","_remove","_this12$context$app","_extends24","_extends25","_this12","existsPath","getExists","path","loadExists","ex","exists_check","_CoreCall$get","setExists","val","_set","_settle","pact","state","s","_Pact","o","bind","v","observer","onRejected","onFulfilled","callback","_isSettledPact","thenable","_forTo","array","body","check","_cycle","i","_forIn","target","push","_iteratorSymbol","Symbol","iterator","noThrowAuth","_exit","config","_catch","_authenticate$catch","_result","bareAuth","verifyOne","verifyUcan","_v","ok","requiredCapabilities","newCapabilities","map","a","capability","can","segments","_verifyUcan","orVerifyLoop","arr","_interrupt","_temp4","_v2","_arr$i","_verifyOne","verifyAgainstReqs","reqs","vMethod","client_ucan","ucan_aud","or","method","uc","methodOpts","_v3","_exit2","cs","cap_subjects","filter","_temp8","loginConfig","loginCheckId","String","capability_service","subject","$in","caps","_exit3","step","next","done","_fixup","TypeError","values","_forOf","cap","k","logins","_temp7","_v4","_temp6","ucanString","_temp5","_vMethod","_result2","modelCapabilities","rootIssuer","isArray","genCapability","with","defaultScheme","hierPart","defaultHierPart","namespace","checkUcan","_temp20","_v5","_v6","authenticated","canU","specialChange","sk","spl","split","_temp18","_result9","_v7","error","type","noThrow","_no_throw_error","loginPass","_temp17","_iteratorError","_temp16","_result7","_interrupt2","scrubData","scrubbedData","_iteratorAbruptCompletion","_didIteratorError","_temp15","_finallyRethrows","_step","_iterator","_asyncIterator","_temp11","stage","shouldContinue","updateValue","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","_for","_temp9","_iterator$next","lpass","_temp10","methodsOnly","allMethods","methodIdx","_temp21","existingParams","existing","loginOk","checkLogin","recordLoginPassId","loginIdPath","checkArr","checkId","rl","_step2","_iterator2","_createForOfIteratorHelperLoose","spl2","obj","_step3","_iterator3","currentMethod","_step4","_iterator4","slice","join","field","topLevel","_arr","operator","operatorLevel","checkLoginPass","_wasThrown","_temp14","_result8","_temp13","_temp12","_wasThrown2","_temp19","_verifyAgainstReqs","ucanAuth","_exit5","_temp27","_result10","_temp25","adminPass","_temp24","_noThrowAuth","login","_temp26","_temp23","_temp22","methods","_context$data","_context$data$add","add","_context$data$remove","_context$app$get","checkAbilities","stack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AaA,cAAC,CAACC,UAAWC,IAClCE,SAAUjD,EACVkD,kBAAmB,OACnBwR,OAAQF,GACL9Q,EAAQzE,KAAI,CACfkE,aAAAA,MACF/H,KAPIuZ,SAAAA,GASN,IAAMC,EAAUrV,EAAAA,UAAUoV,GAAK,OAAAha,QAAAC,QACTC,eAAa+Z,IAAQxZ,KAAA,SAArCyZ,GAAO,IAAAC,EACb,IAAKD,EAAS,MAAU,IAAAhc,MAAM,wCAAwC,OAAA8B,QAAAC,QAChD,IAAI6I,EAASnF,EAASoF,GAASH,MAAM+Q,GAASQ,EAAAA,GAAAA,EAAK7N,GAAO2N,EAAOE,KAAG1Z,KAAA,SAApF2Z,GAEN,OADArR,EAAQ7F,OAAS,CAAC8W,IAAKjR,EAAQzE,KAAM2V,QAAAA,EAAS5I,QAAS+I,GAChDrR,CAAQ,EAAA,EAAA,EAAA,EAAA,EACnB,CAAC,MAAAnH,GAAA5B,OAAAA,QAAA6B,OAAAD,IACL"}
|
package/lib/index.d.ts
DELETED
package/lib/index.modern.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{validateUcan as t,_unset as e,ucanToken as i,_get as n,parseUcan as a,encodeKeyPair as s,buildUcan as o,_set as r,genCapability as c,verifyUcan as l,stackAbilities as u,reduceAbilities as h}from"symbol-ucan";import{AuthenticationBaseStrategy as p,AuthenticationService as d,authenticate as g}from"@feathersjs/authentication";import y from"long-timeout";function f(t){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var e=t.done;return Promise.resolve(t.value).then(function(t){return{value:t,done:e}})}return f=function(t){this.s=t,this.n=t.next},f.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(t){var i=this.s.return;return void 0===i?Promise.resolve({value:t,done:!0}):e(i.apply(this.s,arguments))},throw:function(t){var i=this.s.return;return void 0===i?Promise.reject(t):e(i.apply(this.s,arguments))}},new f(t)}function v(){return v=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},v.apply(this,arguments)}function m(t,e){if(null==t)return{};var i,n,a={},s=Object.keys(t);for(n=0;n<s.length;n++)e.indexOf(i=s[n])>=0||(a[i]=t[i]);return a}class w extends Error{constructor(t){super(t)}}const _=/(\S+)\s+(\S+)/;class x extends p{constructor(...t){super(...t),this.expirationTimers=new WeakMap}setAuthentication(t){t.verifyAccessToken=t=>({}),super.setAuthentication(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 v({service:e.service,entity:e.entity,entityId:e.entityId,header:"Authorization",schemes:["Bearer","JWT"]},super.configuration)}async handleConnection(e,i,n){const a="logout"===e&&i.authentication&&n&&i.authentication.accessToken===n.accessToken,{accessToken:s}=n||{};if(s&&"login"===e){const e=await t(s).catch(t=>{console.log("Could not validate ucan in connection: ",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:n}}=e||{payload:{exp:0}},a=1e3*n-Date.now(),o=y.setTimeout(()=>this.app.emit("disconnect",i),a);y.clearTimeout(this.expirationTimers.get(i)),this.expirationTimers.set(i,o),i.authentication={strategy:this.name,accessToken:s}}else if("disconnect"===e||a){const{entity:t}=this.configuration;delete i[t],delete i.authentication,y.clearTimeout(this.expirationTimers.get(i)),this.expirationTimers.delete(i)}}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,i){const n=this.entityService,{entity:a}=this.configuration;if(null===n)throw new w("Could not find entity service");const s=await this.getEntityQuery(i),o=Object.assign({},e(i,"provider"),{query:s}),r=await n.get(t,o);return i.provider?n.get(t,v({},i,{[a]:r})):r}async getEntityId(t,e){let{query:i,loginId:n}=e;if(n)return n;{var a;const{service:t,core_path:n="core"}=this.configuration,s={query:v({},i,{$limit:1}),[n]:v({skipJoins:!0},e[n])},o=await(null==(a=this.app)?void 0:a.service(t).find(v({},s,{skipJoins:!0,skip_hooks:!0,admin_pass:!0})));if(o.total)return o.data[0]._id;throw new w("Could not find login associated with this ucan")}}async authenticate(e,a){let{accessToken:s,loginId:o,ucan:r}=e;const{entity:c,core_path:l}=this.configuration;if(!s){if(!r)throw new w("Error generating ucan");s=i(r)}const u=await t(s).catch(t=>{console.log("Could not validate ucan during authentication: ",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)}),h={accessToken:s,authentication:{strategy:"jwt",accessToken:s}};if(null===c)return h;let p;const d=n(a,[l,c]);if(d)p=d;else{const t=await this.getEntityId(h,v({},a,{loginId:o,query:{did:null==u?void 0:u.payload.aud}}));p=await this.getEntity(t,a)}return v({},h,{[c]:p})}async parse(t){const{header:e,schemes:i}=this.configuration,n=t.headers&&t.headers[e.toLowerCase()];if(!n||"string"!=typeof n)return null;const[,a,s]=n.match(_)||[],o=a&&i.some(t=>new RegExp(t,"i").test(a));return a&&!o?null:{strategy:this.name,accessToken:o?s:n}}}const k=["NotAuthenticated"];class b extends Error{constructor(t){super(t)}}class E extends d{constructor(t,e="authentication",i={}){const{NotAuthenticated:n}=i;super(t,e,m(i,k)),this.options=void 0,this.app=t,this.options={NotAuthenticated:n}}async create(e,r){var c,l;const u=(null==(c=this.options)?void 0:c.NotAuthenticated)||b,{entity:h,service:p,ucan_path:d="ucan"}=this.app.get("authentication"),g=(null==(l=r)?void 0:l.authStrategies)||this.configuration.authStrategies;if(r||(r={}),!g.length)throw new u("No authentication strategies allowed for creating a JWT (`authStrategies`)");const y=await this.authenticate(e,r,...g).catch(t=>{throw new Error(t.message)});if(y.accessToken)return y;const f=e.did||n(y,[h,"did"]);let m=e.ucan||n(y,[h,"ucan"]);if(!f)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 creating authentication: ",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 creating authentication",m,e.message),null})){const t=a(m);let{secret:e}=this.app.get("authentication");const c=s({secretKey:e});m=await o({audience:t.payload.aud,issuer:c,lifetimeInSeconds:5184e3,capabilities:t.payload.att}),r.admin_pass=!0,await this.app.service(p).patch(n(y,[h,"_id"]),{[d]:i(m)},v({},r))}const w=i(m);return v({accessToken:w},y,{authentication:v({},y.authentication,{payload:w})})}}class ${constructor(t,e,i){var n;this.context=void 0,this.service=void 0,this.core=void 0,this.entity=void 0,this.service=t,this.context=e;const a=(e.app.get("authentication")||{entity:"login"}).entity||"login";this.entity=a;const s=(null==(n=e.params)?void 0:n.core)||{};s[a]||(s[a]=e.params[a]),this.core=v({},s,i)}async get(t,e={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).get(t,v({},e,{[this.entity]:e[this.entity]},{[n]:this.core}))}async find(t={}){var e;const{core_path:i}=this.context.app.get("authentication");return null==(e=this.context.app)?void 0:e.service(this.service).find(v({},t,{[this.entity]:t[this.entity],skip_hooks:!0,admin_pass:!0},{[i]:this.core}))}async create(t,e={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).create(t,v({},e,{[this.entity]:e[this.entity]},{[n]:this.core}))}async patch(t,e,i={}){var n;const{core_path:a}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).patch(t,e,v({},i,{[this.entity]:i[this.entity]},{[a]:this.core}))}async update(t,e,i={}){var n;const{core_path:a}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service).update(t,e,v({},i,{[this.entity]:i[this.entity]},{[a]:this.core}))}async remove(t,e={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service).remove(t,v({},e,{[this.entity]:e[this.entity]},{[n]:this.core}))}async _get(t,e={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._get(t,v({},e,{[this.entity]:e[this.entity]},{[n]:this.core}))}async _find(t={}){var e;const{core_path:i}=this.context.app.get("authentication");return null==(e=this.context.app)?void 0:e.service(this.service)._find(v({},t,{[this.entity]:t[this.entity]},{[i]:this.core}))}async _create(t,e={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._create(t,v({},e,{[this.entity]:e[this.entity]},{[n]:this.core}))}async _patch(t,e,i={}){var n;const{core_path:a}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._patch(t,e,v({},i,{[this.entity]:i[this.entity]},{[a]:this.core}))}async _update(t,e,i={}){var n;const{core_path:a}=this.context.app.get("authentication");return null==(n=this.context.app)?void 0:n.service(this.service)._update(t,e,v({},i,{[this.entity]:i[this.entity]},{[a]:this.core}))}async _remove(t,e={}){var i;const{core_path:n}=this.context.app.get("authentication");return null==(i=this.context.app)?void 0:i.service(this.service)._remove(t,v({},e,{[this.entity]:e[this.entity]},{[n]:this.core}))}}const T="_exists",C=t=>{const e=t.app.get("existsPath")||T;return n(t.params,`core.${e}.${t.path}.${t.id}`)||void 0},S=async(t,e)=>{let i=C(t);return!i&&t.id&&(i=await new $(t.path,t,{skipJoins:!1!==(null==e?void 0:e.skipJoins)}).get(t.id,v({exists_check:!0,admin_pass:!0,skip_hooks:!0},(null==e?void 0:e.params)||{}))),i},j=(t,e)=>{const i=t.app.get("existsPath")||T;return t.params=r(t.params,`core.${i}.${t.path}.${(null==e?void 0:e._id)||t.id}`,e),t},A=["ucan"],I="*",q="$",O=async t=>{const e=t.app.get("authentication"),i=n(t,["auth",e.entity]);i&&(t=r(t,[e.core_path,e.entity],i));try{t=await g("jwt")(t).catch(()=>t)}catch(e){return t}return t},U=async t=>{const e=t.app.get("authentication"),i=n(t,["auth",e.entity]);return i&&(t=r(t,[e.core_path,e.entity],i)),g("jwt")(t)},P=async(t,e,i)=>{try{var n;let s=await l(t,e);if((null==(n=s)||!n.ok)&&e.requiredCapabilities){const n=e.requiredCapabilities.map(t=>("*"!==t.capability.can&&(t.capability.can.segments=["*"]),t));i&&console.log("set new req capabilities",n,a(t)),s=await l(t,v({},e,{requiredCapabilities:n})),i&&console.log("Second verification result:",s)}return s}catch(t){return{ok:!1,err:[t.message]}}},N=async(t,e)=>{let i={ok:!1,value:[]};try{for(const s in t){var n;if(e&&console.log("or verify loop",t[s],a(t[s].ucan)),null!=(n=i)&&n.ok)break;{const n=t[s],{ucan:a}=n,o=m(n,A);i=await P(a,o,e),e&&console.log("got in verify loop",i)}}return i}catch(t){return{ok:!1,err:[t.message]}}},J=(t,e,a)=>async s=>{var o;const r=null==a?void 0:a.log,c=n(s.params,e.client_ucan),l=(null==a?void 0:a.audience)||n(s.params,e.ucan_aud);let u;r&&console.log("verify against reqs",t);const h=(null==a?void 0:a.or)||[];u=c&&("*"===h||h.includes(s.method))?(e,i)=>N((t||[]).map(t=>({ucan:e||c,audience:(null==i?void 0:i.aud)||l,requiredCapabilities:[t]})),r):(e,i)=>P(e||c,{audience:(null==i?void 0:i.aud)||l,requiredCapabilities:t},r);let p=await u();if(r&&console.log("first verify try",p),null!=(o=p)&&o.ok)return p;const d=((null==a?void 0:a.cap_subjects)||[]).filter(t=>!!t);if(r&&console.log("check cap_subjects",d),d){const t=(null==e?void 0:e.loginConfig)||s.app.get("authentication"),o=String(n(s.params,`${t.entity}._id`||"")),c=await new $(t.capability_service||"caps",s).find({query:{$limit:d.length,subject:{$in:d}},skip_hooks:!0,admin_pass:!0}).catch(t=>console.log(`Error finding caps in ucan auth: ${t.message}`));if(r&&console.log("caps",c),null!=c&&c.data)for(const t of c.data)for(const e in t.caps||{})if(r&&console.log("check cap",e,t.caps[e].logins,o),(t.caps[e].logins||[]).map(t=>String(t)).includes(o)){var g;try{const n=i(t.caps[e].ucan);r&&console.log("got ucan string",n),n&&(p=await u(n,{aud:t.did}),r&&console.log("tried v on cap",p))}catch(e){console.log(`Error verifying ucan from cap: ${t._id}. Err:${e.message}`)}if(null!=a&&a.log&&console.log("tried v on cap",p),null!=(g=p)&&g.ok)return p}}return p},K=(t,e)=>{const i=s({secretKey:e.secret}).did();return Array.isArray(t)?t.map(t=>({capability:Array.isArray(t)?c({with:{scheme:e.defaultScheme,hierPart:e.defaultHierPart},can:{namespace:t[0],segments:"string"==typeof t[1]?[t[1]]:t[1]}},e):c(t,e),rootIssuer:i})):[]},M=(t,e)=>async i=>{var a;const s=(null==e?void 0:e.loginConfig)||i.app.get("authentication");let o={ok:!1,value:[]};const c=K(t,s);if(c.length?o=await J(c,s,e)(i):"*"!==t&&(o.ok=!0),null!=(a=o)&&a.ok)return i.params.authenticated=!0,i.params.canU=!0,i;var l;if(null!=e&&e.log&&console.log("checking special change",null==e?void 0:e.specialChange),null!=e&&e.specialChange){if("*"===e.specialChange)return i.params.canU=!0,i;if(Array.isArray(e.specialChange)&&["create","patch","update"].includes(i.method)){if(Array.isArray(i.data))throw new Error("No multi data allowed with special change");for(const t in i.data||{})if(["$set","$unset","$addToSet","$pull","$push"].includes(t)){for(const n in i.data[t]||{})if(!e.specialChange.includes(n)){const a=n.split(".");1===a.length?delete i.data[t][n]:e.specialChange.includes(a[0])||delete i.data[t][n]}}else e.specialChange.includes(t)||delete i.data[t];return i.params.canU=!0,i}}if(null!=(l=o)&&l.ok)return i.params.authenticated=!0,i.params.canU=!0,i;{var u;const{loginPass:t}=e||{loginPass:[[["*"],["nonExistentMethod"]]]};if(null!=t&&t.length){let a={},c=!0;const l=async t=>{let l=[];const u="*"===t[1];let h=-1;if(u?h=0:(l=t[1].map(t=>t.split("/")[0]),h=l.indexOf(i.method)),h>-1){const l=await S(i,{params:null==e?void 0:e.existingParams});let p=!1;const d=(t,e="_id")=>{const a=n(i.params,`${s.entity}.${e}`);if(a&&t){const e=Array.isArray(a)?a.map(t=>String(t)):[String(a)];if(Array.isArray(t))for(let i=0;i<e.length;i++){const n=String(e[i]);for(let e=0;e<t.length;)String(t[e])===n?p=!0:e++;if(p)return}else if(e.includes(String(t)))return p=!0}};if(l){i=j(i,l);for(const e of t[0]||[]){const t=String(e).split("/");if(t[0].includes("*")){const e=t[0].split("*"),i=n(l,e[0]);if(i&&"object"==typeof i)if(Array.isArray(i)){for(const a of i)if(d(n(a,e[1]),t[1]||"_id"),p)break}else for(const a in i)if(d(n(i,`${a}.${e[1]}`),t[1]||"_id"),p)break}else d(n(l,t[0]),t[1]||"_id")}}if(p)if(o.ok=!0,"*"===t[1]||["find","get","remove"].some(e=>t[1].includes(e)))c=!1;else{const e=u?"*":t[1][h];if(e.split("/")[0]!==e){const t=e.split("/").slice(1).join("").split(",")||[];for(const e of t){const t=n(i.data,e);if(t)a=r(a,e,t);else for(const t of["$addToSet","$pull"]){const s=n(i.data,`${t}.${e}`);s&&(a=r(a,`${t}.${e}`,s))}}}else c=!1}}};var h,p=!1,d=!1;try{for(var g,y=function(t){var e,i,n,a=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,n=Symbol.iterator);a--;){if(i&&null!=(e=t[i]))return e.call(t);if(n&&null!=(e=t[n]))return new f(e.call(t));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}(t);p=!(g=await y.next()).done;p=!1){const t=g.value;if(!c)break;await l(t)}}catch(t){d=!0,h=t}finally{try{p&&null!=y.return&&await y.return()}finally{if(d)throw h}}c&&(i=r(i,"data",a))}if(null!=(u=o)&&u.ok)return i.params.authenticated=!0,i.params.canU=!0,i;if(null!=e&&e.log&&console.error("Ucan capabilities requirements not met: ",o,i.type,i.path),null!=e&&e.noThrow)return i.params._no_throw_error={type:i.type,method:i.method,path:i.path},i;throw new Error("Missing proper capabilities for this action: "+i.type+": "+i.path+" - "+i.method)}},V=(t,e)=>async i=>{var a;const s=i.app.get("authentication"),o=s.core_path||"core",r=s.entity||"login",{_id:c}=n(i.params,[o,r])||(null==(a=i.params)?void 0:a.login)||{_id:void 0};if(null!=e&&e.log&&console.log("ucan auth","loginId",c,"core_path",o,"entity",r,"core",i.params[o],"params login",i.params.login,"required capabilities",t),"$"===t||t&&"$"===t[i.method])return c?i:await O(i);const l=((null==e?void 0:e.adminPass)||[]).includes(i.method)&&(n(i.params,"admin_pass")||n(i.params,[s.core_path,"admin_pass"]));return c||(i=l||null!=e&&e.specialChange?await O(i):await U(i)),"*"!==t||null!=e&&e.specialChange?l?i:t?await M(t,e)(i):i:(i.params.authenticated=!!i.params[r],i)},W=(t,e)=>async i=>{const a=i.app.get("authentication"),s=n(i,["auth",a.entity]);if(s&&(i=r(i,[a.core_path,a.entity],s)),"before"===i.type){const{method:n}=i;return t[n]||t.all?await V(t[n]||t.all,e)(i):i}return i},D=()=>async e=>{const{add:r=[],remove:c=[]}=e.data;if(!(null!=r&&r.length||null!=c&&c.length))throw new Error("No new capabilities passed");const{secret:p,ucan_aud:d,entity:g,ucan:y}=e.app.get("authentication"),f=s({secretKey:p}).did(),m=u([...r,...c]),w=await l(n(e.params,[g,y]),{audience:n(e.params,d),requiredCapabilities:m.map(t=>({capability:t,rootIssuer:f}))});if(null==w||!w.ok)throw new Error("You don't have sufficient capabilities to grant those capabilities");const _=e.id,x=e.data.service||"logins",k=e.data.path||"ucan",b=await new $(x,e,{skipJoins:!0}).get(_),E=a(n(b,k)),{aud:T,att:C,prf:S}=E.payload;let j=[...C];null!=c&&c.length&&(j=h(c,C)),null!=r&&r.length&&(j=u([...C,...r]));const A=await o(v({issuer:s({secretKey:p}),audience:T,lifetimeInSeconds:5184e3,proofs:S},e.data,{capabilities:j})),I=i(A);if(!await t(I))throw new Error("Invalid ucan generated when updating");const q=await new $(x,e).patch(_,{[k]:I});return e.result={raw:e.data,encoded:I,subject:q},e};export{E as AuthService,$ as CoreCall,b as NotAuthError,x as UcanStrategy,W as allUcanAuth,I as anyAuth,U as bareAuth,M as checkUcan,T as existsPath,C as getExists,S as loadExists,K as modelCapabilities,q as noThrow,O as noThrowAuth,N as orVerifyLoop,j as setExists,V as ucanAuth,D as updateUcan,J as verifyAgainstReqs};
|
|
2
|
-
//# sourceMappingURL=index.modern.js.map
|