@dstny/scp-authenticator 0.0.6 → 0.0.7
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 +173 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +19 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +19 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -2
package/README.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# @dstny/authenticator
|
|
2
|
+
|
|
3
|
+
This library provides way to authenticate agains a Dstny identity.
|
|
4
|
+
|
|
5
|
+
## Initialization
|
|
6
|
+
|
|
7
|
+
The authenticator depends on an Authentication API and a Secure Storage.
|
|
8
|
+
|
|
9
|
+
**Secure Storage**: On Web platform you must use `WebLocalStorage` provided by [@dstny/scp-storage](https://www.npmjs.com/package/@dstny/scp-storage) package. \
|
|
10
|
+
**Authentication API**: There are 2 supported implementations:
|
|
11
|
+
|
|
12
|
+
- `SmgAuthApi` used to authenticate against the SMG API
|
|
13
|
+
- `OAuthApi` used to authenticate directly against the Keycloak API
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import Authenticator, { SmgAuthApi, AuthenticatorEvents } from '@dstny/scp-authenticator'
|
|
17
|
+
import { WebLocalStorage } from '@dstny/scp-storage'
|
|
18
|
+
|
|
19
|
+
const api = new SmgAuthApi(
|
|
20
|
+
'https://api.development.aws.d4sp.com/api-user', // base url
|
|
21
|
+
'syslab', // realm
|
|
22
|
+
'connect-me' // client-id
|
|
23
|
+
)
|
|
24
|
+
const secureStorage = new WebLocalStorage()
|
|
25
|
+
|
|
26
|
+
const authenticator = new Authenticator(api, secureStorage)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Once the authenticator is instantiated we must intialize it.
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
await authenticator.setup()
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Login
|
|
36
|
+
|
|
37
|
+
If a valid access token or refresh token was found in storage during the setup, the user will be authenticated automatically.
|
|
38
|
+
`authenticator.credentials` is defined when the user is authenticated. This variable will be set (or not) after `await authenticator.setup()` is invoked. Events will also be emitted to notify when the user is authenticated.
|
|
39
|
+
|
|
40
|
+
If the user is not authenticated in automatically, the first thing to do, is to check if a code is present in the url,
|
|
41
|
+
when that is the case, you should extract it and use it to signIn
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
const query = new URLSearchParams(window.location.search)
|
|
45
|
+
const code = query.get('code')
|
|
46
|
+
|
|
47
|
+
await authenticator.signIn(code, redirectUri) // events will be emitted
|
|
48
|
+
|
|
49
|
+
window.history.replaceState({}, document.title, window.location.pathname) // remove 'code' parameter from url once it was used
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
When the user is not logged in, and no code is present in the url, you can login the user, to do this you need to obtain the login url, and redirect the browser to it.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const redirectUri = window.location.origin // this is only an example, you might have a different redirect uri
|
|
56
|
+
|
|
57
|
+
const url = await authenticator.getLoginUrl(redirectUri)
|
|
58
|
+
window.location.href = url
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Logout
|
|
62
|
+
|
|
63
|
+
To logout use `signOut`. Events will be emitted with `undefined` value to notify that no user is currently authenticated.
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
await authenticator.signOut() // events will be emitted
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
# Destroy
|
|
70
|
+
|
|
71
|
+
Once the authenticator is no longer required it can be destroyed.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
await authenticator.destroy()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
This will not logout the user from Keycloak.
|
|
78
|
+
|
|
79
|
+
## Events
|
|
80
|
+
|
|
81
|
+
The library provides set of events which will be invoked when the state changes or when value of the credentials, access token and jwt payload changes.
|
|
82
|
+
|
|
83
|
+
For all the events below you can assume that:
|
|
84
|
+
|
|
85
|
+
- if the previous value was falsy then became truthy, the user logged in
|
|
86
|
+
- if the previous value was truthy then became falsy, the user logged out
|
|
87
|
+
- if the previous value was truthy and stayed truthy, the tokens were refreshed and new values are available.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
authenticator.on(AuthenticatorEvents.STATE_CHANGE, (state) => {
|
|
91
|
+
if (state) {
|
|
92
|
+
// user is authenticated
|
|
93
|
+
} else {
|
|
94
|
+
// user is not authenticated
|
|
95
|
+
}
|
|
96
|
+
})
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
authenticator.on(AuthenticatorEvents.CREDENTIALS, (credentials) => {
|
|
101
|
+
if (credentials) {
|
|
102
|
+
// user is authenticated, credentials object contains
|
|
103
|
+
// the access token, the refresh token and the expiry time
|
|
104
|
+
} else {
|
|
105
|
+
// user is not authenticated
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
authenticator.on(AuthenticatorEvents.ACCESS_TOKEN, (accessToken) => {
|
|
112
|
+
if (accessToken) {
|
|
113
|
+
// user is authenticated, accessToken contains the
|
|
114
|
+
// the access token string
|
|
115
|
+
} else {
|
|
116
|
+
// user is not authenticated
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
authenticator.on(AuthenticatorEvents.JWT_PAYLOAD, (jwt) => {
|
|
123
|
+
if (jwt) {
|
|
124
|
+
// user is authenticated, jwt object contains
|
|
125
|
+
// the decoded payload from the access token
|
|
126
|
+
} else {
|
|
127
|
+
// user is not authenticated
|
|
128
|
+
}
|
|
129
|
+
})
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Authentication API & Coven
|
|
133
|
+
|
|
134
|
+
Coven will provide the Authentication API configuration.
|
|
135
|
+
Coven will replace specific strings placed in the files with configuration.
|
|
136
|
+
|
|
137
|
+
`__COVEN_SDK_LOGIN_METHOD__` indicates which Authentication API implementation you must use, when:
|
|
138
|
+
|
|
139
|
+
- `smg` you are expected use use `SmgAuthApi` implementation,
|
|
140
|
+
- otherwise you must use `OAuthApi` implementation.
|
|
141
|
+
|
|
142
|
+
### SmgAuthAPI
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
class SmgAuthApi extends AbstractAuthenticationApi {
|
|
146
|
+
constructor(baseURL: string, realm: string, clientId: string)
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
| String | Contains | Example |
|
|
151
|
+
| ----------------------------- | ---------- | ----------------------------------------------- |
|
|
152
|
+
| `__COVEN_SDK_SMG_AUTH_URL__` | `baseURL` | `https://api.development.aws.d4sp.com/api-user` |
|
|
153
|
+
| `__COVEN_SDK_SMG_CLIENT_ID__` | `clientId` | `connect-me` |
|
|
154
|
+
| `__CONNECTME_SDK_SMG_REALM__` | `realm` | `syslab1` |
|
|
155
|
+
|
|
156
|
+
### OAuthApi
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
class OAuthApi extends AbstractAuthenticationApi {
|
|
160
|
+
constructor(baseURL: string, clientId: string, authorizationRoute: string, scope: string)
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
| String | Contains | Example |
|
|
165
|
+
| ----------------------------------------- | -------------------- | ----------------------------------------------------------------------------- |
|
|
166
|
+
| `__COVEN_SDK_OAUTH_URL__` | `baseURL` | `https://keycloak.test.aws.d4sp.com/auth/realms/odos/protocol/openid-connect` |
|
|
167
|
+
| `__COVEN_SDK_OAUTH_CLIENT_ID__` | `clientId` | `connect-me` |
|
|
168
|
+
| `__COVEN_SDK_OAUTH_AUTHORIZATION_ROUTE__` | `authorizationRoute` | `/auth` |
|
|
169
|
+
| `__COVEN_SDK_OAUTH_SCOPE__` | `scope` | |
|
|
170
|
+
|
|
171
|
+
## Example
|
|
172
|
+
|
|
173
|
+
An example application can be found in the [example](https://code.internal.destiny.be/escaux/uep/connectme-sdk/-/tree/develop/packages/authenticator/example?ref_type=heads) directory.
|
package/dist/index.d.mts
CHANGED
|
@@ -58,6 +58,7 @@ declare class Authenticator extends Emittery {
|
|
|
58
58
|
private unsubscribeListenerAdded?;
|
|
59
59
|
private unsubscribeUpdateState?;
|
|
60
60
|
private timers;
|
|
61
|
+
delegateSignOutOnRefreshFailure?: () => Promise<void>;
|
|
61
62
|
get jwtPayload(): JwtPayload | undefined;
|
|
62
63
|
get credentials(): Credentials | undefined;
|
|
63
64
|
get state(): AuthenticatorState;
|
package/dist/index.d.ts
CHANGED
|
@@ -58,6 +58,7 @@ declare class Authenticator extends Emittery {
|
|
|
58
58
|
private unsubscribeListenerAdded?;
|
|
59
59
|
private unsubscribeUpdateState?;
|
|
60
60
|
private timers;
|
|
61
|
+
delegateSignOutOnRefreshFailure?: () => Promise<void>;
|
|
61
62
|
get jwtPayload(): JwtPayload | undefined;
|
|
62
63
|
get credentials(): Credentials | undefined;
|
|
63
64
|
get state(): AuthenticatorState;
|
package/dist/index.js
CHANGED
|
@@ -846,6 +846,19 @@ var Authenticator = class extends Emittery {
|
|
|
846
846
|
unsubscribeListenerAdded;
|
|
847
847
|
unsubscribeUpdateState;
|
|
848
848
|
timers = /* @__PURE__ */ new Map();
|
|
849
|
+
/**
|
|
850
|
+
* In some cases we don't want to trigger the logout automatically
|
|
851
|
+
* on refresh failure.
|
|
852
|
+
*
|
|
853
|
+
* When defined, this method will be invoked after the refresh failure
|
|
854
|
+
* allowing you to define the behavior in that case.
|
|
855
|
+
*
|
|
856
|
+
* Example: You might not want sign out the user immediately
|
|
857
|
+
* when your application is handling calls and you have ongoing calls.
|
|
858
|
+
*
|
|
859
|
+
* @returns {Promise<void>}
|
|
860
|
+
*/
|
|
861
|
+
delegateSignOutOnRefreshFailure;
|
|
849
862
|
get jwtPayload() {
|
|
850
863
|
return this._jwtPayload;
|
|
851
864
|
}
|
|
@@ -1125,7 +1138,7 @@ var Authenticator = class extends Emittery {
|
|
|
1125
1138
|
throw new Error("Unable to start refresh token runner without credentials");
|
|
1126
1139
|
}
|
|
1127
1140
|
const refreshIn = new Date(this.credentials.expires_at).getTime() - (/* @__PURE__ */ new Date()).getTime();
|
|
1128
|
-
const refreshTimeout = this.refreshSeparationMilliseconds + Math.max(
|
|
1141
|
+
const refreshTimeout = this.refreshSeparationMilliseconds + Math.max(1e4, refreshIn - 1e4);
|
|
1129
1142
|
this.logger?.info(
|
|
1130
1143
|
`Setting timer to refresh token in ${Math.round(refreshTimeout / 1e3)} seconds at ${new Date((/* @__PURE__ */ new Date()).getTime() + refreshTimeout).toTimeString()}`
|
|
1131
1144
|
);
|
|
@@ -1226,7 +1239,11 @@ var Authenticator = class extends Emittery {
|
|
|
1226
1239
|
}
|
|
1227
1240
|
}
|
|
1228
1241
|
if (error instanceof RefreshTokenError_default) {
|
|
1229
|
-
|
|
1242
|
+
if (this.delegateSignOutOnRefreshFailure) {
|
|
1243
|
+
await this.delegateSignOutOnRefreshFailure();
|
|
1244
|
+
} else {
|
|
1245
|
+
await this.signOut(false);
|
|
1246
|
+
}
|
|
1230
1247
|
}
|
|
1231
1248
|
throw error;
|
|
1232
1249
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/maps.js","../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/index.js","../../credentials/src/utils.ts","../../credentials/src/Credentials.ts","../src/utils/jwt.ts","../src/events.ts","../src/types.ts","../src/utils/separation.ts","../src/errors/TokenNetworkError.ts","../src/errors/RefreshTokenError.ts","../src/errors/AuthorizationError.ts","../src/errors/InvalidClientError.ts","../src/Authenticator.ts","../src/api/AbstractAuthenticationApi.ts","../src/api/OAuthApi.ts","../src/api/SmgAuthApi.ts"],"sourcesContent":["import Authenticator from './Authenticator'\n\nexport * from './types'\nexport * from './events'\n\nexport * from './api/AbstractAuthenticationApi'\nexport * from './api/OAuthApi'\nexport * from './api/SmgAuthApi'\n\nexport default Authenticator\n","export const anyMap = new WeakMap();\nexport const eventsMap = new WeakMap();\nexport const producersMap = new WeakMap();\n","import {anyMap, producersMap, eventsMap} from './maps.js';\n\nconst anyProducer = Symbol('anyProducer');\nconst resolvedPromise = Promise.resolve();\n\n// Define symbols for \"meta\" events.\nconst listenerAdded = Symbol('listenerAdded');\nconst listenerRemoved = Symbol('listenerRemoved');\n\nlet canEmitMetaEvents = false;\nlet isGlobalDebugEnabled = false;\n\nconst isEventKeyType = key => typeof key === 'string' || typeof key === 'symbol' || typeof key === 'number';\n\nfunction assertEventName(eventName) {\n\tif (!isEventKeyType(eventName)) {\n\t\tthrow new TypeError('`eventName` must be a string, symbol, or number');\n\t}\n}\n\nfunction assertListener(listener) {\n\tif (typeof listener !== 'function') {\n\t\tthrow new TypeError('listener must be a function');\n\t}\n}\n\nfunction getListeners(instance, eventName) {\n\tconst events = eventsMap.get(instance);\n\tif (!events.has(eventName)) {\n\t\treturn;\n\t}\n\n\treturn events.get(eventName);\n}\n\nfunction getEventProducers(instance, eventName) {\n\tconst key = isEventKeyType(eventName) ? eventName : anyProducer;\n\tconst producers = producersMap.get(instance);\n\tif (!producers.has(key)) {\n\t\treturn;\n\t}\n\n\treturn producers.get(key);\n}\n\nfunction enqueueProducers(instance, eventName, eventData) {\n\tconst producers = producersMap.get(instance);\n\tif (producers.has(eventName)) {\n\t\tfor (const producer of producers.get(eventName)) {\n\t\t\tproducer.enqueue(eventData);\n\t\t}\n\t}\n\n\tif (producers.has(anyProducer)) {\n\t\tconst item = Promise.all([eventName, eventData]);\n\t\tfor (const producer of producers.get(anyProducer)) {\n\t\t\tproducer.enqueue(item);\n\t\t}\n\t}\n}\n\nfunction iterator(instance, eventNames) {\n\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\tlet isFinished = false;\n\tlet flush = () => {};\n\tlet queue = [];\n\n\tconst producer = {\n\t\tenqueue(item) {\n\t\t\tqueue.push(item);\n\t\t\tflush();\n\t\t},\n\t\tfinish() {\n\t\t\tisFinished = true;\n\t\t\tflush();\n\t\t},\n\t};\n\n\tfor (const eventName of eventNames) {\n\t\tlet set = getEventProducers(instance, eventName);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tconst producers = producersMap.get(instance);\n\t\t\tproducers.set(eventName, set);\n\t\t}\n\n\t\tset.add(producer);\n\t}\n\n\treturn {\n\t\tasync next() {\n\t\t\tif (!queue) {\n\t\t\t\treturn {done: true};\n\t\t\t}\n\n\t\t\tif (queue.length === 0) {\n\t\t\t\tif (isFinished) {\n\t\t\t\t\tqueue = undefined;\n\t\t\t\t\treturn this.next();\n\t\t\t\t}\n\n\t\t\t\tawait new Promise(resolve => {\n\t\t\t\t\tflush = resolve;\n\t\t\t\t});\n\n\t\t\t\treturn this.next();\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdone: false,\n\t\t\t\tvalue: await queue.shift(),\n\t\t\t};\n\t\t},\n\n\t\tasync return(value) {\n\t\t\tqueue = undefined;\n\n\t\t\tfor (const eventName of eventNames) {\n\t\t\t\tconst set = getEventProducers(instance, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.delete(producer);\n\t\t\t\t\tif (set.size === 0) {\n\t\t\t\t\t\tconst producers = producersMap.get(instance);\n\t\t\t\t\t\tproducers.delete(eventName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tflush();\n\n\t\t\treturn arguments.length > 0\n\t\t\t\t? {done: true, value: await value}\n\t\t\t\t: {done: true};\n\t\t},\n\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t};\n}\n\nfunction defaultMethodNamesOrAssert(methodNames) {\n\tif (methodNames === undefined) {\n\t\treturn allEmitteryMethods;\n\t}\n\n\tif (!Array.isArray(methodNames)) {\n\t\tthrow new TypeError('`methodNames` must be an array of strings');\n\t}\n\n\tfor (const methodName of methodNames) {\n\t\tif (!allEmitteryMethods.includes(methodName)) {\n\t\t\tif (typeof methodName !== 'string') {\n\t\t\t\tthrow new TypeError('`methodNames` element must be a string');\n\t\t\t}\n\n\t\t\tthrow new Error(`${methodName} is not Emittery method`);\n\t\t}\n\t}\n\n\treturn methodNames;\n}\n\nconst isMetaEvent = eventName => eventName === listenerAdded || eventName === listenerRemoved;\n\nfunction emitMetaEvent(emitter, eventName, eventData) {\n\tif (!isMetaEvent(eventName)) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tcanEmitMetaEvents = true;\n\t\temitter.emit(eventName, eventData);\n\t} finally {\n\t\tcanEmitMetaEvents = false;\n\t}\n}\n\nexport default class Emittery {\n\tstatic mixin(emitteryPropertyName, methodNames) {\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\t\treturn target => {\n\t\t\tif (typeof target !== 'function') {\n\t\t\t\tthrow new TypeError('`target` must be function');\n\t\t\t}\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tif (target.prototype[methodName] !== undefined) {\n\t\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction getEmitteryProperty() {\n\t\t\t\tObject.defineProperty(this, emitteryPropertyName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: new Emittery(),\n\t\t\t\t});\n\t\t\t\treturn this[emitteryPropertyName];\n\t\t\t}\n\n\t\t\tObject.defineProperty(target.prototype, emitteryPropertyName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tget: getEmitteryProperty,\n\t\t\t});\n\n\t\t\tconst emitteryMethodCaller = methodName => function (...args) {\n\t\t\t\treturn this[emitteryPropertyName][methodName](...args);\n\t\t\t};\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tObject.defineProperty(target.prototype, methodName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: emitteryMethodCaller(methodName),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn target;\n\t\t};\n\t}\n\n\tstatic get isDebugEnabled() {\n\t\t// In a browser environment, `globalThis.process` can potentially reference a DOM Element with a `#process` ID,\n\t\t// so instead of just type checking `globalThis.process`, we need to make sure that `globalThis.process.env` exists.\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tif (typeof globalThis.process?.env !== 'object') {\n\t\t\treturn isGlobalDebugEnabled;\n\t\t}\n\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tconst {env} = globalThis.process ?? {env: {}};\n\t\treturn env.DEBUG === 'emittery' || env.DEBUG === '*' || isGlobalDebugEnabled;\n\t}\n\n\tstatic set isDebugEnabled(newValue) {\n\t\tisGlobalDebugEnabled = newValue;\n\t}\n\n\tconstructor(options = {}) {\n\t\tanyMap.set(this, new Set());\n\t\teventsMap.set(this, new Map());\n\t\tproducersMap.set(this, new Map());\n\n\t\tproducersMap.get(this).set(anyProducer, new Set());\n\n\t\tthis.debug = options.debug ?? {};\n\n\t\tif (this.debug.enabled === undefined) {\n\t\t\tthis.debug.enabled = false;\n\t\t}\n\n\t\tif (!this.debug.logger) {\n\t\t\tthis.debug.logger = (type, debugName, eventName, eventData) => {\n\t\t\t\ttry {\n\t\t\t\t\t// TODO: Use https://github.com/sindresorhus/safe-stringify when the package is more mature. Just copy-paste the code.\n\t\t\t\t\teventData = JSON.stringify(eventData);\n\t\t\t\t} catch {\n\t\t\t\t\teventData = `Object with the following keys failed to stringify: ${Object.keys(eventData).join(',')}`;\n\t\t\t\t}\n\n\t\t\t\tif (typeof eventName === 'symbol' || typeof eventName === 'number') {\n\t\t\t\t\teventName = eventName.toString();\n\t\t\t\t}\n\n\t\t\t\tconst currentTime = new Date();\n\t\t\t\tconst logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;\n\t\t\t\tconsole.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\\n\\tdata: ${eventData}`);\n\t\t\t};\n\t\t}\n\t}\n\n\tlogIfDebugEnabled(type, eventName, eventData) {\n\t\tif (Emittery.isDebugEnabled || this.debug.enabled) {\n\t\t\tthis.debug.logger(type, this.debug.name, eventName, eventData);\n\t\t}\n\t}\n\n\ton(eventNames, listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tlet set = getListeners(this, eventName);\n\t\t\tif (!set) {\n\t\t\t\tset = new Set();\n\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\tevents.set(eventName, set);\n\t\t\t}\n\n\t\t\tset.add(listener);\n\n\t\t\tthis.logIfDebugEnabled('subscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerAdded, {eventName, listener});\n\t\t\t}\n\t\t}\n\n\t\tconst off = () => {\n\t\t\tthis.off(eventNames, listener);\n\t\t\tsignal?.removeEventListener('abort', off);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', off, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toff();\n\t\t}\n\n\t\treturn off;\n\t}\n\n\toff(eventNames, listener) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tconst set = getListeners(this, eventName);\n\t\t\tif (set) {\n\t\t\t\tset.delete(listener);\n\t\t\t\tif (set.size === 0) {\n\t\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\t\tevents.delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.logIfDebugEnabled('unsubscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerRemoved, {eventName, listener});\n\t\t\t}\n\t\t}\n\t}\n\n\tonce(eventNames) {\n\t\tlet off_;\n\n\t\tconst promise = new Promise(resolve => {\n\t\t\toff_ = this.on(eventNames, data => {\n\t\t\t\toff_();\n\t\t\t\tresolve(data);\n\t\t\t});\n\t\t});\n\n\t\tpromise.off = off_;\n\t\treturn promise;\n\t}\n\n\tevents(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t}\n\n\t\treturn iterator(this, eventNames);\n\t}\n\n\tasync emit(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emit', eventName, eventData);\n\n\t\tenqueueProducers(this, eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\tawait Promise.all([\n\t\t\t...staticListeners.map(async listener => {\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\treturn listener(eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t\t...staticAnyListeners.map(async listener => {\n\t\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\t\treturn listener(eventName, eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t]);\n\t}\n\n\tasync emitSerial(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emitSerial', eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\t/* eslint-disable no-await-in-loop */\n\t\tfor (const listener of staticListeners) {\n\t\t\tif (listeners.has(listener)) {\n\t\t\t\tawait listener(eventData);\n\t\t\t}\n\t\t}\n\n\t\tfor (const listener of staticAnyListeners) {\n\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\tawait listener(eventName, eventData);\n\t\t\t}\n\t\t}\n\t\t/* eslint-enable no-await-in-loop */\n\t}\n\n\tonAny(listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('subscribeAny', undefined, undefined);\n\n\t\tanyMap.get(this).add(listener);\n\t\temitMetaEvent(this, listenerAdded, {listener});\n\n\t\tconst offAny = () => {\n\t\t\tthis.offAny(listener);\n\t\t\tsignal?.removeEventListener('abort', offAny);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', offAny, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toffAny();\n\t\t}\n\n\t\treturn offAny;\n\t}\n\n\tanyEvent() {\n\t\treturn iterator(this);\n\t}\n\n\toffAny(listener) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('unsubscribeAny', undefined, undefined);\n\n\t\temitMetaEvent(this, listenerRemoved, {listener});\n\t\tanyMap.get(this).delete(listener);\n\t}\n\n\tclearListeners(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tthis.logIfDebugEnabled('clear', eventName, undefined);\n\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tconst set = getListeners(this, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.clear();\n\t\t\t\t}\n\n\t\t\t\tconst producers = getEventProducers(this, eventName);\n\t\t\t\tif (producers) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tanyMap.get(this).clear();\n\n\t\t\t\tfor (const [eventName, listeners] of eventsMap.get(this).entries()) {\n\t\t\t\t\tlisteners.clear();\n\t\t\t\t\teventsMap.get(this).delete(eventName);\n\t\t\t\t}\n\n\t\t\t\tfor (const [eventName, producers] of producersMap.get(this).entries()) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t\tproducersMap.get(this).delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlistenerCount(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tlet count = 0;\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tcount += anyMap.get(this).size\n\t\t\t\t\t+ (getListeners(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this)?.size ?? 0);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (eventName !== undefined) {\n\t\t\t\tassertEventName(eventName);\n\t\t\t}\n\n\t\t\tcount += anyMap.get(this).size;\n\n\t\t\tfor (const value of eventsMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\n\t\t\tfor (const value of producersMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tbindMethods(target, methodNames) {\n\t\tif (typeof target !== 'object' || target === null) {\n\t\t\tthrow new TypeError('`target` must be an object');\n\t\t}\n\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\n\t\tfor (const methodName of methodNames) {\n\t\t\tif (target[methodName] !== undefined) {\n\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t}\n\n\t\t\tObject.defineProperty(target, methodName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: this[methodName].bind(this),\n\t\t\t});\n\t\t}\n\t}\n}\n\nconst allEmitteryMethods = Object.getOwnPropertyNames(Emittery.prototype).filter(v => v !== 'constructor');\n\nObject.defineProperty(Emittery, 'listenerAdded', {\n\tvalue: listenerAdded,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\nObject.defineProperty(Emittery, 'listenerRemoved', {\n\tvalue: listenerRemoved,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\n","// declare const Buffer\n\nfunction byteToPercent(b: string) {\n return `%${`00${b.charCodeAt(0).toString(16)}`.slice(-2)}`\n}\n\nexport function base64decode(str: string): string | undefined {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\n\nexport async function sha1(str: string) {\n if (typeof crypto === 'object') {\n const hash = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(str))\n return Array.from(new Uint8Array(hash))\n .map((v) => v.toString(16).padStart(2, '0'))\n .join('')\n } else {\n return binb2hex(core_sha1(str2binb(str), str.length * chrsz))\n }\n}\n\nconst hexcase = 0 /* hex output format. 0 - lowercase; 1 - uppercase */\nconst b64pad = '' /* base-64 pad character. \"=\" for strict RFC compliance */\nconst chrsz = 8 /* bits per input character. 8 - ASCII; 16 - Unicode */\n\n/*\n * Calculate the SHA-1 of an array of big-endian words, and a bit length\n */\nfunction core_sha1(x: Array<number>, len: number) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - (len % 32))\n x[(((len + 64) >> 9) << 4) + 15] = len\n\n var w = Array(80)\n var a = 1732584193\n var b = -271733879\n var c = -1732584194\n var d = 271733878\n var e = -1009589776\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a\n var oldb = b\n var oldc = c\n var oldd = d\n var olde = e\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j]\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)\n var t = safe_add(\n safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n safe_add(safe_add(e, w[j]), sha1_kt(j))\n )\n e = d\n d = c\n c = rol(b, 30)\n b = a\n a = t\n }\n\n a = safe_add(a, olda)\n b = safe_add(b, oldb)\n c = safe_add(c, oldc)\n d = safe_add(d, oldd)\n e = safe_add(e, olde)\n }\n return Array(a, b, c, d, e)\n}\n\n/*\n * Perform the appropriate triplet combination function for the current\n * iteration\n */\nfunction sha1_ft(t: number, b: number, c: number, d: number) {\n if (t < 20) return (b & c) | (~b & d)\n if (t < 40) return b ^ c ^ d\n if (t < 60) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\n/*\n * Determine the appropriate additive constant for the current iteration\n */\nfunction sha1_kt(t: number) {\n return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514\n}\n\n/*\n * Calculate the HMAC-SHA1 of a key and some data\n */\nfunction core_hmac_sha1(key: string, data: string) {\n let bkey = str2binb(key)\n if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz)\n\n let ipad = Array(16),\n opad = Array(16)\n for (let i = 0; i < 16; i++) {\n ipad[i] = bkey[i] ^ 0x36363636\n opad[i] = bkey[i] ^ 0x5c5c5c5c\n }\n\n let hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz)\n return core_sha1(opad.concat(hash), 512 + 160)\n}\n\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\nfunction safe_add(x: number, y: number) {\n const lsw = (x & 0xffff) + (y & 0xffff)\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16)\n return (msw << 16) | (lsw & 0xffff)\n}\n\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\nfunction rol(num: number, cnt: number) {\n return (num << cnt) | (num >>> (32 - cnt))\n}\n\n/*\n * Convert an 8-bit or 16-bit string to an array of big-endian words\n * In 8-bit function, characters >255 have their hi-byte silently ignored.\n */\nfunction str2binb(str: string): Array<number> {\n const bin: Array<number> = []\n const mask = (1 << chrsz) - 1\n for (let i = 0; i < str.length * chrsz; i += chrsz)\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - (i % 32))\n return bin\n}\n\n/*\n * Convert an array of big-endian words to a string\n */\nfunction binb2str(bin: Array<number>): string {\n let str = ''\n let mask = (1 << chrsz) - 1\n for (let i = 0; i < bin.length * 32; i += chrsz)\n str += String.fromCharCode((bin[i >> 5] >>> (32 - chrsz - (i % 32))) & mask)\n return str\n}\n\n/*\n * Convert an array of big-endian words to a hex string.\n */\nfunction binb2hex(binarray: Array<number>) {\n let hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i++) {\n str +=\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) +\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf)\n }\n return str\n}\n\n/*\n * Convert an array of big-endian words to a base-64 string\n */\nfunction binb2b64(binarray: Array<number>) {\n let tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i += 3) {\n let triplet =\n (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) << 16) |\n (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) & 0xff) << 8) |\n ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) & 0xff)\n for (let j = 0; j < 4; j++) {\n if (i * 8 + j * 6 > binarray.length * 32) str += b64pad\n else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)\n }\n }\n return str\n}\n","import { base64decode, sha1 } from './utils'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\n\nexport const STORE_CREDENTILAS_KEY = 'sdk-auth-credential'\n\ntype CredentialsCallback = (callback: Credentials) => void\ntype JSONCredentials = {\n access_token: string\n refresh_token: string\n expires_in: number\n expires_at: Date\n token_type: 'Bearer' | string\n}\n\nexport default class Credentials {\n static async fromStorage(storage: SecureStorageHandler): Promise<Credentials> {\n const str: string | null = await storage.getItem(STORE_CREDENTILAS_KEY)\n if (str == null || str == undefined) {\n throw new Error('No credentials found in storage.')\n }\n return Credentials.fromJSON(str)\n }\n\n static async toStorage(storage: SecureStorageHandler, credentials: Credentials): Promise<void> {\n await storage.setItem(STORE_CREDENTILAS_KEY, JSON.stringify(credentials))\n }\n\n static async clearFromStorage(storage: SecureStorageHandler): Promise<void> {\n await storage.deleteItem(STORE_CREDENTILAS_KEY)\n }\n\n static fromJSON(str: string): Credentials {\n const { access_token, refresh_token, expires_in } = JSON.parse(str)\n return new Credentials(access_token, refresh_token, expires_in)\n }\n\n static onStorageUpdate(storage: SecureStorageHandler, callback: CredentialsCallback): () => void {\n return storage.on(STORE_CREDENTILAS_KEY, (credentials: string | null) => {\n if (typeof credentials === 'string') {\n callback(Credentials.fromJSON(credentials))\n }\n })\n }\n\n static equals(a?: Credentials, b?: Credentials) {\n if (!a && !b) {\n return true\n }\n if ((a && !b) || (b && !a)) {\n return false\n }\n return (\n a?.access_token === b?.access_token &&\n a?._refresh_token === b?.refresh_token &&\n a?.expires_in === b?.expires_in\n )\n }\n\n /**\n * Used to access resources.\n */\n private _access_token: string\n /**\n * Used to obtain a new access token.\n */\n private _refresh_token: string\n /**\n * Number of seconds until the access token expires.\n * This value is calculated at the moment the access token is generated.\n */\n private _expires_in: number\n\n constructor(access_token: string, refresh_token: string, expires_in: number) {\n this._access_token = access_token\n this._refresh_token = refresh_token\n this._expires_in = expires_in\n }\n\n /**\n * Lists the claims present in the access token.\n */\n get claims() {\n const fallback = {}\n if (typeof this._access_token != 'string') {\n return fallback\n }\n const [, b64payload] = this._access_token.split('.')\n const payload = base64decode(b64payload)\n if (!payload) {\n return fallback\n }\n try {\n return JSON.parse(payload)\n } catch (err) {\n return {}\n }\n }\n\n get access_token(): string {\n return this._access_token\n }\n\n get refresh_token(): string {\n return this._refresh_token\n }\n\n get expires_in(): number {\n return this._expires_in\n }\n\n get token_type(): string {\n return 'Bearer'\n }\n\n get expires_at(): Date {\n if (typeof this.claims?.exp === 'number') {\n return new Date(this.claims?.exp * 1000)\n }\n const expiryDate = new Date()\n expiryDate.setSeconds(expiryDate.getSeconds() + this._expires_in)\n return expiryDate\n }\n\n isExpired(): boolean {\n return this.expires_at && new Date().getTime() > new Date(this.expires_at).getTime()\n }\n\n async getUepId(): Promise<string> {\n const { sub, uep_id: rawUepId } = this.claims \n if (!sub) {\n throw new Error(\"Missing 'sub' claim.\")\n }\n\n if (rawUepId) {\n return rawUepId\n }\n \n return await sha1(sub)\n }\n\n toJSON(): JSONCredentials {\n return {\n access_token: this._access_token,\n refresh_token: this._refresh_token,\n expires_in: this._expires_in,\n expires_at: this.expires_at,\n token_type: this.token_type,\n }\n }\n}\n","export interface JwtPayload {\n [key: string]: any\n iss?: string | undefined\n sub?: string | undefined\n aud?: string | string[] | undefined\n exp?: number | undefined\n nbf?: number | undefined\n iat?: number | undefined\n jti?: string | undefined\n}\n\nexport function decodeToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('No token provided')\n }\n const parts = token.split('.')\n\n if (parts.length !== 3) {\n throw new Error('JWT must have 3 parts')\n }\n\n const decoded = urlBase64Decode(parts[1])\n if (!decoded) {\n throw new Error('Cannot decode the token')\n }\n\n return JSON.parse(decoded)\n}\n\nfunction urlBase64Decode(str: string): string {\n let output = str.replace(/-/g, '+').replace(/_/g, '/')\n switch (output.length % 4) {\n case 0: {\n break\n }\n case 2: {\n output += '=='\n break\n }\n case 3: {\n output += '='\n break\n }\n default: {\n // TODO\n throw new Error('Illegal base64url string!')\n }\n }\n return b64DecodeUnicode(output)\n}\n\nfunction b64DecodeUnicode(str: any): any {\n return decodeURIComponent(\n Array.prototype.map\n .call(b64decode(str), (c: any) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join('')\n )\n}\n\nexport function b64decode(str: string): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\nexport function b64encode(input: string, encode = true) {\n let output = ''\n let chr1, chr2, chr3, enc1, enc2, enc3, enc4\n let i = 0\n const _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n if (encode) {\n input = _utf8_encode(input)\n }\n\n while (i < input.length) {\n chr1 = input.charCodeAt(i++)\n chr2 = input.charCodeAt(i++)\n chr3 = input.charCodeAt(i++)\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64\n } else if (isNaN(chr3)) {\n enc4 = 64\n }\n\n output =\n output +\n _keyStr.charAt(enc1) +\n _keyStr.charAt(enc2) +\n _keyStr.charAt(enc3) +\n _keyStr.charAt(enc4)\n }\n return output\n}\n\nexport function _utf8_encode(string: string) {\n string = string.replace(/\\r\\n/g, '\\n')\n let utftext = ''\n\n for (let n = 0; n < string.length; n++) {\n const c = string.charCodeAt(n)\n\n if (c < 128) {\n utftext += String.fromCharCode(c)\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n } else {\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n }\n return utftext\n}\n","export enum AuthenticatorEvents {\n CREDENTIALS = 'CREDENTIALS',\n ACCESS_TOKEN = 'ACCESS_TOKEN',\n JWT_PAYLOAD = 'JWT_PAYLOAD',\n STATE_CHANGE = 'STATE_CHANGE',\n ERROR = 'ERROR',\n}\n","import { Credentials } from '@dstny/scp-credentials'\n\nexport const STORE_CREDENTIALS_KEY = 'sdk-auth-credential'\nexport const STORE_REFRESH_SEPARATION_SECONDS = 'sdk-separation-seconds'\n\nexport type AuthenticatorState = boolean\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace'\nexport interface Logger {\n log(...arg: any[]): void\n error(...arg: any[]): void\n warn(...arg: any[]): void\n info(...arg: any[]): void\n debug(...arg: any[]): void\n trace(...arg: any[]): void\n\n setLevel(level: LogLevel, persist?: boolean): void\n resetLevel(): void\n}\n\nexport interface AuthenticatorOptions {\n credentials?: Credentials\n logger?: Logger\n}\n","import { SecureStorageHandler } from '@dstny/scp-storage'\nimport { STORE_REFRESH_SEPARATION_SECONDS } from '../types'\n\nexport const getRefreshSeparationMilliseconds = async (\n storage: SecureStorageHandler\n): Promise<number> => {\n const next = parseInt((await storage.getItem(STORE_REFRESH_SEPARATION_SECONDS)) || '0') || 0\n await storage.setItem(STORE_REFRESH_SEPARATION_SECONDS, '' + ((next + 5) % 60))\n return next * 1000\n}\n\n\n","class TokenNetworkError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Network unavailable to refresh the network', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'NetworkError'\n }\n}\n\nexport default TokenNetworkError\n","/**\n * This kind of exceptions are using for reporting error cases for refresh token action such as update, request and ect.\n */\nclass RefreshTokenError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your token or session is expired.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'RefreshTokenError'\n }\n}\n\nexport default RefreshTokenError\n","/**\n * Use it for authorization specific errors\n * Depends on reason of exception use proper type\n */\nclass AuthorizationError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Authorization failed', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'AuthorizationError'\n }\n}\n\nexport default AuthorizationError\n","/**\n * This kind of is launched when the configured client is invalid\n */\nclass InvalidClientError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your client is invalid.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'InvalidClientError'\n }\n}\n\nexport default InvalidClientError\n","import Emittery from 'emittery'\n\nimport { Credentials } from '@dstny/scp-credentials'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\nimport { AbstractAuthenticationApi } from './api/AbstractAuthenticationApi'\nimport { decodeToken, JwtPayload } from './utils/jwt'\nimport { AuthenticatorEvents } from './events'\nimport { AuthenticatorOptions, AuthenticatorState, Logger, STORE_CREDENTIALS_KEY } from './types'\nimport { getRefreshSeparationMilliseconds } from './utils/separation'\nimport TokenNetworkError from './errors/TokenNetworkError'\nimport RefreshTokenError from './errors/RefreshTokenError'\nimport AuthorizationError from './errors/AuthorizationError'\nimport InvalidClientError from './errors/InvalidClientError'\n\nconst INTERNAL_CREDENTIALS = 'INTERNAL_CREDENTIALS'\n\nclass Authenticator extends Emittery {\n private readonly api: AbstractAuthenticationApi\n private readonly secureStorage: SecureStorageHandler\n private readonly logger?: Logger\n private readonly initialCredentials?: Credentials\n\n private _state?: boolean = false\n private _credentials?: Credentials\n private _jwtPayload?: JwtPayload\n\n private isSetup: boolean = false\n private refreshTokenRunnerTimer?: any\n private refreshSeparationMilliseconds: number = 0\n private refreshTokenPromise?: Promise<Credentials>\n private removeCredentialStorageUpdates?: () => void\n private unsubscribeListenerAdded?: () => void\n private unsubscribeUpdateState?: () => void\n private timers: Map<ReturnType<typeof setTimeout>, (error: any) => void> = new Map()\n\n public get jwtPayload(): JwtPayload | undefined {\n return this._jwtPayload\n }\n\n public get credentials(): Credentials | undefined {\n return this._credentials\n }\n\n public get state(): AuthenticatorState {\n return this._state ?? false\n }\n\n /**\n *\n * @param {ConnectEmitter} globalEmitter\n * @param {API} api\n * @param {string} oauthUrl\n */\n constructor(\n api: AbstractAuthenticationApi,\n secureStorage: SecureStorageHandler,\n options?: AuthenticatorOptions\n ) {\n super()\n this.api = api\n this.secureStorage = secureStorage\n this.logger = options?.logger\n this.initialCredentials = options?.credentials\n }\n\n /**\n * Starts the authenticator\n */\n async setup(): Promise<void> {\n let credentials\n\n if (this.initialCredentials) {\n credentials = this.initialCredentials\n } else {\n const localStorageCredentials = await this.secureStorage.getItem(STORE_CREDENTIALS_KEY)\n if (typeof localStorageCredentials === 'string') {\n credentials = Credentials.fromJSON(localStorageCredentials)\n }\n }\n\n // When loading a second instance of ConnectMe on the same browser,\n // the second instance cannot use the refresh token at the same time\n // as the first instance. In that case they will try to use the same\n // refresh_token and the instance that comes last will be returned an error.\n\n // Two mechanisms are put in place to mitigate this:\n // - The first instance to obtain the refresh token will save it to the SecureStorageHandler.\n // Other instances will be notified of the new token. When an instance recevices\n // credentials from another instance they will reset their _setupRefreshTokenRunner,\n // effectively becoming slave from the first instance.\n // - An instance separation delay is added, which separates the refresh of each instance\n // by 5 seconds. Up to 12 instance supported. 60 secs / 5 seconds delay\n this.removeCredentialStorageUpdates = Credentials.onStorageUpdate(\n this.secureStorage,\n (credentials: Credentials) => {\n this._signInWithCredentials(credentials, true)\n }\n )\n // _refreshSeparationMilliseconds is used in _setupRefreshTokenRunner\n this.refreshSeparationMilliseconds = await getRefreshSeparationMilliseconds(this.secureStorage)\n\n // Emit current credentials/access_token/jwt if they are defined when someone registers a listener\n this.unsubscribeListenerAdded = this.on(Emittery.listenerAdded, ({ listener, eventName }) => {\n if (eventName === AuthenticatorEvents.CREDENTIALS && this._credentials) {\n listener(this._credentials)\n } else if (eventName === AuthenticatorEvents.ACCESS_TOKEN && this._credentials) {\n listener(decodeToken(this._credentials.access_token))\n } else if (eventName === AuthenticatorEvents.JWT_PAYLOAD && this._jwtPayload) {\n listener(this._jwtPayload)\n }\n })\n\n // Update jwt payload and state, and re-broadcast credentials update\n this.unsubscribeUpdateState = this.on(\n INTERNAL_CREDENTIALS,\n async ({ credentials, isFromOtherInstance }) => {\n if (Credentials.equals(this._credentials, credentials)) {\n return\n }\n this._credentials = credentials\n this.emit(AuthenticatorEvents.CREDENTIALS, credentials)\n if (credentials) {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, credentials.access_token)\n this._jwtPayload = decodeToken(credentials.access_token)\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, this._jwtPayload)\n this._state = true\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n if (isFromOtherInstance === false) {\n this.storeCredentials(credentials)\n }\n } else {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, undefined)\n this._jwtPayload = undefined\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, undefined)\n this._state = false\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n // Credentials are not removed from the store here as the user\n // might only be stopping the authenticator, not necessarily signin out.\n }\n }\n )\n\n this.isSetup = true\n\n if (credentials) {\n this.logger?.log('Has credentials:', credentials)\n await this._signInWithCredentials(credentials)\n }\n }\n\n /**\n * Destroys the ConnectAuth module.\n * This method is called when the user signs-out.\n *\n * @returns {Promise}\n */\n async destroy(): Promise<void> {\n this.refreshTokenRunnerTimer && clearTimeout(this.refreshTokenRunnerTimer)\n\n await this.emit(INTERNAL_CREDENTIALS, { credentials: undefined, isFromOtherInstance: false })\n\n if (this.unsubscribeListenerAdded) {\n this.unsubscribeListenerAdded()\n }\n if (this.unsubscribeUpdateState) {\n this.unsubscribeUpdateState()\n }\n\n this.isSetup = false\n\n for (const [timer, reject] of this.timers.entries()) {\n clearTimeout(timer)\n reject(new Error('Authenticator is being destroyed. Wait functions are rejected.'))\n }\n this.timers.clear()\n }\n\n /**\n * Waits for the given number of milliseconds before resolving the promise.\n *\n * @param waitMilliseconds\n * @returns {Promise<void>}\n */\n private wait(waitMilliseconds: number): Promise<void> {\n try {\n this.assertIsSetup()\n } catch (err) {\n return Promise.reject(err)\n }\n return new Promise((resolve, reject) => {\n const fn = () => {\n this.timers.delete(timer)\n resolve()\n }\n const timer = setTimeout(fn, waitMilliseconds)\n this.timers.set(timer, reject)\n })\n }\n\n /**\n * Generates the login uri for OAuth authentication.\n * Supports escaux-oauth and SMG providers.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<string>} The authorization URI.\n *\n * The browser should be redirected to this URI.\n */\n async getLoginUrl(redirectUri: string): Promise<string> {\n this.assertIsSetup()\n const loginUrl: string = await this.api.getLoginUrl(redirectUri)\n return loginUrl\n }\n\n /**\n * Sign-in the user. Using the authorization code, an access and refresh token\n * is retrieved from the OAuth server. These are stored in an Credentials object.\n *\n * @param {string} authorizationCode - The autorization code recieved from OAuth\n * once the user has authorized the request.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<Credentials>} The user Crendetials\n */\n async signIn(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n this.assertIsSetup()\n try {\n const credentials: Credentials = await this.api.getToken(authorizationCode, redirectUri)\n return await this._signInWithCredentials(credentials)\n } catch (error) {\n const authorizationError = new AuthorizationError(\n 'Failed to sign in with authorization code and redirect uri',\n { cause: error }\n )\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * Signs the user out.\n *\n * @returns {Promise<void>}\n */\n async signOut(remote?: boolean): Promise<void> {\n this.assertIsSetup()\n await this.secureStorage.deleteItem(STORE_CREDENTIALS_KEY)\n if (this.removeCredentialStorageUpdates) {\n this.removeCredentialStorageUpdates()\n this.removeCredentialStorageUpdates = undefined\n }\n\n const credentials = this.credentials\n\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: undefined,\n isFromOtherInstance: false,\n })\n\n try {\n if (credentials && remote !== false) {\n const { refresh_token, access_token } = credentials\n await this.api.logout(refresh_token, access_token)\n } else {\n this.logger?.log('No credentials were available. No action was executed on logout.')\n }\n } catch (error) {\n const authorizationError = new AuthorizationError('Failed to sign out the user', {\n cause: error,\n })\n this.emit(AuthenticatorEvents.ERROR, authorizationError)\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * On wake from sleep, we sign-in with the credentials to force the renewal of the credentials\n * if they expired during the sleep period.\n */\n public async sanityCheck(): Promise<void> {\n this.assertIsSetup()\n if (this._credentials) {\n try {\n await this._signInWithCredentials(this._credentials)\n } catch (error) {\n this.logger?.error('Failed to sign with credentials after sleep', error)\n }\n } else {\n this.logger?.info('No credentials available')\n }\n }\n\n /**\n * Indicates if there are valid credentials.\n *\n * Absent credentials or credentials which have expired are considered not valid.\n */\n public isTokenValid(): boolean {\n if (!this.credentials) {\n return false\n }\n return !this.credentials.isExpired()\n }\n\n public async signInWithCredentials(credentials: Credentials): Promise<Credentials> {\n this.assertIsSetup()\n return this._signInWithCredentials(credentials)\n }\n\n /**\n *\n * @param credentials\n * @returns {Promise<Credentials>}\n */\n private async _signInWithCredentials(\n credentials: Credentials,\n isFromOtherInstance: boolean = false\n ): Promise<Credentials> {\n this.logger?.log('signInWithCredentials')\n if (!credentials) {\n throw new Error('Invalid argument, credentials cannot be null or undefined.')\n }\n\n if (credentials?.isExpired()) {\n this._credentials = credentials\n await this.refreshTokenWithRetry()\n // _setupRefreshTokenRunner is setup in the refreshToken function\n } else {\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials,\n isFromOtherInstance,\n })\n this._setupRefreshTokenRunner()\n }\n\n if (!this._credentials) {\n throw new Error('Failed to authenticate')\n }\n\n return this._credentials\n }\n\n /**\n * Sets up a timeout which will automatically refresh the token.\n *\n * The timeout is calculated based on the value of the `expires_at` property of\n * the `Credentials`, the refresh is always scheduled at 80% of the token life-time.\n *\n * When there are multiple ConnectMe instances the refresh timeout can vary\n * up to 60 seconds.\n *\n * A token will never be refreshed before at least 60 seconds.\n *\n */\n private _setupRefreshTokenRunner(): void {\n clearTimeout(this.refreshTokenRunnerTimer)\n if (!this.credentials) {\n throw new Error('Unable to start refresh token runner without credentials')\n }\n const refreshIn: number = new Date(this.credentials.expires_at).getTime() - new Date().getTime()\n const refreshTimeout: number =\n this.refreshSeparationMilliseconds + Math.max(60000, refreshIn * 0.8) // Refresh 20% before the expires with a minimum of 60 sec\n this.logger?.info(\n `Setting timer to refresh token in ${Math.round(refreshTimeout / 1000)} seconds ` +\n `at ${new Date(new Date().getTime() + refreshTimeout).toTimeString()}`\n )\n this.refreshTokenRunnerTimer = setTimeout(async () => {\n try {\n await this.refreshToken()\n } catch (error) {\n const refreshTokenError = new RefreshTokenError(\n 'Refresh runner failed to refresh token with existing credentials',\n { cause: error }\n )\n this.emit(AuthenticatorEvents.ERROR, refreshTokenError)\n this.logger?.error(refreshTokenError)\n }\n }, refreshTimeout)\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method ensures that no parallel requests to refreshToken are done.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n async refreshToken(): Promise<Credentials> {\n this.assertIsSetup()\n if (this.refreshTokenPromise) {\n this.logger?.info('Refresh token already in progress: returning existing promise.')\n return await this.refreshTokenPromise\n }\n try {\n this.refreshTokenPromise = this._refreshToken()\n return await this.refreshTokenPromise\n } finally {\n this.refreshTokenPromise = undefined\n }\n }\n\n /**\n * Attempts the refresh the credentials.\n *\n * On failure it will throw an exception.\n * This method might end up signing the user out in case the refresh token are invalid.\n * It will not sign you out in case of network issues.\n *\n * @returns\n */\n async refreshTokenWithRetry(): Promise<Credentials> {\n this.assertIsSetup()\n const MAX_DEPTH = 7\n const MAX_TIMEOUT = 30 * 1000\n for (let depth = 0; depth < MAX_DEPTH; depth++) {\n try {\n return await this.refreshToken()\n } catch (err) {\n if (depth + 1 >= MAX_DEPTH) {\n throw err\n }\n if (err instanceof TokenNetworkError) {\n await this.wait(Math.min(2 ** depth * 1000, MAX_TIMEOUT))\n } else {\n throw err\n }\n }\n }\n return await this.refreshToken()\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method should only be called by `refreshToken`.\n *\n * Use `refreshToken` method if you need to refresh the token.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n private async _refreshToken(): Promise<Credentials> {\n this.logger?.info('Starting access token refresh')\n try {\n if (!this.credentials) {\n throw new Error('Failed to refresh token. No credentials available.')\n }\n const { refresh_token, access_token } = this.credentials\n const credentials = await this.api.refreshToken(refresh_token, access_token)\n this.logger?.info('Access token refreshed successfully')\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: credentials,\n isFromOtherInstance: false,\n })\n this._setupRefreshTokenRunner()\n return credentials\n } catch (error) {\n this.logger?.error('Failed to refresh token', error)\n if (error instanceof InvalidClientError) {\n if (typeof location !== 'undefined') {\n location.reload()\n } else {\n this.logger?.warn('Location reload not supported')\n throw error\n }\n }\n if (error instanceof RefreshTokenError) {\n await this.signOut(false)\n }\n throw error\n }\n }\n\n /**\n * Stores the credentials in secureStorage.\n *\n * @param {Credentials} credentials - The credentials to store in the secure storage.\n */\n private async storeCredentials(credentials: Credentials): Promise<void> {\n try {\n await this.secureStorage.setItem(STORE_CREDENTIALS_KEY, JSON.stringify(credentials))\n } catch (error: any) {\n this.logger?.error('Failed to store credentials in storage', error)\n }\n }\n\n private assertIsSetup() {\n if (!this.isSetup) {\n throw new Error('Authenticator needs to be setup before it can be used.')\n }\n }\n}\n\nexport default Authenticator\n","import { Credentials } from '@dstny/scp-credentials'\nimport axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\n\nexport abstract class AbstractAuthenticationApi {\n protected axiosInstance: AxiosInstance\n\n constructor(baseURL: string) {\n const config: AxiosRequestConfig = {\n baseURL,\n timeout: 50000,\n }\n this.axiosInstance = axios.create(config)\n }\n\n /**\n * Given a redirectUri it calculates the URL where the browser needs to be\n * redirected in other to authenticate\n *\n * @param {string} redirectUri\n * @returns {string} login url\n */\n abstract getLoginUrl(redirectUri: string): Promise<string>\n\n /**\n * Given the authorizationCode and the redirectUri this method will provide\n * credentials containing an access and refresh token\n *\n * @param {string} authorizationCode\n * @param {string} redirectUri\n * @returns {Promise<Credentials>}\n */\n abstract getToken(authorizationCode: string, redirectUri: string): Promise<Credentials>\n\n /**\n * Given a refresh token this method will provide a new set of credentials\n * containing an access token and a refresh token\n *\n * @param {string} refreshToken\n * @returns {Promise<Credentials>}\n */\n abstract refreshToken(refreshToken: string, accessToken: string): Promise<Credentials>\n\n /**\n * Given a access and refresh token, this method will logout the user from\n * the IAM\n *\n * @param {string} accessToken\n * @param {string} refreshToken\n * @returns {Promise<void>}\n */\n abstract logout(accessToken?: string, refreshToken?: string): Promise<void>\n}\n","/* eslint-disable no-async-promise-executor */\nimport { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport axios from 'axios'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetTokenResponse = {\n access_token: string\n refresh_token: string\n expires_in: number\n}\n\nexport class OAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly scope: string\n public readonly authorizationRoute: string\n\n private readonly baseURL: string\n\n constructor(baseURL: string, clientId: string, authorizationRoute: string, scope: string) {\n super(baseURL)\n this.baseURL = baseURL\n this.clientId = clientId\n this.authorizationRoute = authorizationRoute\n this.scope = scope\n }\n\n async getLoginUrl(redirectUri: string) {\n this.axiosInstance.getUri()\n return (\n `${this.baseURL}${this.authorizationRoute}` +\n `?client_id=${encodeURIComponent(this.clientId)}` +\n '&response_type=code' +\n `&redirect_uri=${encodeURIComponent(redirectUri)}` +\n (this.scope ? `&scope=${encodeURIComponent(this.scope)}` : '')\n )\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n code: authorizationCode,\n grant_type: 'authorization_code',\n redirect_uri: redirectUri,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async loginWithUsernamePassword(username: string, password: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'password',\n username,\n password,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const response = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n })\n )\n return new Credentials(\n response.data.access_token,\n response.data.refresh_token,\n response.data.expires_in\n )\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'unauthorized_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(_redirectUri?: string): Promise<void> {\n await this.axiosInstance.post('/logout', null, { withCredentials: true })\n }\n}\n","import { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport axios from 'axios'\nimport { decodeToken } from '../utils/jwt'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetLoginUrlResponse = {\n loginUrl: string\n}\n\ntype GetTokenResponse = {\n refreshToken: string\n accessToken: string\n message: string\n status: string\n}\n\nexport class SmgAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly realm: string\n\n constructor(baseURL: string, realm: string, clientId: string) {\n super(baseURL)\n this.clientId = clientId\n this.realm = realm\n }\n\n async getLoginUrl(redirectUri: string) {\n const { data } = await this.axiosInstance.get<GetLoginUrlResponse>(\n `/login/getloginurl/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`\n )\n\n const baseUrl = new URL(data.loginUrl)\n // The redirect_uri provided by the SMG is inacurate, this needs to be rewritten with the actual\n // redirect uri.\n baseUrl.searchParams.set('redirect_uri', redirectUri)\n // The authentication pathname of the SMG cannot be trusted to be configured correctly.\n // Duplicate '/' characters in the authentication URL causes the authentication\n // prompt to be displayed twice. Once when coven attempts to obtain a token, and\n // again when connect me attempts to obtain a token.\n // vv\n // example: https://keycloak.development.aws.d4sp.com//auth/realms/syslab1/protocol/openid-connect/auth\n baseUrl.pathname = baseUrl.pathname.replace(/\\/\\/+/g, '/')\n\n return baseUrl.toString()\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/getaccesstoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n code: authorizationCode,\n redirectUri: redirectUri,\n }\n )\n const { refreshToken, accessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(accessToken)\n const expires_in = exp - iat\n const expires_at = new Date()\n expires_at.setSeconds(expires_at.getSeconds() + expires_in)\n return new Credentials(accessToken, refreshToken, expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/refreshtoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n const { refreshToken: newRefreshToken, accessToken: newAccessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(newAccessToken)\n const expires_in = exp - iat\n return new Credentials(newAccessToken, newRefreshToken, expires_in)\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'invalid_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(refreshToken: string, accessToken: string): Promise<void> {\n await this.axiosInstance.post(\n `/login/logout/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n }\n}\n\nexport default SmgAuthApi\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,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,KAAK,IAAI,MAAM,KAAK,cAAc;AAAA,QACxC,6BAA6B,mBAAmB,KAAK,KAAK,CAAC,WAAW;AAAA,UACpE,KAAK;AAAA,QACP,CAAC;AAAA,QACD;AAAA,UACE,KAAK;AAAA,UACL;AAAA,QACF;AAAA,MACF;AACA,YAAM,EAAE,cAAc,iBAAiB,aAAa,eAAe,IAAI;AAEvE,YAAM,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,YAAY,cAAc;AACvD,YAAM,aAAa,MAAM;AACzB,aAAO,IAAI,YAAY,gBAAgB,iBAAiB,UAAU;AAAA,IACpE,SAAS,OAAO;AACd,UAAI,cAAAC,QAAM,aAAa,KAAK,GAAG;AAC7B,YAAI,MAAM,YAAY,iBAAiB;AACrC,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AACA,cAAM,aAAa,MAAM,UAAU;AACnC,YAAI,eAAe,OAAO,MAAM,UAAU,MAAM,UAAU,kBAAkB;AAC1E,gBAAM,IAAI,2BAAmB;AAAA,QAC/B;AACA,YAAI,OAAO,eAAe,YAAY,cAAc,OAAO,aAAa,KAAK;AAC3E,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,cAAsB,aAAoC;AACrE,UAAM,KAAK,cAAc;AAAA,MACvB,uBAAuB,mBAAmB,KAAK,KAAK,CAAC,WAAW;AAAA,QAC9D,KAAK;AAAA,MACP,CAAC;AAAA,MACD;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AhBzGA,IAAO,cAAQ;","names":["eventName","AuthenticatorEvents","credentials","axios","import_axios","axios","import_axios","axios"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/maps.js","../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/index.js","../../credentials/src/utils.ts","../../credentials/src/Credentials.ts","../src/utils/jwt.ts","../src/events.ts","../src/types.ts","../src/utils/separation.ts","../src/errors/TokenNetworkError.ts","../src/errors/RefreshTokenError.ts","../src/errors/AuthorizationError.ts","../src/errors/InvalidClientError.ts","../src/Authenticator.ts","../src/api/AbstractAuthenticationApi.ts","../src/api/OAuthApi.ts","../src/api/SmgAuthApi.ts"],"sourcesContent":["import Authenticator from './Authenticator'\n\nexport * from './types'\nexport * from './events'\n\nexport * from './api/AbstractAuthenticationApi'\nexport * from './api/OAuthApi'\nexport * from './api/SmgAuthApi'\n\nexport default Authenticator\n","export const anyMap = new WeakMap();\nexport const eventsMap = new WeakMap();\nexport const producersMap = new WeakMap();\n","import {anyMap, producersMap, eventsMap} from './maps.js';\n\nconst anyProducer = Symbol('anyProducer');\nconst resolvedPromise = Promise.resolve();\n\n// Define symbols for \"meta\" events.\nconst listenerAdded = Symbol('listenerAdded');\nconst listenerRemoved = Symbol('listenerRemoved');\n\nlet canEmitMetaEvents = false;\nlet isGlobalDebugEnabled = false;\n\nconst isEventKeyType = key => typeof key === 'string' || typeof key === 'symbol' || typeof key === 'number';\n\nfunction assertEventName(eventName) {\n\tif (!isEventKeyType(eventName)) {\n\t\tthrow new TypeError('`eventName` must be a string, symbol, or number');\n\t}\n}\n\nfunction assertListener(listener) {\n\tif (typeof listener !== 'function') {\n\t\tthrow new TypeError('listener must be a function');\n\t}\n}\n\nfunction getListeners(instance, eventName) {\n\tconst events = eventsMap.get(instance);\n\tif (!events.has(eventName)) {\n\t\treturn;\n\t}\n\n\treturn events.get(eventName);\n}\n\nfunction getEventProducers(instance, eventName) {\n\tconst key = isEventKeyType(eventName) ? eventName : anyProducer;\n\tconst producers = producersMap.get(instance);\n\tif (!producers.has(key)) {\n\t\treturn;\n\t}\n\n\treturn producers.get(key);\n}\n\nfunction enqueueProducers(instance, eventName, eventData) {\n\tconst producers = producersMap.get(instance);\n\tif (producers.has(eventName)) {\n\t\tfor (const producer of producers.get(eventName)) {\n\t\t\tproducer.enqueue(eventData);\n\t\t}\n\t}\n\n\tif (producers.has(anyProducer)) {\n\t\tconst item = Promise.all([eventName, eventData]);\n\t\tfor (const producer of producers.get(anyProducer)) {\n\t\t\tproducer.enqueue(item);\n\t\t}\n\t}\n}\n\nfunction iterator(instance, eventNames) {\n\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\tlet isFinished = false;\n\tlet flush = () => {};\n\tlet queue = [];\n\n\tconst producer = {\n\t\tenqueue(item) {\n\t\t\tqueue.push(item);\n\t\t\tflush();\n\t\t},\n\t\tfinish() {\n\t\t\tisFinished = true;\n\t\t\tflush();\n\t\t},\n\t};\n\n\tfor (const eventName of eventNames) {\n\t\tlet set = getEventProducers(instance, eventName);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tconst producers = producersMap.get(instance);\n\t\t\tproducers.set(eventName, set);\n\t\t}\n\n\t\tset.add(producer);\n\t}\n\n\treturn {\n\t\tasync next() {\n\t\t\tif (!queue) {\n\t\t\t\treturn {done: true};\n\t\t\t}\n\n\t\t\tif (queue.length === 0) {\n\t\t\t\tif (isFinished) {\n\t\t\t\t\tqueue = undefined;\n\t\t\t\t\treturn this.next();\n\t\t\t\t}\n\n\t\t\t\tawait new Promise(resolve => {\n\t\t\t\t\tflush = resolve;\n\t\t\t\t});\n\n\t\t\t\treturn this.next();\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdone: false,\n\t\t\t\tvalue: await queue.shift(),\n\t\t\t};\n\t\t},\n\n\t\tasync return(value) {\n\t\t\tqueue = undefined;\n\n\t\t\tfor (const eventName of eventNames) {\n\t\t\t\tconst set = getEventProducers(instance, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.delete(producer);\n\t\t\t\t\tif (set.size === 0) {\n\t\t\t\t\t\tconst producers = producersMap.get(instance);\n\t\t\t\t\t\tproducers.delete(eventName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tflush();\n\n\t\t\treturn arguments.length > 0\n\t\t\t\t? {done: true, value: await value}\n\t\t\t\t: {done: true};\n\t\t},\n\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t};\n}\n\nfunction defaultMethodNamesOrAssert(methodNames) {\n\tif (methodNames === undefined) {\n\t\treturn allEmitteryMethods;\n\t}\n\n\tif (!Array.isArray(methodNames)) {\n\t\tthrow new TypeError('`methodNames` must be an array of strings');\n\t}\n\n\tfor (const methodName of methodNames) {\n\t\tif (!allEmitteryMethods.includes(methodName)) {\n\t\t\tif (typeof methodName !== 'string') {\n\t\t\t\tthrow new TypeError('`methodNames` element must be a string');\n\t\t\t}\n\n\t\t\tthrow new Error(`${methodName} is not Emittery method`);\n\t\t}\n\t}\n\n\treturn methodNames;\n}\n\nconst isMetaEvent = eventName => eventName === listenerAdded || eventName === listenerRemoved;\n\nfunction emitMetaEvent(emitter, eventName, eventData) {\n\tif (!isMetaEvent(eventName)) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tcanEmitMetaEvents = true;\n\t\temitter.emit(eventName, eventData);\n\t} finally {\n\t\tcanEmitMetaEvents = false;\n\t}\n}\n\nexport default class Emittery {\n\tstatic mixin(emitteryPropertyName, methodNames) {\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\t\treturn target => {\n\t\t\tif (typeof target !== 'function') {\n\t\t\t\tthrow new TypeError('`target` must be function');\n\t\t\t}\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tif (target.prototype[methodName] !== undefined) {\n\t\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction getEmitteryProperty() {\n\t\t\t\tObject.defineProperty(this, emitteryPropertyName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: new Emittery(),\n\t\t\t\t});\n\t\t\t\treturn this[emitteryPropertyName];\n\t\t\t}\n\n\t\t\tObject.defineProperty(target.prototype, emitteryPropertyName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tget: getEmitteryProperty,\n\t\t\t});\n\n\t\t\tconst emitteryMethodCaller = methodName => function (...args) {\n\t\t\t\treturn this[emitteryPropertyName][methodName](...args);\n\t\t\t};\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tObject.defineProperty(target.prototype, methodName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: emitteryMethodCaller(methodName),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn target;\n\t\t};\n\t}\n\n\tstatic get isDebugEnabled() {\n\t\t// In a browser environment, `globalThis.process` can potentially reference a DOM Element with a `#process` ID,\n\t\t// so instead of just type checking `globalThis.process`, we need to make sure that `globalThis.process.env` exists.\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tif (typeof globalThis.process?.env !== 'object') {\n\t\t\treturn isGlobalDebugEnabled;\n\t\t}\n\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tconst {env} = globalThis.process ?? {env: {}};\n\t\treturn env.DEBUG === 'emittery' || env.DEBUG === '*' || isGlobalDebugEnabled;\n\t}\n\n\tstatic set isDebugEnabled(newValue) {\n\t\tisGlobalDebugEnabled = newValue;\n\t}\n\n\tconstructor(options = {}) {\n\t\tanyMap.set(this, new Set());\n\t\teventsMap.set(this, new Map());\n\t\tproducersMap.set(this, new Map());\n\n\t\tproducersMap.get(this).set(anyProducer, new Set());\n\n\t\tthis.debug = options.debug ?? {};\n\n\t\tif (this.debug.enabled === undefined) {\n\t\t\tthis.debug.enabled = false;\n\t\t}\n\n\t\tif (!this.debug.logger) {\n\t\t\tthis.debug.logger = (type, debugName, eventName, eventData) => {\n\t\t\t\ttry {\n\t\t\t\t\t// TODO: Use https://github.com/sindresorhus/safe-stringify when the package is more mature. Just copy-paste the code.\n\t\t\t\t\teventData = JSON.stringify(eventData);\n\t\t\t\t} catch {\n\t\t\t\t\teventData = `Object with the following keys failed to stringify: ${Object.keys(eventData).join(',')}`;\n\t\t\t\t}\n\n\t\t\t\tif (typeof eventName === 'symbol' || typeof eventName === 'number') {\n\t\t\t\t\teventName = eventName.toString();\n\t\t\t\t}\n\n\t\t\t\tconst currentTime = new Date();\n\t\t\t\tconst logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;\n\t\t\t\tconsole.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\\n\\tdata: ${eventData}`);\n\t\t\t};\n\t\t}\n\t}\n\n\tlogIfDebugEnabled(type, eventName, eventData) {\n\t\tif (Emittery.isDebugEnabled || this.debug.enabled) {\n\t\t\tthis.debug.logger(type, this.debug.name, eventName, eventData);\n\t\t}\n\t}\n\n\ton(eventNames, listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tlet set = getListeners(this, eventName);\n\t\t\tif (!set) {\n\t\t\t\tset = new Set();\n\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\tevents.set(eventName, set);\n\t\t\t}\n\n\t\t\tset.add(listener);\n\n\t\t\tthis.logIfDebugEnabled('subscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerAdded, {eventName, listener});\n\t\t\t}\n\t\t}\n\n\t\tconst off = () => {\n\t\t\tthis.off(eventNames, listener);\n\t\t\tsignal?.removeEventListener('abort', off);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', off, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toff();\n\t\t}\n\n\t\treturn off;\n\t}\n\n\toff(eventNames, listener) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tconst set = getListeners(this, eventName);\n\t\t\tif (set) {\n\t\t\t\tset.delete(listener);\n\t\t\t\tif (set.size === 0) {\n\t\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\t\tevents.delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.logIfDebugEnabled('unsubscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerRemoved, {eventName, listener});\n\t\t\t}\n\t\t}\n\t}\n\n\tonce(eventNames) {\n\t\tlet off_;\n\n\t\tconst promise = new Promise(resolve => {\n\t\t\toff_ = this.on(eventNames, data => {\n\t\t\t\toff_();\n\t\t\t\tresolve(data);\n\t\t\t});\n\t\t});\n\n\t\tpromise.off = off_;\n\t\treturn promise;\n\t}\n\n\tevents(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t}\n\n\t\treturn iterator(this, eventNames);\n\t}\n\n\tasync emit(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emit', eventName, eventData);\n\n\t\tenqueueProducers(this, eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\tawait Promise.all([\n\t\t\t...staticListeners.map(async listener => {\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\treturn listener(eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t\t...staticAnyListeners.map(async listener => {\n\t\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\t\treturn listener(eventName, eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t]);\n\t}\n\n\tasync emitSerial(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emitSerial', eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\t/* eslint-disable no-await-in-loop */\n\t\tfor (const listener of staticListeners) {\n\t\t\tif (listeners.has(listener)) {\n\t\t\t\tawait listener(eventData);\n\t\t\t}\n\t\t}\n\n\t\tfor (const listener of staticAnyListeners) {\n\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\tawait listener(eventName, eventData);\n\t\t\t}\n\t\t}\n\t\t/* eslint-enable no-await-in-loop */\n\t}\n\n\tonAny(listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('subscribeAny', undefined, undefined);\n\n\t\tanyMap.get(this).add(listener);\n\t\temitMetaEvent(this, listenerAdded, {listener});\n\n\t\tconst offAny = () => {\n\t\t\tthis.offAny(listener);\n\t\t\tsignal?.removeEventListener('abort', offAny);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', offAny, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toffAny();\n\t\t}\n\n\t\treturn offAny;\n\t}\n\n\tanyEvent() {\n\t\treturn iterator(this);\n\t}\n\n\toffAny(listener) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('unsubscribeAny', undefined, undefined);\n\n\t\temitMetaEvent(this, listenerRemoved, {listener});\n\t\tanyMap.get(this).delete(listener);\n\t}\n\n\tclearListeners(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tthis.logIfDebugEnabled('clear', eventName, undefined);\n\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tconst set = getListeners(this, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.clear();\n\t\t\t\t}\n\n\t\t\t\tconst producers = getEventProducers(this, eventName);\n\t\t\t\tif (producers) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tanyMap.get(this).clear();\n\n\t\t\t\tfor (const [eventName, listeners] of eventsMap.get(this).entries()) {\n\t\t\t\t\tlisteners.clear();\n\t\t\t\t\teventsMap.get(this).delete(eventName);\n\t\t\t\t}\n\n\t\t\t\tfor (const [eventName, producers] of producersMap.get(this).entries()) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t\tproducersMap.get(this).delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlistenerCount(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tlet count = 0;\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tcount += anyMap.get(this).size\n\t\t\t\t\t+ (getListeners(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this)?.size ?? 0);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (eventName !== undefined) {\n\t\t\t\tassertEventName(eventName);\n\t\t\t}\n\n\t\t\tcount += anyMap.get(this).size;\n\n\t\t\tfor (const value of eventsMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\n\t\t\tfor (const value of producersMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tbindMethods(target, methodNames) {\n\t\tif (typeof target !== 'object' || target === null) {\n\t\t\tthrow new TypeError('`target` must be an object');\n\t\t}\n\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\n\t\tfor (const methodName of methodNames) {\n\t\t\tif (target[methodName] !== undefined) {\n\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t}\n\n\t\t\tObject.defineProperty(target, methodName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: this[methodName].bind(this),\n\t\t\t});\n\t\t}\n\t}\n}\n\nconst allEmitteryMethods = Object.getOwnPropertyNames(Emittery.prototype).filter(v => v !== 'constructor');\n\nObject.defineProperty(Emittery, 'listenerAdded', {\n\tvalue: listenerAdded,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\nObject.defineProperty(Emittery, 'listenerRemoved', {\n\tvalue: listenerRemoved,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\n","// declare const Buffer\n\nfunction byteToPercent(b: string) {\n return `%${`00${b.charCodeAt(0).toString(16)}`.slice(-2)}`\n}\n\nexport function base64decode(str: string): string | undefined {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\n\nexport async function sha1(str: string) {\n if (typeof crypto === 'object') {\n const hash = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(str))\n return Array.from(new Uint8Array(hash))\n .map((v) => v.toString(16).padStart(2, '0'))\n .join('')\n } else {\n return binb2hex(core_sha1(str2binb(str), str.length * chrsz))\n }\n}\n\nconst hexcase = 0 /* hex output format. 0 - lowercase; 1 - uppercase */\nconst b64pad = '' /* base-64 pad character. \"=\" for strict RFC compliance */\nconst chrsz = 8 /* bits per input character. 8 - ASCII; 16 - Unicode */\n\n/*\n * Calculate the SHA-1 of an array of big-endian words, and a bit length\n */\nfunction core_sha1(x: Array<number>, len: number) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - (len % 32))\n x[(((len + 64) >> 9) << 4) + 15] = len\n\n var w = Array(80)\n var a = 1732584193\n var b = -271733879\n var c = -1732584194\n var d = 271733878\n var e = -1009589776\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a\n var oldb = b\n var oldc = c\n var oldd = d\n var olde = e\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j]\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)\n var t = safe_add(\n safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n safe_add(safe_add(e, w[j]), sha1_kt(j))\n )\n e = d\n d = c\n c = rol(b, 30)\n b = a\n a = t\n }\n\n a = safe_add(a, olda)\n b = safe_add(b, oldb)\n c = safe_add(c, oldc)\n d = safe_add(d, oldd)\n e = safe_add(e, olde)\n }\n return Array(a, b, c, d, e)\n}\n\n/*\n * Perform the appropriate triplet combination function for the current\n * iteration\n */\nfunction sha1_ft(t: number, b: number, c: number, d: number) {\n if (t < 20) return (b & c) | (~b & d)\n if (t < 40) return b ^ c ^ d\n if (t < 60) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\n/*\n * Determine the appropriate additive constant for the current iteration\n */\nfunction sha1_kt(t: number) {\n return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514\n}\n\n/*\n * Calculate the HMAC-SHA1 of a key and some data\n */\nfunction core_hmac_sha1(key: string, data: string) {\n let bkey = str2binb(key)\n if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz)\n\n let ipad = Array(16),\n opad = Array(16)\n for (let i = 0; i < 16; i++) {\n ipad[i] = bkey[i] ^ 0x36363636\n opad[i] = bkey[i] ^ 0x5c5c5c5c\n }\n\n let hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz)\n return core_sha1(opad.concat(hash), 512 + 160)\n}\n\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\nfunction safe_add(x: number, y: number) {\n const lsw = (x & 0xffff) + (y & 0xffff)\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16)\n return (msw << 16) | (lsw & 0xffff)\n}\n\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\nfunction rol(num: number, cnt: number) {\n return (num << cnt) | (num >>> (32 - cnt))\n}\n\n/*\n * Convert an 8-bit or 16-bit string to an array of big-endian words\n * In 8-bit function, characters >255 have their hi-byte silently ignored.\n */\nfunction str2binb(str: string): Array<number> {\n const bin: Array<number> = []\n const mask = (1 << chrsz) - 1\n for (let i = 0; i < str.length * chrsz; i += chrsz)\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - (i % 32))\n return bin\n}\n\n/*\n * Convert an array of big-endian words to a string\n */\nfunction binb2str(bin: Array<number>): string {\n let str = ''\n let mask = (1 << chrsz) - 1\n for (let i = 0; i < bin.length * 32; i += chrsz)\n str += String.fromCharCode((bin[i >> 5] >>> (32 - chrsz - (i % 32))) & mask)\n return str\n}\n\n/*\n * Convert an array of big-endian words to a hex string.\n */\nfunction binb2hex(binarray: Array<number>) {\n let hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i++) {\n str +=\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) +\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf)\n }\n return str\n}\n\n/*\n * Convert an array of big-endian words to a base-64 string\n */\nfunction binb2b64(binarray: Array<number>) {\n let tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i += 3) {\n let triplet =\n (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) << 16) |\n (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) & 0xff) << 8) |\n ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) & 0xff)\n for (let j = 0; j < 4; j++) {\n if (i * 8 + j * 6 > binarray.length * 32) str += b64pad\n else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)\n }\n }\n return str\n}\n","import { base64decode, sha1 } from './utils'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\n\nexport const STORE_CREDENTILAS_KEY = 'sdk-auth-credential'\n\ntype CredentialsCallback = (callback: Credentials) => void\ntype JSONCredentials = {\n access_token: string\n refresh_token: string\n expires_in: number\n expires_at: Date\n token_type: 'Bearer' | string\n}\n\nexport default class Credentials {\n static async fromStorage(storage: SecureStorageHandler): Promise<Credentials> {\n const str: string | null = await storage.getItem(STORE_CREDENTILAS_KEY)\n if (str == null || str == undefined) {\n throw new Error('No credentials found in storage.')\n }\n return Credentials.fromJSON(str)\n }\n\n static async toStorage(storage: SecureStorageHandler, credentials: Credentials): Promise<void> {\n await storage.setItem(STORE_CREDENTILAS_KEY, JSON.stringify(credentials))\n }\n\n static async clearFromStorage(storage: SecureStorageHandler): Promise<void> {\n await storage.deleteItem(STORE_CREDENTILAS_KEY)\n }\n\n static fromJSON(str: string): Credentials {\n const { access_token, refresh_token, expires_in } = JSON.parse(str)\n return new Credentials(access_token, refresh_token, expires_in)\n }\n\n static onStorageUpdate(storage: SecureStorageHandler, callback: CredentialsCallback): () => void {\n return storage.on(STORE_CREDENTILAS_KEY, (credentials: string | null) => {\n if (typeof credentials === 'string') {\n callback(Credentials.fromJSON(credentials))\n }\n })\n }\n\n static equals(a?: Credentials, b?: Credentials) {\n if (!a && !b) {\n return true\n }\n if ((a && !b) || (b && !a)) {\n return false\n }\n return (\n a?.access_token === b?.access_token &&\n a?._refresh_token === b?.refresh_token &&\n a?.expires_in === b?.expires_in\n )\n }\n\n /**\n * Used to access resources.\n */\n private _access_token: string\n /**\n * Used to obtain a new access token.\n */\n private _refresh_token: string\n /**\n * Number of seconds until the access token expires.\n * This value is calculated at the moment the access token is generated.\n */\n private _expires_in: number\n\n constructor(access_token: string, refresh_token: string, expires_in: number) {\n this._access_token = access_token\n this._refresh_token = refresh_token\n this._expires_in = expires_in\n }\n\n /**\n * Lists the claims present in the access token.\n */\n get claims() {\n const fallback = {}\n if (typeof this._access_token != 'string') {\n return fallback\n }\n const [, b64payload] = this._access_token.split('.')\n const payload = base64decode(b64payload)\n if (!payload) {\n return fallback\n }\n try {\n return JSON.parse(payload)\n } catch (err) {\n return {}\n }\n }\n\n get access_token(): string {\n return this._access_token\n }\n\n get refresh_token(): string {\n return this._refresh_token\n }\n\n get expires_in(): number {\n return this._expires_in\n }\n\n get token_type(): string {\n return 'Bearer'\n }\n\n get expires_at(): Date {\n if (typeof this.claims?.exp === 'number') {\n return new Date(this.claims?.exp * 1000)\n }\n const expiryDate = new Date()\n expiryDate.setSeconds(expiryDate.getSeconds() + this._expires_in)\n return expiryDate\n }\n\n isExpired(): boolean {\n return this.expires_at && new Date().getTime() > new Date(this.expires_at).getTime()\n }\n\n async getUepId(): Promise<string> {\n const { sub, uep_id: rawUepId } = this.claims \n if (!sub) {\n throw new Error(\"Missing 'sub' claim.\")\n }\n\n if (rawUepId) {\n return rawUepId\n }\n \n return await sha1(sub)\n }\n\n toJSON(): JSONCredentials {\n return {\n access_token: this._access_token,\n refresh_token: this._refresh_token,\n expires_in: this._expires_in,\n expires_at: this.expires_at,\n token_type: this.token_type,\n }\n }\n}\n","export interface JwtPayload {\n [key: string]: any\n iss?: string | undefined\n sub?: string | undefined\n aud?: string | string[] | undefined\n exp?: number | undefined\n nbf?: number | undefined\n iat?: number | undefined\n jti?: string | undefined\n}\n\nexport function decodeToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('No token provided')\n }\n const parts = token.split('.')\n\n if (parts.length !== 3) {\n throw new Error('JWT must have 3 parts')\n }\n\n const decoded = urlBase64Decode(parts[1])\n if (!decoded) {\n throw new Error('Cannot decode the token')\n }\n\n return JSON.parse(decoded)\n}\n\nfunction urlBase64Decode(str: string): string {\n let output = str.replace(/-/g, '+').replace(/_/g, '/')\n switch (output.length % 4) {\n case 0: {\n break\n }\n case 2: {\n output += '=='\n break\n }\n case 3: {\n output += '='\n break\n }\n default: {\n // TODO\n throw new Error('Illegal base64url string!')\n }\n }\n return b64DecodeUnicode(output)\n}\n\nfunction b64DecodeUnicode(str: any): any {\n return decodeURIComponent(\n Array.prototype.map\n .call(b64decode(str), (c: any) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join('')\n )\n}\n\nexport function b64decode(str: string): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\nexport function b64encode(input: string, encode = true) {\n let output = ''\n let chr1, chr2, chr3, enc1, enc2, enc3, enc4\n let i = 0\n const _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n if (encode) {\n input = _utf8_encode(input)\n }\n\n while (i < input.length) {\n chr1 = input.charCodeAt(i++)\n chr2 = input.charCodeAt(i++)\n chr3 = input.charCodeAt(i++)\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64\n } else if (isNaN(chr3)) {\n enc4 = 64\n }\n\n output =\n output +\n _keyStr.charAt(enc1) +\n _keyStr.charAt(enc2) +\n _keyStr.charAt(enc3) +\n _keyStr.charAt(enc4)\n }\n return output\n}\n\nexport function _utf8_encode(string: string) {\n string = string.replace(/\\r\\n/g, '\\n')\n let utftext = ''\n\n for (let n = 0; n < string.length; n++) {\n const c = string.charCodeAt(n)\n\n if (c < 128) {\n utftext += String.fromCharCode(c)\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n } else {\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n }\n return utftext\n}\n","export enum AuthenticatorEvents {\n CREDENTIALS = 'CREDENTIALS',\n ACCESS_TOKEN = 'ACCESS_TOKEN',\n JWT_PAYLOAD = 'JWT_PAYLOAD',\n STATE_CHANGE = 'STATE_CHANGE',\n ERROR = 'ERROR',\n}\n","import { Credentials } from '@dstny/scp-credentials'\n\nexport const STORE_CREDENTIALS_KEY = 'sdk-auth-credential'\nexport const STORE_REFRESH_SEPARATION_SECONDS = 'sdk-separation-seconds'\n\nexport type AuthenticatorState = boolean\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace'\nexport interface Logger {\n log(...arg: any[]): void\n error(...arg: any[]): void\n warn(...arg: any[]): void\n info(...arg: any[]): void\n debug(...arg: any[]): void\n trace(...arg: any[]): void\n\n setLevel(level: LogLevel, persist?: boolean): void\n resetLevel(): void\n}\n\nexport interface AuthenticatorOptions {\n /**\n * The authenticator library will try to use these credentials\n * when the setup method is invoked.\n *\n * This might be useful if you already have credentials available\n * and want to avoid doing the authentication procedure.\n */\n credentials?: Credentials\n /**\n * The authenticator library will use this logger instance for its\n * log statements.\n */\n logger?: Logger\n}\n","import { SecureStorageHandler } from '@dstny/scp-storage'\nimport { STORE_REFRESH_SEPARATION_SECONDS } from '../types'\n\nexport const getRefreshSeparationMilliseconds = async (\n storage: SecureStorageHandler\n): Promise<number> => {\n const next = parseInt((await storage.getItem(STORE_REFRESH_SEPARATION_SECONDS)) || '0') || 0\n await storage.setItem(STORE_REFRESH_SEPARATION_SECONDS, '' + ((next + 5) % 60))\n return next * 1000\n}\n\n\n","class TokenNetworkError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Network unavailable to refresh the network', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'NetworkError'\n }\n}\n\nexport default TokenNetworkError\n","/**\n * This kind of exceptions are using for reporting error cases for refresh token action such as update, request and ect.\n */\nclass RefreshTokenError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your token or session is expired.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'RefreshTokenError'\n }\n}\n\nexport default RefreshTokenError\n","/**\n * Use it for authorization specific errors\n * Depends on reason of exception use proper type\n */\nclass AuthorizationError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Authorization failed', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'AuthorizationError'\n }\n}\n\nexport default AuthorizationError\n","/**\n * This kind of is launched when the configured client is invalid\n */\nclass InvalidClientError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your client is invalid.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'InvalidClientError'\n }\n}\n\nexport default InvalidClientError\n","import Emittery from 'emittery'\n\nimport { Credentials } from '@dstny/scp-credentials'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\nimport { AbstractAuthenticationApi } from './api/AbstractAuthenticationApi'\nimport { decodeToken, JwtPayload } from './utils/jwt'\nimport { AuthenticatorEvents } from './events'\nimport { AuthenticatorOptions, AuthenticatorState, Logger, STORE_CREDENTIALS_KEY } from './types'\nimport { getRefreshSeparationMilliseconds } from './utils/separation'\nimport TokenNetworkError from './errors/TokenNetworkError'\nimport RefreshTokenError from './errors/RefreshTokenError'\nimport AuthorizationError from './errors/AuthorizationError'\nimport InvalidClientError from './errors/InvalidClientError'\n\nconst INTERNAL_CREDENTIALS = 'INTERNAL_CREDENTIALS'\n\nclass Authenticator extends Emittery {\n private readonly api: AbstractAuthenticationApi\n private readonly secureStorage: SecureStorageHandler\n private readonly logger?: Logger\n private readonly initialCredentials?: Credentials\n\n private _state?: boolean = false\n private _credentials?: Credentials\n private _jwtPayload?: JwtPayload\n\n private isSetup: boolean = false\n private refreshTokenRunnerTimer?: any\n private refreshSeparationMilliseconds: number = 0\n private refreshTokenPromise?: Promise<Credentials>\n private removeCredentialStorageUpdates?: () => void\n private unsubscribeListenerAdded?: () => void\n private unsubscribeUpdateState?: () => void\n private timers: Map<ReturnType<typeof setTimeout>, (error: any) => void> = new Map()\n\n /**\n * In some cases we don't want to trigger the logout automatically\n * on refresh failure.\n *\n * When defined, this method will be invoked after the refresh failure\n * allowing you to define the behavior in that case.\n *\n * Example: You might not want sign out the user immediately\n * when your application is handling calls and you have ongoing calls.\n *\n * @returns {Promise<void>}\n */\n public delegateSignOutOnRefreshFailure?: () => Promise<void>\n\n public get jwtPayload(): JwtPayload | undefined {\n return this._jwtPayload\n }\n\n public get credentials(): Credentials | undefined {\n return this._credentials\n }\n\n public get state(): AuthenticatorState {\n return this._state ?? false\n }\n\n /**\n *\n * @param {ConnectEmitter} globalEmitter\n * @param {API} api\n * @param {string} oauthUrl\n */\n constructor(\n api: AbstractAuthenticationApi,\n secureStorage: SecureStorageHandler,\n options?: AuthenticatorOptions\n ) {\n super()\n this.api = api\n this.secureStorage = secureStorage\n this.logger = options?.logger\n this.initialCredentials = options?.credentials\n }\n\n /**\n * Starts the authenticator\n */\n async setup(): Promise<void> {\n let credentials\n\n if (this.initialCredentials) {\n credentials = this.initialCredentials\n } else {\n const localStorageCredentials = await this.secureStorage.getItem(STORE_CREDENTIALS_KEY)\n if (typeof localStorageCredentials === 'string') {\n credentials = Credentials.fromJSON(localStorageCredentials)\n }\n }\n\n // When loading a second instance of ConnectMe on the same browser,\n // the second instance cannot use the refresh token at the same time\n // as the first instance. In that case they will try to use the same\n // refresh_token and the instance that comes last will be returned an error.\n\n // Two mechanisms are put in place to mitigate this:\n // - The first instance to obtain the refresh token will save it to the SecureStorageHandler.\n // Other instances will be notified of the new token. When an instance recevices\n // credentials from another instance they will reset their _setupRefreshTokenRunner,\n // effectively becoming slave from the first instance.\n // - An instance separation delay is added, which separates the refresh of each instance\n // by 5 seconds. Up to 12 instance supported. 60 secs / 5 seconds delay\n this.removeCredentialStorageUpdates = Credentials.onStorageUpdate(\n this.secureStorage,\n (credentials: Credentials) => {\n this._signInWithCredentials(credentials, true)\n }\n )\n // _refreshSeparationMilliseconds is used in _setupRefreshTokenRunner\n this.refreshSeparationMilliseconds = await getRefreshSeparationMilliseconds(this.secureStorage)\n\n // Emit current credentials/access_token/jwt if they are defined when someone registers a listener\n this.unsubscribeListenerAdded = this.on(Emittery.listenerAdded, ({ listener, eventName }) => {\n if (eventName === AuthenticatorEvents.CREDENTIALS && this._credentials) {\n listener(this._credentials)\n } else if (eventName === AuthenticatorEvents.ACCESS_TOKEN && this._credentials) {\n listener(decodeToken(this._credentials.access_token))\n } else if (eventName === AuthenticatorEvents.JWT_PAYLOAD && this._jwtPayload) {\n listener(this._jwtPayload)\n }\n })\n\n // Update jwt payload and state, and re-broadcast credentials update\n this.unsubscribeUpdateState = this.on(\n INTERNAL_CREDENTIALS,\n async ({ credentials, isFromOtherInstance }) => {\n if (Credentials.equals(this._credentials, credentials)) {\n return\n }\n this._credentials = credentials\n this.emit(AuthenticatorEvents.CREDENTIALS, credentials)\n if (credentials) {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, credentials.access_token)\n this._jwtPayload = decodeToken(credentials.access_token)\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, this._jwtPayload)\n this._state = true\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n if (isFromOtherInstance === false) {\n this.storeCredentials(credentials)\n }\n } else {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, undefined)\n this._jwtPayload = undefined\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, undefined)\n this._state = false\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n // Credentials are not removed from the store here as the user\n // might only be stopping the authenticator, not necessarily signin out.\n }\n }\n )\n\n this.isSetup = true\n\n if (credentials) {\n this.logger?.log('Has credentials:', credentials)\n await this._signInWithCredentials(credentials)\n }\n }\n\n /**\n * Destroys the ConnectAuth module.\n * This method is called when the user signs-out.\n *\n * @returns {Promise}\n */\n async destroy(): Promise<void> {\n this.refreshTokenRunnerTimer && clearTimeout(this.refreshTokenRunnerTimer)\n\n await this.emit(INTERNAL_CREDENTIALS, { credentials: undefined, isFromOtherInstance: false })\n\n if (this.unsubscribeListenerAdded) {\n this.unsubscribeListenerAdded()\n }\n if (this.unsubscribeUpdateState) {\n this.unsubscribeUpdateState()\n }\n\n this.isSetup = false\n\n for (const [timer, reject] of this.timers.entries()) {\n clearTimeout(timer)\n reject(new Error('Authenticator is being destroyed. Wait functions are rejected.'))\n }\n this.timers.clear()\n }\n\n /**\n * Waits for the given number of milliseconds before resolving the promise.\n *\n * @param waitMilliseconds\n * @returns {Promise<void>}\n */\n private wait(waitMilliseconds: number): Promise<void> {\n try {\n this.assertIsSetup()\n } catch (err) {\n return Promise.reject(err)\n }\n return new Promise((resolve, reject) => {\n const fn = () => {\n this.timers.delete(timer)\n resolve()\n }\n const timer = setTimeout(fn, waitMilliseconds)\n this.timers.set(timer, reject)\n })\n }\n\n /**\n * Generates the login uri for OAuth authentication.\n * Supports escaux-oauth and SMG providers.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<string>} The authorization URI.\n *\n * The browser should be redirected to this URI.\n */\n async getLoginUrl(redirectUri: string): Promise<string> {\n this.assertIsSetup()\n const loginUrl: string = await this.api.getLoginUrl(redirectUri)\n return loginUrl\n }\n\n /**\n * Sign-in the user. Using the authorization code, an access and refresh token\n * is retrieved from the OAuth server. These are stored in an Credentials object.\n *\n * @param {string} authorizationCode - The autorization code recieved from OAuth\n * once the user has authorized the request.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<Credentials>} The user Crendetials\n */\n async signIn(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n this.assertIsSetup()\n try {\n const credentials: Credentials = await this.api.getToken(authorizationCode, redirectUri)\n return await this._signInWithCredentials(credentials)\n } catch (error) {\n const authorizationError = new AuthorizationError(\n 'Failed to sign in with authorization code and redirect uri',\n { cause: error }\n )\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * Signs the user out.\n *\n * @returns {Promise<void>}\n */\n async signOut(remote?: boolean): Promise<void> {\n this.assertIsSetup()\n await this.secureStorage.deleteItem(STORE_CREDENTIALS_KEY)\n if (this.removeCredentialStorageUpdates) {\n this.removeCredentialStorageUpdates()\n this.removeCredentialStorageUpdates = undefined\n }\n\n const credentials = this.credentials\n\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: undefined,\n isFromOtherInstance: false,\n })\n\n try {\n if (credentials && remote !== false) {\n const { refresh_token, access_token } = credentials\n await this.api.logout(refresh_token, access_token)\n } else {\n this.logger?.log('No credentials were available. No action was executed on logout.')\n }\n } catch (error) {\n const authorizationError = new AuthorizationError('Failed to sign out the user', {\n cause: error,\n })\n this.emit(AuthenticatorEvents.ERROR, authorizationError)\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * On wake from sleep, we sign-in with the credentials to force the renewal of the credentials\n * if they expired during the sleep period.\n */\n public async sanityCheck(): Promise<void> {\n this.assertIsSetup()\n if (this._credentials) {\n try {\n await this._signInWithCredentials(this._credentials)\n } catch (error) {\n this.logger?.error('Failed to sign with credentials after sleep', error)\n }\n } else {\n this.logger?.info('No credentials available')\n }\n }\n\n /**\n * Indicates if there are valid credentials.\n *\n * Absent credentials or credentials which have expired are considered not valid.\n */\n public isTokenValid(): boolean {\n if (!this.credentials) {\n return false\n }\n return !this.credentials.isExpired()\n }\n\n public async signInWithCredentials(credentials: Credentials): Promise<Credentials> {\n this.assertIsSetup()\n return this._signInWithCredentials(credentials)\n }\n\n /**\n *\n * @param credentials\n * @returns {Promise<Credentials>}\n */\n private async _signInWithCredentials(\n credentials: Credentials,\n isFromOtherInstance: boolean = false\n ): Promise<Credentials> {\n this.logger?.log('signInWithCredentials')\n if (!credentials) {\n throw new Error('Invalid argument, credentials cannot be null or undefined.')\n }\n\n if (credentials?.isExpired()) {\n this._credentials = credentials\n await this.refreshTokenWithRetry()\n // _setupRefreshTokenRunner is setup in the refreshToken function\n } else {\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials,\n isFromOtherInstance,\n })\n this._setupRefreshTokenRunner()\n }\n\n if (!this._credentials) {\n throw new Error('Failed to authenticate')\n }\n\n return this._credentials\n }\n\n /**\n * Sets up a timeout which will automatically refresh the token.\n *\n * The timeout is calculated based on the value of the `expires_at` property of\n * the `Credentials`, the refresh is always scheduled at 80% of the token life-time.\n *\n * When there are multiple ConnectMe instances the refresh timeout can vary\n * up to 60 seconds.\n *\n * A token will never be refreshed before at least 60 seconds.\n *\n */\n private _setupRefreshTokenRunner(): void {\n clearTimeout(this.refreshTokenRunnerTimer)\n if (!this.credentials) {\n throw new Error('Unable to start refresh token runner without credentials')\n }\n const refreshIn: number = new Date(this.credentials.expires_at).getTime() - new Date().getTime()\n const refreshTimeout: number =\n this.refreshSeparationMilliseconds + Math.max(10_000, refreshIn - 10_000)\n this.logger?.info(\n `Setting timer to refresh token in ${Math.round(refreshTimeout / 1000)} seconds ` +\n `at ${new Date(new Date().getTime() + refreshTimeout).toTimeString()}`\n )\n this.refreshTokenRunnerTimer = setTimeout(async () => {\n try {\n await this.refreshToken()\n } catch (error) {\n const refreshTokenError = new RefreshTokenError(\n 'Refresh runner failed to refresh token with existing credentials',\n { cause: error }\n )\n this.emit(AuthenticatorEvents.ERROR, refreshTokenError)\n this.logger?.error(refreshTokenError)\n }\n }, refreshTimeout)\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method ensures that no parallel requests to refreshToken are done.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n async refreshToken(): Promise<Credentials> {\n this.assertIsSetup()\n if (this.refreshTokenPromise) {\n this.logger?.info('Refresh token already in progress: returning existing promise.')\n return await this.refreshTokenPromise\n }\n try {\n this.refreshTokenPromise = this._refreshToken()\n return await this.refreshTokenPromise\n } finally {\n this.refreshTokenPromise = undefined\n }\n }\n\n /**\n * Attempts the refresh the credentials.\n *\n * On failure it will throw an exception.\n * This method might end up signing the user out in case the refresh token are invalid.\n * It will not sign you out in case of network issues.\n *\n * @returns\n */\n async refreshTokenWithRetry(): Promise<Credentials> {\n this.assertIsSetup()\n const MAX_DEPTH = 7\n const MAX_TIMEOUT = 30 * 1000\n for (let depth = 0; depth < MAX_DEPTH; depth++) {\n try {\n return await this.refreshToken()\n } catch (err) {\n if (depth + 1 >= MAX_DEPTH) {\n throw err\n }\n if (err instanceof TokenNetworkError) {\n await this.wait(Math.min(2 ** depth * 1000, MAX_TIMEOUT))\n } else {\n throw err\n }\n }\n }\n return await this.refreshToken()\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method should only be called by `refreshToken`.\n *\n * Use `refreshToken` method if you need to refresh the token.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n private async _refreshToken(): Promise<Credentials> {\n this.logger?.info('Starting access token refresh')\n try {\n if (!this.credentials) {\n throw new Error('Failed to refresh token. No credentials available.')\n }\n const { refresh_token, access_token } = this.credentials\n const credentials = await this.api.refreshToken(refresh_token, access_token)\n this.logger?.info('Access token refreshed successfully')\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: credentials,\n isFromOtherInstance: false,\n })\n this._setupRefreshTokenRunner()\n return credentials\n } catch (error) {\n this.logger?.error('Failed to refresh token', error)\n if (error instanceof InvalidClientError) {\n if (typeof location !== 'undefined') {\n location.reload()\n } else {\n this.logger?.warn('Location reload not supported')\n throw error\n }\n }\n if (error instanceof RefreshTokenError) {\n if (this.delegateSignOutOnRefreshFailure) {\n await this.delegateSignOutOnRefreshFailure()\n } else {\n await this.signOut(false)\n }\n }\n throw error\n }\n }\n\n /**\n * Stores the credentials in secureStorage.\n *\n * @param {Credentials} credentials - The credentials to store in the secure storage.\n */\n private async storeCredentials(credentials: Credentials): Promise<void> {\n try {\n await this.secureStorage.setItem(STORE_CREDENTIALS_KEY, JSON.stringify(credentials))\n } catch (error: any) {\n this.logger?.error('Failed to store credentials in storage', error)\n }\n }\n\n private assertIsSetup() {\n if (!this.isSetup) {\n throw new Error('Authenticator needs to be setup before it can be used.')\n }\n }\n}\n\nexport default Authenticator\n","import { Credentials } from '@dstny/scp-credentials'\nimport axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\n\nexport abstract class AbstractAuthenticationApi {\n protected axiosInstance: AxiosInstance\n\n constructor(baseURL: string) {\n const config: AxiosRequestConfig = {\n baseURL,\n timeout: 50000,\n }\n this.axiosInstance = axios.create(config)\n }\n\n /**\n * Given a redirectUri it calculates the URL where the browser needs to be\n * redirected in other to authenticate\n *\n * @param {string} redirectUri\n * @returns {string} login url\n */\n abstract getLoginUrl(redirectUri: string): Promise<string>\n\n /**\n * Given the authorizationCode and the redirectUri this method will provide\n * credentials containing an access and refresh token\n *\n * @param {string} authorizationCode\n * @param {string} redirectUri\n * @returns {Promise<Credentials>}\n */\n abstract getToken(authorizationCode: string, redirectUri: string): Promise<Credentials>\n\n /**\n * Given a refresh token this method will provide a new set of credentials\n * containing an access token and a refresh token\n *\n * @param {string} refreshToken\n * @returns {Promise<Credentials>}\n */\n abstract refreshToken(refreshToken: string, accessToken: string): Promise<Credentials>\n\n /**\n * Given a access and refresh token, this method will logout the user from\n * the IAM\n *\n * @param {string} accessToken\n * @param {string} refreshToken\n * @returns {Promise<void>}\n */\n abstract logout(accessToken?: string, refreshToken?: string): Promise<void>\n}\n","/* eslint-disable no-async-promise-executor */\nimport { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport axios from 'axios'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetTokenResponse = {\n access_token: string\n refresh_token: string\n expires_in: number\n}\n\nexport class OAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly scope: string\n public readonly authorizationRoute: string\n\n private readonly baseURL: string\n\n constructor(baseURL: string, clientId: string, authorizationRoute: string, scope: string) {\n super(baseURL)\n this.baseURL = baseURL\n this.clientId = clientId\n this.authorizationRoute = authorizationRoute\n this.scope = scope\n }\n\n async getLoginUrl(redirectUri: string) {\n this.axiosInstance.getUri()\n return (\n `${this.baseURL}${this.authorizationRoute}` +\n `?client_id=${encodeURIComponent(this.clientId)}` +\n '&response_type=code' +\n `&redirect_uri=${encodeURIComponent(redirectUri)}` +\n (this.scope ? `&scope=${encodeURIComponent(this.scope)}` : '')\n )\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n code: authorizationCode,\n grant_type: 'authorization_code',\n redirect_uri: redirectUri,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async loginWithUsernamePassword(username: string, password: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'password',\n username,\n password,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const response = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n })\n )\n return new Credentials(\n response.data.access_token,\n response.data.refresh_token,\n response.data.expires_in\n )\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'unauthorized_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(_redirectUri?: string): Promise<void> {\n await this.axiosInstance.post('/logout', null, { withCredentials: true })\n }\n}\n","import { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport axios from 'axios'\nimport { decodeToken } from '../utils/jwt'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetLoginUrlResponse = {\n loginUrl: string\n}\n\ntype GetTokenResponse = {\n refreshToken: string\n accessToken: string\n message: string\n status: string\n}\n\nexport class SmgAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly realm: string\n\n constructor(baseURL: string, realm: string, clientId: string) {\n super(baseURL)\n this.clientId = clientId\n this.realm = realm\n }\n\n async getLoginUrl(redirectUri: string) {\n const { data } = await this.axiosInstance.get<GetLoginUrlResponse>(\n `/login/getloginurl/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`\n )\n\n const baseUrl = new URL(data.loginUrl)\n // The redirect_uri provided by the SMG is inacurate, this needs to be rewritten with the actual\n // redirect uri.\n baseUrl.searchParams.set('redirect_uri', redirectUri)\n // The authentication pathname of the SMG cannot be trusted to be configured correctly.\n // Duplicate '/' characters in the authentication URL causes the authentication\n // prompt to be displayed twice. Once when coven attempts to obtain a token, and\n // again when connect me attempts to obtain a token.\n // vv\n // example: https://keycloak.development.aws.d4sp.com//auth/realms/syslab1/protocol/openid-connect/auth\n baseUrl.pathname = baseUrl.pathname.replace(/\\/\\/+/g, '/')\n\n return baseUrl.toString()\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/getaccesstoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n code: authorizationCode,\n redirectUri: redirectUri,\n }\n )\n const { refreshToken, accessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(accessToken)\n const expires_in = exp - iat\n const expires_at = new Date()\n expires_at.setSeconds(expires_at.getSeconds() + expires_in)\n return new Credentials(accessToken, refreshToken, expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/refreshtoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n const { refreshToken: newRefreshToken, accessToken: newAccessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(newAccessToken)\n const expires_in = exp - iat\n return new Credentials(newAccessToken, newRefreshToken, expires_in)\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'invalid_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(refreshToken: string, accessToken: string): Promise<void> {\n await this.axiosInstance.post(\n `/login/logout/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n }\n}\n\nexport default SmgAuthApi\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,SAAS,oBAAI,QAAQ;AAC3B,IAAM,YAAY,oBAAI,QAAQ;AAC9B,IAAM,eAAe,oBAAI,QAAQ;;;ACAxC,IAAM,cAAc,OAAO,aAAa;AACxC,IAAM,kBAAkB,QAAQ,QAAQ;AAGxC,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,kBAAkB,OAAO,iBAAiB;AAEhD,IAAI,oBAAoB;AACxB,IAAI,uBAAuB;AAE3B,IAAM,iBAAiB,SAAO,OAAO,QAAQ,YAAY,OAAO,QAAQ,YAAY,OAAO,QAAQ;AAEnG,SAAS,gBAAgB,WAAW;AACnC,MAAI,CAAC,eAAe,SAAS,GAAG;AAC/B,UAAM,IAAI,UAAU,iDAAiD;AAAA,EACtE;AACD;AAEA,SAAS,eAAe,UAAU;AACjC,MAAI,OAAO,aAAa,YAAY;AACnC,UAAM,IAAI,UAAU,6BAA6B;AAAA,EAClD;AACD;AAEA,SAAS,aAAa,UAA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,KAAK,GAAG;AAC7B,YAAI,MAAM,YAAY,iBAAiB;AACrC,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AACA,cAAM,aAAa,MAAM,UAAU;AACnC,YAAI,eAAe,OAAO,MAAM,UAAU,MAAM,UAAU,kBAAkB;AAC1E,gBAAM,IAAI,2BAAmB;AAAA,QAC/B;AACA,YAAI,OAAO,eAAe,YAAY,cAAc,OAAO,aAAa,KAAK;AAC3E,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,cAAsB,aAAoC;AACrE,UAAM,KAAK,cAAc;AAAA,MACvB,uBAAuB,mBAAmB,KAAK,KAAK,CAAC,WAAW;AAAA,QAC9D,KAAK;AAAA,MACP,CAAC;AAAA,MACD;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AhBzGA,IAAO,cAAQ;","names":["eventName","AuthenticatorEvents","credentials","axios","import_axios","axios","import_axios","axios"]}
|
package/dist/index.mjs
CHANGED
|
@@ -804,6 +804,19 @@ var Authenticator = class extends Emittery {
|
|
|
804
804
|
unsubscribeListenerAdded;
|
|
805
805
|
unsubscribeUpdateState;
|
|
806
806
|
timers = /* @__PURE__ */ new Map();
|
|
807
|
+
/**
|
|
808
|
+
* In some cases we don't want to trigger the logout automatically
|
|
809
|
+
* on refresh failure.
|
|
810
|
+
*
|
|
811
|
+
* When defined, this method will be invoked after the refresh failure
|
|
812
|
+
* allowing you to define the behavior in that case.
|
|
813
|
+
*
|
|
814
|
+
* Example: You might not want sign out the user immediately
|
|
815
|
+
* when your application is handling calls and you have ongoing calls.
|
|
816
|
+
*
|
|
817
|
+
* @returns {Promise<void>}
|
|
818
|
+
*/
|
|
819
|
+
delegateSignOutOnRefreshFailure;
|
|
807
820
|
get jwtPayload() {
|
|
808
821
|
return this._jwtPayload;
|
|
809
822
|
}
|
|
@@ -1083,7 +1096,7 @@ var Authenticator = class extends Emittery {
|
|
|
1083
1096
|
throw new Error("Unable to start refresh token runner without credentials");
|
|
1084
1097
|
}
|
|
1085
1098
|
const refreshIn = new Date(this.credentials.expires_at).getTime() - (/* @__PURE__ */ new Date()).getTime();
|
|
1086
|
-
const refreshTimeout = this.refreshSeparationMilliseconds + Math.max(
|
|
1099
|
+
const refreshTimeout = this.refreshSeparationMilliseconds + Math.max(1e4, refreshIn - 1e4);
|
|
1087
1100
|
this.logger?.info(
|
|
1088
1101
|
`Setting timer to refresh token in ${Math.round(refreshTimeout / 1e3)} seconds at ${new Date((/* @__PURE__ */ new Date()).getTime() + refreshTimeout).toTimeString()}`
|
|
1089
1102
|
);
|
|
@@ -1184,7 +1197,11 @@ var Authenticator = class extends Emittery {
|
|
|
1184
1197
|
}
|
|
1185
1198
|
}
|
|
1186
1199
|
if (error instanceof RefreshTokenError_default) {
|
|
1187
|
-
|
|
1200
|
+
if (this.delegateSignOutOnRefreshFailure) {
|
|
1201
|
+
await this.delegateSignOutOnRefreshFailure();
|
|
1202
|
+
} else {
|
|
1203
|
+
await this.signOut(false);
|
|
1204
|
+
}
|
|
1188
1205
|
}
|
|
1189
1206
|
throw error;
|
|
1190
1207
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/maps.js","../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/index.js","../../credentials/src/utils.ts","../../credentials/src/Credentials.ts","../src/utils/jwt.ts","../src/events.ts","../src/types.ts","../src/utils/separation.ts","../src/errors/TokenNetworkError.ts","../src/errors/RefreshTokenError.ts","../src/errors/AuthorizationError.ts","../src/errors/InvalidClientError.ts","../src/Authenticator.ts","../src/api/AbstractAuthenticationApi.ts","../src/api/OAuthApi.ts","../src/api/SmgAuthApi.ts","../src/index.ts"],"sourcesContent":["export const anyMap = new WeakMap();\nexport const eventsMap = new WeakMap();\nexport const producersMap = new WeakMap();\n","import {anyMap, producersMap, eventsMap} from './maps.js';\n\nconst anyProducer = Symbol('anyProducer');\nconst resolvedPromise = Promise.resolve();\n\n// Define symbols for \"meta\" events.\nconst listenerAdded = Symbol('listenerAdded');\nconst listenerRemoved = Symbol('listenerRemoved');\n\nlet canEmitMetaEvents = false;\nlet isGlobalDebugEnabled = false;\n\nconst isEventKeyType = key => typeof key === 'string' || typeof key === 'symbol' || typeof key === 'number';\n\nfunction assertEventName(eventName) {\n\tif (!isEventKeyType(eventName)) {\n\t\tthrow new TypeError('`eventName` must be a string, symbol, or number');\n\t}\n}\n\nfunction assertListener(listener) {\n\tif (typeof listener !== 'function') {\n\t\tthrow new TypeError('listener must be a function');\n\t}\n}\n\nfunction getListeners(instance, eventName) {\n\tconst events = eventsMap.get(instance);\n\tif (!events.has(eventName)) {\n\t\treturn;\n\t}\n\n\treturn events.get(eventName);\n}\n\nfunction getEventProducers(instance, eventName) {\n\tconst key = isEventKeyType(eventName) ? eventName : anyProducer;\n\tconst producers = producersMap.get(instance);\n\tif (!producers.has(key)) {\n\t\treturn;\n\t}\n\n\treturn producers.get(key);\n}\n\nfunction enqueueProducers(instance, eventName, eventData) {\n\tconst producers = producersMap.get(instance);\n\tif (producers.has(eventName)) {\n\t\tfor (const producer of producers.get(eventName)) {\n\t\t\tproducer.enqueue(eventData);\n\t\t}\n\t}\n\n\tif (producers.has(anyProducer)) {\n\t\tconst item = Promise.all([eventName, eventData]);\n\t\tfor (const producer of producers.get(anyProducer)) {\n\t\t\tproducer.enqueue(item);\n\t\t}\n\t}\n}\n\nfunction iterator(instance, eventNames) {\n\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\tlet isFinished = false;\n\tlet flush = () => {};\n\tlet queue = [];\n\n\tconst producer = {\n\t\tenqueue(item) {\n\t\t\tqueue.push(item);\n\t\t\tflush();\n\t\t},\n\t\tfinish() {\n\t\t\tisFinished = true;\n\t\t\tflush();\n\t\t},\n\t};\n\n\tfor (const eventName of eventNames) {\n\t\tlet set = getEventProducers(instance, eventName);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tconst producers = producersMap.get(instance);\n\t\t\tproducers.set(eventName, set);\n\t\t}\n\n\t\tset.add(producer);\n\t}\n\n\treturn {\n\t\tasync next() {\n\t\t\tif (!queue) {\n\t\t\t\treturn {done: true};\n\t\t\t}\n\n\t\t\tif (queue.length === 0) {\n\t\t\t\tif (isFinished) {\n\t\t\t\t\tqueue = undefined;\n\t\t\t\t\treturn this.next();\n\t\t\t\t}\n\n\t\t\t\tawait new Promise(resolve => {\n\t\t\t\t\tflush = resolve;\n\t\t\t\t});\n\n\t\t\t\treturn this.next();\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdone: false,\n\t\t\t\tvalue: await queue.shift(),\n\t\t\t};\n\t\t},\n\n\t\tasync return(value) {\n\t\t\tqueue = undefined;\n\n\t\t\tfor (const eventName of eventNames) {\n\t\t\t\tconst set = getEventProducers(instance, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.delete(producer);\n\t\t\t\t\tif (set.size === 0) {\n\t\t\t\t\t\tconst producers = producersMap.get(instance);\n\t\t\t\t\t\tproducers.delete(eventName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tflush();\n\n\t\t\treturn arguments.length > 0\n\t\t\t\t? {done: true, value: await value}\n\t\t\t\t: {done: true};\n\t\t},\n\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t};\n}\n\nfunction defaultMethodNamesOrAssert(methodNames) {\n\tif (methodNames === undefined) {\n\t\treturn allEmitteryMethods;\n\t}\n\n\tif (!Array.isArray(methodNames)) {\n\t\tthrow new TypeError('`methodNames` must be an array of strings');\n\t}\n\n\tfor (const methodName of methodNames) {\n\t\tif (!allEmitteryMethods.includes(methodName)) {\n\t\t\tif (typeof methodName !== 'string') {\n\t\t\t\tthrow new TypeError('`methodNames` element must be a string');\n\t\t\t}\n\n\t\t\tthrow new Error(`${methodName} is not Emittery method`);\n\t\t}\n\t}\n\n\treturn methodNames;\n}\n\nconst isMetaEvent = eventName => eventName === listenerAdded || eventName === listenerRemoved;\n\nfunction emitMetaEvent(emitter, eventName, eventData) {\n\tif (!isMetaEvent(eventName)) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tcanEmitMetaEvents = true;\n\t\temitter.emit(eventName, eventData);\n\t} finally {\n\t\tcanEmitMetaEvents = false;\n\t}\n}\n\nexport default class Emittery {\n\tstatic mixin(emitteryPropertyName, methodNames) {\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\t\treturn target => {\n\t\t\tif (typeof target !== 'function') {\n\t\t\t\tthrow new TypeError('`target` must be function');\n\t\t\t}\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tif (target.prototype[methodName] !== undefined) {\n\t\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction getEmitteryProperty() {\n\t\t\t\tObject.defineProperty(this, emitteryPropertyName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: new Emittery(),\n\t\t\t\t});\n\t\t\t\treturn this[emitteryPropertyName];\n\t\t\t}\n\n\t\t\tObject.defineProperty(target.prototype, emitteryPropertyName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tget: getEmitteryProperty,\n\t\t\t});\n\n\t\t\tconst emitteryMethodCaller = methodName => function (...args) {\n\t\t\t\treturn this[emitteryPropertyName][methodName](...args);\n\t\t\t};\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tObject.defineProperty(target.prototype, methodName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: emitteryMethodCaller(methodName),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn target;\n\t\t};\n\t}\n\n\tstatic get isDebugEnabled() {\n\t\t// In a browser environment, `globalThis.process` can potentially reference a DOM Element with a `#process` ID,\n\t\t// so instead of just type checking `globalThis.process`, we need to make sure that `globalThis.process.env` exists.\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tif (typeof globalThis.process?.env !== 'object') {\n\t\t\treturn isGlobalDebugEnabled;\n\t\t}\n\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tconst {env} = globalThis.process ?? {env: {}};\n\t\treturn env.DEBUG === 'emittery' || env.DEBUG === '*' || isGlobalDebugEnabled;\n\t}\n\n\tstatic set isDebugEnabled(newValue) {\n\t\tisGlobalDebugEnabled = newValue;\n\t}\n\n\tconstructor(options = {}) {\n\t\tanyMap.set(this, new Set());\n\t\teventsMap.set(this, new Map());\n\t\tproducersMap.set(this, new Map());\n\n\t\tproducersMap.get(this).set(anyProducer, new Set());\n\n\t\tthis.debug = options.debug ?? {};\n\n\t\tif (this.debug.enabled === undefined) {\n\t\t\tthis.debug.enabled = false;\n\t\t}\n\n\t\tif (!this.debug.logger) {\n\t\t\tthis.debug.logger = (type, debugName, eventName, eventData) => {\n\t\t\t\ttry {\n\t\t\t\t\t// TODO: Use https://github.com/sindresorhus/safe-stringify when the package is more mature. Just copy-paste the code.\n\t\t\t\t\teventData = JSON.stringify(eventData);\n\t\t\t\t} catch {\n\t\t\t\t\teventData = `Object with the following keys failed to stringify: ${Object.keys(eventData).join(',')}`;\n\t\t\t\t}\n\n\t\t\t\tif (typeof eventName === 'symbol' || typeof eventName === 'number') {\n\t\t\t\t\teventName = eventName.toString();\n\t\t\t\t}\n\n\t\t\t\tconst currentTime = new Date();\n\t\t\t\tconst logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;\n\t\t\t\tconsole.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\\n\\tdata: ${eventData}`);\n\t\t\t};\n\t\t}\n\t}\n\n\tlogIfDebugEnabled(type, eventName, eventData) {\n\t\tif (Emittery.isDebugEnabled || this.debug.enabled) {\n\t\t\tthis.debug.logger(type, this.debug.name, eventName, eventData);\n\t\t}\n\t}\n\n\ton(eventNames, listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tlet set = getListeners(this, eventName);\n\t\t\tif (!set) {\n\t\t\t\tset = new Set();\n\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\tevents.set(eventName, set);\n\t\t\t}\n\n\t\t\tset.add(listener);\n\n\t\t\tthis.logIfDebugEnabled('subscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerAdded, {eventName, listener});\n\t\t\t}\n\t\t}\n\n\t\tconst off = () => {\n\t\t\tthis.off(eventNames, listener);\n\t\t\tsignal?.removeEventListener('abort', off);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', off, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toff();\n\t\t}\n\n\t\treturn off;\n\t}\n\n\toff(eventNames, listener) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tconst set = getListeners(this, eventName);\n\t\t\tif (set) {\n\t\t\t\tset.delete(listener);\n\t\t\t\tif (set.size === 0) {\n\t\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\t\tevents.delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.logIfDebugEnabled('unsubscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerRemoved, {eventName, listener});\n\t\t\t}\n\t\t}\n\t}\n\n\tonce(eventNames) {\n\t\tlet off_;\n\n\t\tconst promise = new Promise(resolve => {\n\t\t\toff_ = this.on(eventNames, data => {\n\t\t\t\toff_();\n\t\t\t\tresolve(data);\n\t\t\t});\n\t\t});\n\n\t\tpromise.off = off_;\n\t\treturn promise;\n\t}\n\n\tevents(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t}\n\n\t\treturn iterator(this, eventNames);\n\t}\n\n\tasync emit(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emit', eventName, eventData);\n\n\t\tenqueueProducers(this, eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\tawait Promise.all([\n\t\t\t...staticListeners.map(async listener => {\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\treturn listener(eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t\t...staticAnyListeners.map(async listener => {\n\t\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\t\treturn listener(eventName, eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t]);\n\t}\n\n\tasync emitSerial(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emitSerial', eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\t/* eslint-disable no-await-in-loop */\n\t\tfor (const listener of staticListeners) {\n\t\t\tif (listeners.has(listener)) {\n\t\t\t\tawait listener(eventData);\n\t\t\t}\n\t\t}\n\n\t\tfor (const listener of staticAnyListeners) {\n\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\tawait listener(eventName, eventData);\n\t\t\t}\n\t\t}\n\t\t/* eslint-enable no-await-in-loop */\n\t}\n\n\tonAny(listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('subscribeAny', undefined, undefined);\n\n\t\tanyMap.get(this).add(listener);\n\t\temitMetaEvent(this, listenerAdded, {listener});\n\n\t\tconst offAny = () => {\n\t\t\tthis.offAny(listener);\n\t\t\tsignal?.removeEventListener('abort', offAny);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', offAny, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toffAny();\n\t\t}\n\n\t\treturn offAny;\n\t}\n\n\tanyEvent() {\n\t\treturn iterator(this);\n\t}\n\n\toffAny(listener) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('unsubscribeAny', undefined, undefined);\n\n\t\temitMetaEvent(this, listenerRemoved, {listener});\n\t\tanyMap.get(this).delete(listener);\n\t}\n\n\tclearListeners(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tthis.logIfDebugEnabled('clear', eventName, undefined);\n\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tconst set = getListeners(this, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.clear();\n\t\t\t\t}\n\n\t\t\t\tconst producers = getEventProducers(this, eventName);\n\t\t\t\tif (producers) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tanyMap.get(this).clear();\n\n\t\t\t\tfor (const [eventName, listeners] of eventsMap.get(this).entries()) {\n\t\t\t\t\tlisteners.clear();\n\t\t\t\t\teventsMap.get(this).delete(eventName);\n\t\t\t\t}\n\n\t\t\t\tfor (const [eventName, producers] of producersMap.get(this).entries()) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t\tproducersMap.get(this).delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlistenerCount(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tlet count = 0;\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tcount += anyMap.get(this).size\n\t\t\t\t\t+ (getListeners(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this)?.size ?? 0);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (eventName !== undefined) {\n\t\t\t\tassertEventName(eventName);\n\t\t\t}\n\n\t\t\tcount += anyMap.get(this).size;\n\n\t\t\tfor (const value of eventsMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\n\t\t\tfor (const value of producersMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tbindMethods(target, methodNames) {\n\t\tif (typeof target !== 'object' || target === null) {\n\t\t\tthrow new TypeError('`target` must be an object');\n\t\t}\n\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\n\t\tfor (const methodName of methodNames) {\n\t\t\tif (target[methodName] !== undefined) {\n\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t}\n\n\t\t\tObject.defineProperty(target, methodName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: this[methodName].bind(this),\n\t\t\t});\n\t\t}\n\t}\n}\n\nconst allEmitteryMethods = Object.getOwnPropertyNames(Emittery.prototype).filter(v => v !== 'constructor');\n\nObject.defineProperty(Emittery, 'listenerAdded', {\n\tvalue: listenerAdded,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\nObject.defineProperty(Emittery, 'listenerRemoved', {\n\tvalue: listenerRemoved,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\n","// declare const Buffer\n\nfunction byteToPercent(b: string) {\n return `%${`00${b.charCodeAt(0).toString(16)}`.slice(-2)}`\n}\n\nexport function base64decode(str: string): string | undefined {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\n\nexport async function sha1(str: string) {\n if (typeof crypto === 'object') {\n const hash = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(str))\n return Array.from(new Uint8Array(hash))\n .map((v) => v.toString(16).padStart(2, '0'))\n .join('')\n } else {\n return binb2hex(core_sha1(str2binb(str), str.length * chrsz))\n }\n}\n\nconst hexcase = 0 /* hex output format. 0 - lowercase; 1 - uppercase */\nconst b64pad = '' /* base-64 pad character. \"=\" for strict RFC compliance */\nconst chrsz = 8 /* bits per input character. 8 - ASCII; 16 - Unicode */\n\n/*\n * Calculate the SHA-1 of an array of big-endian words, and a bit length\n */\nfunction core_sha1(x: Array<number>, len: number) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - (len % 32))\n x[(((len + 64) >> 9) << 4) + 15] = len\n\n var w = Array(80)\n var a = 1732584193\n var b = -271733879\n var c = -1732584194\n var d = 271733878\n var e = -1009589776\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a\n var oldb = b\n var oldc = c\n var oldd = d\n var olde = e\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j]\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)\n var t = safe_add(\n safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n safe_add(safe_add(e, w[j]), sha1_kt(j))\n )\n e = d\n d = c\n c = rol(b, 30)\n b = a\n a = t\n }\n\n a = safe_add(a, olda)\n b = safe_add(b, oldb)\n c = safe_add(c, oldc)\n d = safe_add(d, oldd)\n e = safe_add(e, olde)\n }\n return Array(a, b, c, d, e)\n}\n\n/*\n * Perform the appropriate triplet combination function for the current\n * iteration\n */\nfunction sha1_ft(t: number, b: number, c: number, d: number) {\n if (t < 20) return (b & c) | (~b & d)\n if (t < 40) return b ^ c ^ d\n if (t < 60) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\n/*\n * Determine the appropriate additive constant for the current iteration\n */\nfunction sha1_kt(t: number) {\n return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514\n}\n\n/*\n * Calculate the HMAC-SHA1 of a key and some data\n */\nfunction core_hmac_sha1(key: string, data: string) {\n let bkey = str2binb(key)\n if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz)\n\n let ipad = Array(16),\n opad = Array(16)\n for (let i = 0; i < 16; i++) {\n ipad[i] = bkey[i] ^ 0x36363636\n opad[i] = bkey[i] ^ 0x5c5c5c5c\n }\n\n let hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz)\n return core_sha1(opad.concat(hash), 512 + 160)\n}\n\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\nfunction safe_add(x: number, y: number) {\n const lsw = (x & 0xffff) + (y & 0xffff)\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16)\n return (msw << 16) | (lsw & 0xffff)\n}\n\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\nfunction rol(num: number, cnt: number) {\n return (num << cnt) | (num >>> (32 - cnt))\n}\n\n/*\n * Convert an 8-bit or 16-bit string to an array of big-endian words\n * In 8-bit function, characters >255 have their hi-byte silently ignored.\n */\nfunction str2binb(str: string): Array<number> {\n const bin: Array<number> = []\n const mask = (1 << chrsz) - 1\n for (let i = 0; i < str.length * chrsz; i += chrsz)\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - (i % 32))\n return bin\n}\n\n/*\n * Convert an array of big-endian words to a string\n */\nfunction binb2str(bin: Array<number>): string {\n let str = ''\n let mask = (1 << chrsz) - 1\n for (let i = 0; i < bin.length * 32; i += chrsz)\n str += String.fromCharCode((bin[i >> 5] >>> (32 - chrsz - (i % 32))) & mask)\n return str\n}\n\n/*\n * Convert an array of big-endian words to a hex string.\n */\nfunction binb2hex(binarray: Array<number>) {\n let hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i++) {\n str +=\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) +\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf)\n }\n return str\n}\n\n/*\n * Convert an array of big-endian words to a base-64 string\n */\nfunction binb2b64(binarray: Array<number>) {\n let tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i += 3) {\n let triplet =\n (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) << 16) |\n (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) & 0xff) << 8) |\n ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) & 0xff)\n for (let j = 0; j < 4; j++) {\n if (i * 8 + j * 6 > binarray.length * 32) str += b64pad\n else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)\n }\n }\n return str\n}\n","import { base64decode, sha1 } from './utils'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\n\nexport const STORE_CREDENTILAS_KEY = 'sdk-auth-credential'\n\ntype CredentialsCallback = (callback: Credentials) => void\ntype JSONCredentials = {\n access_token: string\n refresh_token: string\n expires_in: number\n expires_at: Date\n token_type: 'Bearer' | string\n}\n\nexport default class Credentials {\n static async fromStorage(storage: SecureStorageHandler): Promise<Credentials> {\n const str: string | null = await storage.getItem(STORE_CREDENTILAS_KEY)\n if (str == null || str == undefined) {\n throw new Error('No credentials found in storage.')\n }\n return Credentials.fromJSON(str)\n }\n\n static async toStorage(storage: SecureStorageHandler, credentials: Credentials): Promise<void> {\n await storage.setItem(STORE_CREDENTILAS_KEY, JSON.stringify(credentials))\n }\n\n static async clearFromStorage(storage: SecureStorageHandler): Promise<void> {\n await storage.deleteItem(STORE_CREDENTILAS_KEY)\n }\n\n static fromJSON(str: string): Credentials {\n const { access_token, refresh_token, expires_in } = JSON.parse(str)\n return new Credentials(access_token, refresh_token, expires_in)\n }\n\n static onStorageUpdate(storage: SecureStorageHandler, callback: CredentialsCallback): () => void {\n return storage.on(STORE_CREDENTILAS_KEY, (credentials: string | null) => {\n if (typeof credentials === 'string') {\n callback(Credentials.fromJSON(credentials))\n }\n })\n }\n\n static equals(a?: Credentials, b?: Credentials) {\n if (!a && !b) {\n return true\n }\n if ((a && !b) || (b && !a)) {\n return false\n }\n return (\n a?.access_token === b?.access_token &&\n a?._refresh_token === b?.refresh_token &&\n a?.expires_in === b?.expires_in\n )\n }\n\n /**\n * Used to access resources.\n */\n private _access_token: string\n /**\n * Used to obtain a new access token.\n */\n private _refresh_token: string\n /**\n * Number of seconds until the access token expires.\n * This value is calculated at the moment the access token is generated.\n */\n private _expires_in: number\n\n constructor(access_token: string, refresh_token: string, expires_in: number) {\n this._access_token = access_token\n this._refresh_token = refresh_token\n this._expires_in = expires_in\n }\n\n /**\n * Lists the claims present in the access token.\n */\n get claims() {\n const fallback = {}\n if (typeof this._access_token != 'string') {\n return fallback\n }\n const [, b64payload] = this._access_token.split('.')\n const payload = base64decode(b64payload)\n if (!payload) {\n return fallback\n }\n try {\n return JSON.parse(payload)\n } catch (err) {\n return {}\n }\n }\n\n get access_token(): string {\n return this._access_token\n }\n\n get refresh_token(): string {\n return this._refresh_token\n }\n\n get expires_in(): number {\n return this._expires_in\n }\n\n get token_type(): string {\n return 'Bearer'\n }\n\n get expires_at(): Date {\n if (typeof this.claims?.exp === 'number') {\n return new Date(this.claims?.exp * 1000)\n }\n const expiryDate = new Date()\n expiryDate.setSeconds(expiryDate.getSeconds() + this._expires_in)\n return expiryDate\n }\n\n isExpired(): boolean {\n return this.expires_at && new Date().getTime() > new Date(this.expires_at).getTime()\n }\n\n async getUepId(): Promise<string> {\n const { sub, uep_id: rawUepId } = this.claims \n if (!sub) {\n throw new Error(\"Missing 'sub' claim.\")\n }\n\n if (rawUepId) {\n return rawUepId\n }\n \n return await sha1(sub)\n }\n\n toJSON(): JSONCredentials {\n return {\n access_token: this._access_token,\n refresh_token: this._refresh_token,\n expires_in: this._expires_in,\n expires_at: this.expires_at,\n token_type: this.token_type,\n }\n }\n}\n","export interface JwtPayload {\n [key: string]: any\n iss?: string | undefined\n sub?: string | undefined\n aud?: string | string[] | undefined\n exp?: number | undefined\n nbf?: number | undefined\n iat?: number | undefined\n jti?: string | undefined\n}\n\nexport function decodeToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('No token provided')\n }\n const parts = token.split('.')\n\n if (parts.length !== 3) {\n throw new Error('JWT must have 3 parts')\n }\n\n const decoded = urlBase64Decode(parts[1])\n if (!decoded) {\n throw new Error('Cannot decode the token')\n }\n\n return JSON.parse(decoded)\n}\n\nfunction urlBase64Decode(str: string): string {\n let output = str.replace(/-/g, '+').replace(/_/g, '/')\n switch (output.length % 4) {\n case 0: {\n break\n }\n case 2: {\n output += '=='\n break\n }\n case 3: {\n output += '='\n break\n }\n default: {\n // TODO\n throw new Error('Illegal base64url string!')\n }\n }\n return b64DecodeUnicode(output)\n}\n\nfunction b64DecodeUnicode(str: any): any {\n return decodeURIComponent(\n Array.prototype.map\n .call(b64decode(str), (c: any) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join('')\n )\n}\n\nexport function b64decode(str: string): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\nexport function b64encode(input: string, encode = true) {\n let output = ''\n let chr1, chr2, chr3, enc1, enc2, enc3, enc4\n let i = 0\n const _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n if (encode) {\n input = _utf8_encode(input)\n }\n\n while (i < input.length) {\n chr1 = input.charCodeAt(i++)\n chr2 = input.charCodeAt(i++)\n chr3 = input.charCodeAt(i++)\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64\n } else if (isNaN(chr3)) {\n enc4 = 64\n }\n\n output =\n output +\n _keyStr.charAt(enc1) +\n _keyStr.charAt(enc2) +\n _keyStr.charAt(enc3) +\n _keyStr.charAt(enc4)\n }\n return output\n}\n\nexport function _utf8_encode(string: string) {\n string = string.replace(/\\r\\n/g, '\\n')\n let utftext = ''\n\n for (let n = 0; n < string.length; n++) {\n const c = string.charCodeAt(n)\n\n if (c < 128) {\n utftext += String.fromCharCode(c)\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n } else {\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n }\n return utftext\n}\n","export enum AuthenticatorEvents {\n CREDENTIALS = 'CREDENTIALS',\n ACCESS_TOKEN = 'ACCESS_TOKEN',\n JWT_PAYLOAD = 'JWT_PAYLOAD',\n STATE_CHANGE = 'STATE_CHANGE',\n ERROR = 'ERROR',\n}\n","import { Credentials } from '@dstny/scp-credentials'\n\nexport const STORE_CREDENTIALS_KEY = 'sdk-auth-credential'\nexport const STORE_REFRESH_SEPARATION_SECONDS = 'sdk-separation-seconds'\n\nexport type AuthenticatorState = boolean\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace'\nexport interface Logger {\n log(...arg: any[]): void\n error(...arg: any[]): void\n warn(...arg: any[]): void\n info(...arg: any[]): void\n debug(...arg: any[]): void\n trace(...arg: any[]): void\n\n setLevel(level: LogLevel, persist?: boolean): void\n resetLevel(): void\n}\n\nexport interface AuthenticatorOptions {\n credentials?: Credentials\n logger?: Logger\n}\n","import { SecureStorageHandler } from '@dstny/scp-storage'\nimport { STORE_REFRESH_SEPARATION_SECONDS } from '../types'\n\nexport const getRefreshSeparationMilliseconds = async (\n storage: SecureStorageHandler\n): Promise<number> => {\n const next = parseInt((await storage.getItem(STORE_REFRESH_SEPARATION_SECONDS)) || '0') || 0\n await storage.setItem(STORE_REFRESH_SEPARATION_SECONDS, '' + ((next + 5) % 60))\n return next * 1000\n}\n\n\n","class TokenNetworkError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Network unavailable to refresh the network', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'NetworkError'\n }\n}\n\nexport default TokenNetworkError\n","/**\n * This kind of exceptions are using for reporting error cases for refresh token action such as update, request and ect.\n */\nclass RefreshTokenError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your token or session is expired.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'RefreshTokenError'\n }\n}\n\nexport default RefreshTokenError\n","/**\n * Use it for authorization specific errors\n * Depends on reason of exception use proper type\n */\nclass AuthorizationError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Authorization failed', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'AuthorizationError'\n }\n}\n\nexport default AuthorizationError\n","/**\n * This kind of is launched when the configured client is invalid\n */\nclass InvalidClientError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your client is invalid.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'InvalidClientError'\n }\n}\n\nexport default InvalidClientError\n","import Emittery from 'emittery'\n\nimport { Credentials } from '@dstny/scp-credentials'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\nimport { AbstractAuthenticationApi } from './api/AbstractAuthenticationApi'\nimport { decodeToken, JwtPayload } from './utils/jwt'\nimport { AuthenticatorEvents } from './events'\nimport { AuthenticatorOptions, AuthenticatorState, Logger, STORE_CREDENTIALS_KEY } from './types'\nimport { getRefreshSeparationMilliseconds } from './utils/separation'\nimport TokenNetworkError from './errors/TokenNetworkError'\nimport RefreshTokenError from './errors/RefreshTokenError'\nimport AuthorizationError from './errors/AuthorizationError'\nimport InvalidClientError from './errors/InvalidClientError'\n\nconst INTERNAL_CREDENTIALS = 'INTERNAL_CREDENTIALS'\n\nclass Authenticator extends Emittery {\n private readonly api: AbstractAuthenticationApi\n private readonly secureStorage: SecureStorageHandler\n private readonly logger?: Logger\n private readonly initialCredentials?: Credentials\n\n private _state?: boolean = false\n private _credentials?: Credentials\n private _jwtPayload?: JwtPayload\n\n private isSetup: boolean = false\n private refreshTokenRunnerTimer?: any\n private refreshSeparationMilliseconds: number = 0\n private refreshTokenPromise?: Promise<Credentials>\n private removeCredentialStorageUpdates?: () => void\n private unsubscribeListenerAdded?: () => void\n private unsubscribeUpdateState?: () => void\n private timers: Map<ReturnType<typeof setTimeout>, (error: any) => void> = new Map()\n\n public get jwtPayload(): JwtPayload | undefined {\n return this._jwtPayload\n }\n\n public get credentials(): Credentials | undefined {\n return this._credentials\n }\n\n public get state(): AuthenticatorState {\n return this._state ?? false\n }\n\n /**\n *\n * @param {ConnectEmitter} globalEmitter\n * @param {API} api\n * @param {string} oauthUrl\n */\n constructor(\n api: AbstractAuthenticationApi,\n secureStorage: SecureStorageHandler,\n options?: AuthenticatorOptions\n ) {\n super()\n this.api = api\n this.secureStorage = secureStorage\n this.logger = options?.logger\n this.initialCredentials = options?.credentials\n }\n\n /**\n * Starts the authenticator\n */\n async setup(): Promise<void> {\n let credentials\n\n if (this.initialCredentials) {\n credentials = this.initialCredentials\n } else {\n const localStorageCredentials = await this.secureStorage.getItem(STORE_CREDENTIALS_KEY)\n if (typeof localStorageCredentials === 'string') {\n credentials = Credentials.fromJSON(localStorageCredentials)\n }\n }\n\n // When loading a second instance of ConnectMe on the same browser,\n // the second instance cannot use the refresh token at the same time\n // as the first instance. In that case they will try to use the same\n // refresh_token and the instance that comes last will be returned an error.\n\n // Two mechanisms are put in place to mitigate this:\n // - The first instance to obtain the refresh token will save it to the SecureStorageHandler.\n // Other instances will be notified of the new token. When an instance recevices\n // credentials from another instance they will reset their _setupRefreshTokenRunner,\n // effectively becoming slave from the first instance.\n // - An instance separation delay is added, which separates the refresh of each instance\n // by 5 seconds. Up to 12 instance supported. 60 secs / 5 seconds delay\n this.removeCredentialStorageUpdates = Credentials.onStorageUpdate(\n this.secureStorage,\n (credentials: Credentials) => {\n this._signInWithCredentials(credentials, true)\n }\n )\n // _refreshSeparationMilliseconds is used in _setupRefreshTokenRunner\n this.refreshSeparationMilliseconds = await getRefreshSeparationMilliseconds(this.secureStorage)\n\n // Emit current credentials/access_token/jwt if they are defined when someone registers a listener\n this.unsubscribeListenerAdded = this.on(Emittery.listenerAdded, ({ listener, eventName }) => {\n if (eventName === AuthenticatorEvents.CREDENTIALS && this._credentials) {\n listener(this._credentials)\n } else if (eventName === AuthenticatorEvents.ACCESS_TOKEN && this._credentials) {\n listener(decodeToken(this._credentials.access_token))\n } else if (eventName === AuthenticatorEvents.JWT_PAYLOAD && this._jwtPayload) {\n listener(this._jwtPayload)\n }\n })\n\n // Update jwt payload and state, and re-broadcast credentials update\n this.unsubscribeUpdateState = this.on(\n INTERNAL_CREDENTIALS,\n async ({ credentials, isFromOtherInstance }) => {\n if (Credentials.equals(this._credentials, credentials)) {\n return\n }\n this._credentials = credentials\n this.emit(AuthenticatorEvents.CREDENTIALS, credentials)\n if (credentials) {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, credentials.access_token)\n this._jwtPayload = decodeToken(credentials.access_token)\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, this._jwtPayload)\n this._state = true\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n if (isFromOtherInstance === false) {\n this.storeCredentials(credentials)\n }\n } else {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, undefined)\n this._jwtPayload = undefined\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, undefined)\n this._state = false\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n // Credentials are not removed from the store here as the user\n // might only be stopping the authenticator, not necessarily signin out.\n }\n }\n )\n\n this.isSetup = true\n\n if (credentials) {\n this.logger?.log('Has credentials:', credentials)\n await this._signInWithCredentials(credentials)\n }\n }\n\n /**\n * Destroys the ConnectAuth module.\n * This method is called when the user signs-out.\n *\n * @returns {Promise}\n */\n async destroy(): Promise<void> {\n this.refreshTokenRunnerTimer && clearTimeout(this.refreshTokenRunnerTimer)\n\n await this.emit(INTERNAL_CREDENTIALS, { credentials: undefined, isFromOtherInstance: false })\n\n if (this.unsubscribeListenerAdded) {\n this.unsubscribeListenerAdded()\n }\n if (this.unsubscribeUpdateState) {\n this.unsubscribeUpdateState()\n }\n\n this.isSetup = false\n\n for (const [timer, reject] of this.timers.entries()) {\n clearTimeout(timer)\n reject(new Error('Authenticator is being destroyed. Wait functions are rejected.'))\n }\n this.timers.clear()\n }\n\n /**\n * Waits for the given number of milliseconds before resolving the promise.\n *\n * @param waitMilliseconds\n * @returns {Promise<void>}\n */\n private wait(waitMilliseconds: number): Promise<void> {\n try {\n this.assertIsSetup()\n } catch (err) {\n return Promise.reject(err)\n }\n return new Promise((resolve, reject) => {\n const fn = () => {\n this.timers.delete(timer)\n resolve()\n }\n const timer = setTimeout(fn, waitMilliseconds)\n this.timers.set(timer, reject)\n })\n }\n\n /**\n * Generates the login uri for OAuth authentication.\n * Supports escaux-oauth and SMG providers.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<string>} The authorization URI.\n *\n * The browser should be redirected to this URI.\n */\n async getLoginUrl(redirectUri: string): Promise<string> {\n this.assertIsSetup()\n const loginUrl: string = await this.api.getLoginUrl(redirectUri)\n return loginUrl\n }\n\n /**\n * Sign-in the user. Using the authorization code, an access and refresh token\n * is retrieved from the OAuth server. These are stored in an Credentials object.\n *\n * @param {string} authorizationCode - The autorization code recieved from OAuth\n * once the user has authorized the request.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<Credentials>} The user Crendetials\n */\n async signIn(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n this.assertIsSetup()\n try {\n const credentials: Credentials = await this.api.getToken(authorizationCode, redirectUri)\n return await this._signInWithCredentials(credentials)\n } catch (error) {\n const authorizationError = new AuthorizationError(\n 'Failed to sign in with authorization code and redirect uri',\n { cause: error }\n )\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * Signs the user out.\n *\n * @returns {Promise<void>}\n */\n async signOut(remote?: boolean): Promise<void> {\n this.assertIsSetup()\n await this.secureStorage.deleteItem(STORE_CREDENTIALS_KEY)\n if (this.removeCredentialStorageUpdates) {\n this.removeCredentialStorageUpdates()\n this.removeCredentialStorageUpdates = undefined\n }\n\n const credentials = this.credentials\n\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: undefined,\n isFromOtherInstance: false,\n })\n\n try {\n if (credentials && remote !== false) {\n const { refresh_token, access_token } = credentials\n await this.api.logout(refresh_token, access_token)\n } else {\n this.logger?.log('No credentials were available. No action was executed on logout.')\n }\n } catch (error) {\n const authorizationError = new AuthorizationError('Failed to sign out the user', {\n cause: error,\n })\n this.emit(AuthenticatorEvents.ERROR, authorizationError)\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * On wake from sleep, we sign-in with the credentials to force the renewal of the credentials\n * if they expired during the sleep period.\n */\n public async sanityCheck(): Promise<void> {\n this.assertIsSetup()\n if (this._credentials) {\n try {\n await this._signInWithCredentials(this._credentials)\n } catch (error) {\n this.logger?.error('Failed to sign with credentials after sleep', error)\n }\n } else {\n this.logger?.info('No credentials available')\n }\n }\n\n /**\n * Indicates if there are valid credentials.\n *\n * Absent credentials or credentials which have expired are considered not valid.\n */\n public isTokenValid(): boolean {\n if (!this.credentials) {\n return false\n }\n return !this.credentials.isExpired()\n }\n\n public async signInWithCredentials(credentials: Credentials): Promise<Credentials> {\n this.assertIsSetup()\n return this._signInWithCredentials(credentials)\n }\n\n /**\n *\n * @param credentials\n * @returns {Promise<Credentials>}\n */\n private async _signInWithCredentials(\n credentials: Credentials,\n isFromOtherInstance: boolean = false\n ): Promise<Credentials> {\n this.logger?.log('signInWithCredentials')\n if (!credentials) {\n throw new Error('Invalid argument, credentials cannot be null or undefined.')\n }\n\n if (credentials?.isExpired()) {\n this._credentials = credentials\n await this.refreshTokenWithRetry()\n // _setupRefreshTokenRunner is setup in the refreshToken function\n } else {\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials,\n isFromOtherInstance,\n })\n this._setupRefreshTokenRunner()\n }\n\n if (!this._credentials) {\n throw new Error('Failed to authenticate')\n }\n\n return this._credentials\n }\n\n /**\n * Sets up a timeout which will automatically refresh the token.\n *\n * The timeout is calculated based on the value of the `expires_at` property of\n * the `Credentials`, the refresh is always scheduled at 80% of the token life-time.\n *\n * When there are multiple ConnectMe instances the refresh timeout can vary\n * up to 60 seconds.\n *\n * A token will never be refreshed before at least 60 seconds.\n *\n */\n private _setupRefreshTokenRunner(): void {\n clearTimeout(this.refreshTokenRunnerTimer)\n if (!this.credentials) {\n throw new Error('Unable to start refresh token runner without credentials')\n }\n const refreshIn: number = new Date(this.credentials.expires_at).getTime() - new Date().getTime()\n const refreshTimeout: number =\n this.refreshSeparationMilliseconds + Math.max(60000, refreshIn * 0.8) // Refresh 20% before the expires with a minimum of 60 sec\n this.logger?.info(\n `Setting timer to refresh token in ${Math.round(refreshTimeout / 1000)} seconds ` +\n `at ${new Date(new Date().getTime() + refreshTimeout).toTimeString()}`\n )\n this.refreshTokenRunnerTimer = setTimeout(async () => {\n try {\n await this.refreshToken()\n } catch (error) {\n const refreshTokenError = new RefreshTokenError(\n 'Refresh runner failed to refresh token with existing credentials',\n { cause: error }\n )\n this.emit(AuthenticatorEvents.ERROR, refreshTokenError)\n this.logger?.error(refreshTokenError)\n }\n }, refreshTimeout)\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method ensures that no parallel requests to refreshToken are done.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n async refreshToken(): Promise<Credentials> {\n this.assertIsSetup()\n if (this.refreshTokenPromise) {\n this.logger?.info('Refresh token already in progress: returning existing promise.')\n return await this.refreshTokenPromise\n }\n try {\n this.refreshTokenPromise = this._refreshToken()\n return await this.refreshTokenPromise\n } finally {\n this.refreshTokenPromise = undefined\n }\n }\n\n /**\n * Attempts the refresh the credentials.\n *\n * On failure it will throw an exception.\n * This method might end up signing the user out in case the refresh token are invalid.\n * It will not sign you out in case of network issues.\n *\n * @returns\n */\n async refreshTokenWithRetry(): Promise<Credentials> {\n this.assertIsSetup()\n const MAX_DEPTH = 7\n const MAX_TIMEOUT = 30 * 1000\n for (let depth = 0; depth < MAX_DEPTH; depth++) {\n try {\n return await this.refreshToken()\n } catch (err) {\n if (depth + 1 >= MAX_DEPTH) {\n throw err\n }\n if (err instanceof TokenNetworkError) {\n await this.wait(Math.min(2 ** depth * 1000, MAX_TIMEOUT))\n } else {\n throw err\n }\n }\n }\n return await this.refreshToken()\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method should only be called by `refreshToken`.\n *\n * Use `refreshToken` method if you need to refresh the token.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n private async _refreshToken(): Promise<Credentials> {\n this.logger?.info('Starting access token refresh')\n try {\n if (!this.credentials) {\n throw new Error('Failed to refresh token. No credentials available.')\n }\n const { refresh_token, access_token } = this.credentials\n const credentials = await this.api.refreshToken(refresh_token, access_token)\n this.logger?.info('Access token refreshed successfully')\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: credentials,\n isFromOtherInstance: false,\n })\n this._setupRefreshTokenRunner()\n return credentials\n } catch (error) {\n this.logger?.error('Failed to refresh token', error)\n if (error instanceof InvalidClientError) {\n if (typeof location !== 'undefined') {\n location.reload()\n } else {\n this.logger?.warn('Location reload not supported')\n throw error\n }\n }\n if (error instanceof RefreshTokenError) {\n await this.signOut(false)\n }\n throw error\n }\n }\n\n /**\n * Stores the credentials in secureStorage.\n *\n * @param {Credentials} credentials - The credentials to store in the secure storage.\n */\n private async storeCredentials(credentials: Credentials): Promise<void> {\n try {\n await this.secureStorage.setItem(STORE_CREDENTIALS_KEY, JSON.stringify(credentials))\n } catch (error: any) {\n this.logger?.error('Failed to store credentials in storage', error)\n }\n }\n\n private assertIsSetup() {\n if (!this.isSetup) {\n throw new Error('Authenticator needs to be setup before it can be used.')\n }\n }\n}\n\nexport default Authenticator\n","import { Credentials } from '@dstny/scp-credentials'\nimport axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\n\nexport abstract class AbstractAuthenticationApi {\n protected axiosInstance: AxiosInstance\n\n constructor(baseURL: string) {\n const config: AxiosRequestConfig = {\n baseURL,\n timeout: 50000,\n }\n this.axiosInstance = axios.create(config)\n }\n\n /**\n * Given a redirectUri it calculates the URL where the browser needs to be\n * redirected in other to authenticate\n *\n * @param {string} redirectUri\n * @returns {string} login url\n */\n abstract getLoginUrl(redirectUri: string): Promise<string>\n\n /**\n * Given the authorizationCode and the redirectUri this method will provide\n * credentials containing an access and refresh token\n *\n * @param {string} authorizationCode\n * @param {string} redirectUri\n * @returns {Promise<Credentials>}\n */\n abstract getToken(authorizationCode: string, redirectUri: string): Promise<Credentials>\n\n /**\n * Given a refresh token this method will provide a new set of credentials\n * containing an access token and a refresh token\n *\n * @param {string} refreshToken\n * @returns {Promise<Credentials>}\n */\n abstract refreshToken(refreshToken: string, accessToken: string): Promise<Credentials>\n\n /**\n * Given a access and refresh token, this method will logout the user from\n * the IAM\n *\n * @param {string} accessToken\n * @param {string} refreshToken\n * @returns {Promise<void>}\n */\n abstract logout(accessToken?: string, refreshToken?: string): Promise<void>\n}\n","/* eslint-disable no-async-promise-executor */\nimport { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport axios from 'axios'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetTokenResponse = {\n access_token: string\n refresh_token: string\n expires_in: number\n}\n\nexport class OAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly scope: string\n public readonly authorizationRoute: string\n\n private readonly baseURL: string\n\n constructor(baseURL: string, clientId: string, authorizationRoute: string, scope: string) {\n super(baseURL)\n this.baseURL = baseURL\n this.clientId = clientId\n this.authorizationRoute = authorizationRoute\n this.scope = scope\n }\n\n async getLoginUrl(redirectUri: string) {\n this.axiosInstance.getUri()\n return (\n `${this.baseURL}${this.authorizationRoute}` +\n `?client_id=${encodeURIComponent(this.clientId)}` +\n '&response_type=code' +\n `&redirect_uri=${encodeURIComponent(redirectUri)}` +\n (this.scope ? `&scope=${encodeURIComponent(this.scope)}` : '')\n )\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n code: authorizationCode,\n grant_type: 'authorization_code',\n redirect_uri: redirectUri,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async loginWithUsernamePassword(username: string, password: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'password',\n username,\n password,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const response = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n })\n )\n return new Credentials(\n response.data.access_token,\n response.data.refresh_token,\n response.data.expires_in\n )\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'unauthorized_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(_redirectUri?: string): Promise<void> {\n await this.axiosInstance.post('/logout', null, { withCredentials: true })\n }\n}\n","import { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport axios from 'axios'\nimport { decodeToken } from '../utils/jwt'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetLoginUrlResponse = {\n loginUrl: string\n}\n\ntype GetTokenResponse = {\n refreshToken: string\n accessToken: string\n message: string\n status: string\n}\n\nexport class SmgAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly realm: string\n\n constructor(baseURL: string, realm: string, clientId: string) {\n super(baseURL)\n this.clientId = clientId\n this.realm = realm\n }\n\n async getLoginUrl(redirectUri: string) {\n const { data } = await this.axiosInstance.get<GetLoginUrlResponse>(\n `/login/getloginurl/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`\n )\n\n const baseUrl = new URL(data.loginUrl)\n // The redirect_uri provided by the SMG is inacurate, this needs to be rewritten with the actual\n // redirect uri.\n baseUrl.searchParams.set('redirect_uri', redirectUri)\n // The authentication pathname of the SMG cannot be trusted to be configured correctly.\n // Duplicate '/' characters in the authentication URL causes the authentication\n // prompt to be displayed twice. Once when coven attempts to obtain a token, and\n // again when connect me attempts to obtain a token.\n // vv\n // example: https://keycloak.development.aws.d4sp.com//auth/realms/syslab1/protocol/openid-connect/auth\n baseUrl.pathname = baseUrl.pathname.replace(/\\/\\/+/g, '/')\n\n return baseUrl.toString()\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/getaccesstoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n code: authorizationCode,\n redirectUri: redirectUri,\n }\n )\n const { refreshToken, accessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(accessToken)\n const expires_in = exp - iat\n const expires_at = new Date()\n expires_at.setSeconds(expires_at.getSeconds() + expires_in)\n return new Credentials(accessToken, refreshToken, expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/refreshtoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n const { refreshToken: newRefreshToken, accessToken: newAccessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(newAccessToken)\n const expires_in = exp - iat\n return new Credentials(newAccessToken, newRefreshToken, expires_in)\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'invalid_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(refreshToken: string, accessToken: string): Promise<void> {\n await this.axiosInstance.post(\n `/login/logout/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n }\n}\n\nexport default SmgAuthApi\n","import Authenticator from './Authenticator'\n\nexport * from './types'\nexport * from './events'\n\nexport * from './api/AbstractAuthenticationApi'\nexport * from './api/OAuthApi'\nexport * from './api/SmgAuthApi'\n\nexport default Authenticator\n"],"mappings":";AAAO,IAAM,SAAS,oBAAI,QAAQ;AAC3B,IAAM,YAAY,oBAAI,QAAQ;AAC9B,IAAM,eAAe,oBAAI,QAAQ;;;ACAxC,I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,CAAC;AAAA,QACD;AAAA,UACE,KAAK;AAAA,UACL;AAAA,QACF;AAAA,MACF;AACA,YAAM,EAAE,cAAc,iBAAiB,aAAa,eAAe,IAAI;AAEvE,YAAM,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,YAAY,cAAc;AACvD,YAAM,aAAa,MAAM;AACzB,aAAO,IAAI,YAAY,gBAAgB,iBAAiB,UAAU;AAAA,IACpE,SAAS,OAAO;AACd,UAAIC,OAAM,aAAa,KAAK,GAAG;AAC7B,YAAI,MAAM,YAAY,iBAAiB;AACrC,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AACA,cAAM,aAAa,MAAM,UAAU;AACnC,YAAI,eAAe,OAAO,MAAM,UAAU,MAAM,UAAU,kBAAkB;AAC1E,gBAAM,IAAI,2BAAmB;AAAA,QAC/B;AACA,YAAI,OAAO,eAAe,YAAY,cAAc,OAAO,aAAa,KAAK;AAC3E,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,cAAsB,aAAoC;AACrE,UAAM,KAAK,cAAc;AAAA,MACvB,uBAAuB,mBAAmB,KAAK,KAAK,CAAC,WAAW;AAAA,QAC9D,KAAK;AAAA,MACP,CAAC;AAAA,MACD;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACzGA,IAAO,cAAQ;","names":["eventName","AuthenticatorEvents","credentials","axios","axios","axios","axios"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/maps.js","../../../node_modules/.pnpm/emittery@1.1.0/node_modules/emittery/index.js","../../credentials/src/utils.ts","../../credentials/src/Credentials.ts","../src/utils/jwt.ts","../src/events.ts","../src/types.ts","../src/utils/separation.ts","../src/errors/TokenNetworkError.ts","../src/errors/RefreshTokenError.ts","../src/errors/AuthorizationError.ts","../src/errors/InvalidClientError.ts","../src/Authenticator.ts","../src/api/AbstractAuthenticationApi.ts","../src/api/OAuthApi.ts","../src/api/SmgAuthApi.ts","../src/index.ts"],"sourcesContent":["export const anyMap = new WeakMap();\nexport const eventsMap = new WeakMap();\nexport const producersMap = new WeakMap();\n","import {anyMap, producersMap, eventsMap} from './maps.js';\n\nconst anyProducer = Symbol('anyProducer');\nconst resolvedPromise = Promise.resolve();\n\n// Define symbols for \"meta\" events.\nconst listenerAdded = Symbol('listenerAdded');\nconst listenerRemoved = Symbol('listenerRemoved');\n\nlet canEmitMetaEvents = false;\nlet isGlobalDebugEnabled = false;\n\nconst isEventKeyType = key => typeof key === 'string' || typeof key === 'symbol' || typeof key === 'number';\n\nfunction assertEventName(eventName) {\n\tif (!isEventKeyType(eventName)) {\n\t\tthrow new TypeError('`eventName` must be a string, symbol, or number');\n\t}\n}\n\nfunction assertListener(listener) {\n\tif (typeof listener !== 'function') {\n\t\tthrow new TypeError('listener must be a function');\n\t}\n}\n\nfunction getListeners(instance, eventName) {\n\tconst events = eventsMap.get(instance);\n\tif (!events.has(eventName)) {\n\t\treturn;\n\t}\n\n\treturn events.get(eventName);\n}\n\nfunction getEventProducers(instance, eventName) {\n\tconst key = isEventKeyType(eventName) ? eventName : anyProducer;\n\tconst producers = producersMap.get(instance);\n\tif (!producers.has(key)) {\n\t\treturn;\n\t}\n\n\treturn producers.get(key);\n}\n\nfunction enqueueProducers(instance, eventName, eventData) {\n\tconst producers = producersMap.get(instance);\n\tif (producers.has(eventName)) {\n\t\tfor (const producer of producers.get(eventName)) {\n\t\t\tproducer.enqueue(eventData);\n\t\t}\n\t}\n\n\tif (producers.has(anyProducer)) {\n\t\tconst item = Promise.all([eventName, eventData]);\n\t\tfor (const producer of producers.get(anyProducer)) {\n\t\t\tproducer.enqueue(item);\n\t\t}\n\t}\n}\n\nfunction iterator(instance, eventNames) {\n\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\tlet isFinished = false;\n\tlet flush = () => {};\n\tlet queue = [];\n\n\tconst producer = {\n\t\tenqueue(item) {\n\t\t\tqueue.push(item);\n\t\t\tflush();\n\t\t},\n\t\tfinish() {\n\t\t\tisFinished = true;\n\t\t\tflush();\n\t\t},\n\t};\n\n\tfor (const eventName of eventNames) {\n\t\tlet set = getEventProducers(instance, eventName);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tconst producers = producersMap.get(instance);\n\t\t\tproducers.set(eventName, set);\n\t\t}\n\n\t\tset.add(producer);\n\t}\n\n\treturn {\n\t\tasync next() {\n\t\t\tif (!queue) {\n\t\t\t\treturn {done: true};\n\t\t\t}\n\n\t\t\tif (queue.length === 0) {\n\t\t\t\tif (isFinished) {\n\t\t\t\t\tqueue = undefined;\n\t\t\t\t\treturn this.next();\n\t\t\t\t}\n\n\t\t\t\tawait new Promise(resolve => {\n\t\t\t\t\tflush = resolve;\n\t\t\t\t});\n\n\t\t\t\treturn this.next();\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdone: false,\n\t\t\t\tvalue: await queue.shift(),\n\t\t\t};\n\t\t},\n\n\t\tasync return(value) {\n\t\t\tqueue = undefined;\n\n\t\t\tfor (const eventName of eventNames) {\n\t\t\t\tconst set = getEventProducers(instance, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.delete(producer);\n\t\t\t\t\tif (set.size === 0) {\n\t\t\t\t\t\tconst producers = producersMap.get(instance);\n\t\t\t\t\t\tproducers.delete(eventName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tflush();\n\n\t\t\treturn arguments.length > 0\n\t\t\t\t? {done: true, value: await value}\n\t\t\t\t: {done: true};\n\t\t},\n\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t};\n}\n\nfunction defaultMethodNamesOrAssert(methodNames) {\n\tif (methodNames === undefined) {\n\t\treturn allEmitteryMethods;\n\t}\n\n\tif (!Array.isArray(methodNames)) {\n\t\tthrow new TypeError('`methodNames` must be an array of strings');\n\t}\n\n\tfor (const methodName of methodNames) {\n\t\tif (!allEmitteryMethods.includes(methodName)) {\n\t\t\tif (typeof methodName !== 'string') {\n\t\t\t\tthrow new TypeError('`methodNames` element must be a string');\n\t\t\t}\n\n\t\t\tthrow new Error(`${methodName} is not Emittery method`);\n\t\t}\n\t}\n\n\treturn methodNames;\n}\n\nconst isMetaEvent = eventName => eventName === listenerAdded || eventName === listenerRemoved;\n\nfunction emitMetaEvent(emitter, eventName, eventData) {\n\tif (!isMetaEvent(eventName)) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tcanEmitMetaEvents = true;\n\t\temitter.emit(eventName, eventData);\n\t} finally {\n\t\tcanEmitMetaEvents = false;\n\t}\n}\n\nexport default class Emittery {\n\tstatic mixin(emitteryPropertyName, methodNames) {\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\t\treturn target => {\n\t\t\tif (typeof target !== 'function') {\n\t\t\t\tthrow new TypeError('`target` must be function');\n\t\t\t}\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tif (target.prototype[methodName] !== undefined) {\n\t\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction getEmitteryProperty() {\n\t\t\t\tObject.defineProperty(this, emitteryPropertyName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: new Emittery(),\n\t\t\t\t});\n\t\t\t\treturn this[emitteryPropertyName];\n\t\t\t}\n\n\t\t\tObject.defineProperty(target.prototype, emitteryPropertyName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tget: getEmitteryProperty,\n\t\t\t});\n\n\t\t\tconst emitteryMethodCaller = methodName => function (...args) {\n\t\t\t\treturn this[emitteryPropertyName][methodName](...args);\n\t\t\t};\n\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tObject.defineProperty(target.prototype, methodName, {\n\t\t\t\t\tenumerable: false,\n\t\t\t\t\tvalue: emitteryMethodCaller(methodName),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn target;\n\t\t};\n\t}\n\n\tstatic get isDebugEnabled() {\n\t\t// In a browser environment, `globalThis.process` can potentially reference a DOM Element with a `#process` ID,\n\t\t// so instead of just type checking `globalThis.process`, we need to make sure that `globalThis.process.env` exists.\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tif (typeof globalThis.process?.env !== 'object') {\n\t\t\treturn isGlobalDebugEnabled;\n\t\t}\n\n\t\t// eslint-disable-next-line n/prefer-global/process\n\t\tconst {env} = globalThis.process ?? {env: {}};\n\t\treturn env.DEBUG === 'emittery' || env.DEBUG === '*' || isGlobalDebugEnabled;\n\t}\n\n\tstatic set isDebugEnabled(newValue) {\n\t\tisGlobalDebugEnabled = newValue;\n\t}\n\n\tconstructor(options = {}) {\n\t\tanyMap.set(this, new Set());\n\t\teventsMap.set(this, new Map());\n\t\tproducersMap.set(this, new Map());\n\n\t\tproducersMap.get(this).set(anyProducer, new Set());\n\n\t\tthis.debug = options.debug ?? {};\n\n\t\tif (this.debug.enabled === undefined) {\n\t\t\tthis.debug.enabled = false;\n\t\t}\n\n\t\tif (!this.debug.logger) {\n\t\t\tthis.debug.logger = (type, debugName, eventName, eventData) => {\n\t\t\t\ttry {\n\t\t\t\t\t// TODO: Use https://github.com/sindresorhus/safe-stringify when the package is more mature. Just copy-paste the code.\n\t\t\t\t\teventData = JSON.stringify(eventData);\n\t\t\t\t} catch {\n\t\t\t\t\teventData = `Object with the following keys failed to stringify: ${Object.keys(eventData).join(',')}`;\n\t\t\t\t}\n\n\t\t\t\tif (typeof eventName === 'symbol' || typeof eventName === 'number') {\n\t\t\t\t\teventName = eventName.toString();\n\t\t\t\t}\n\n\t\t\t\tconst currentTime = new Date();\n\t\t\t\tconst logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;\n\t\t\t\tconsole.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\\n\\tdata: ${eventData}`);\n\t\t\t};\n\t\t}\n\t}\n\n\tlogIfDebugEnabled(type, eventName, eventData) {\n\t\tif (Emittery.isDebugEnabled || this.debug.enabled) {\n\t\t\tthis.debug.logger(type, this.debug.name, eventName, eventData);\n\t\t}\n\t}\n\n\ton(eventNames, listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tlet set = getListeners(this, eventName);\n\t\t\tif (!set) {\n\t\t\t\tset = new Set();\n\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\tevents.set(eventName, set);\n\t\t\t}\n\n\t\t\tset.add(listener);\n\n\t\t\tthis.logIfDebugEnabled('subscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerAdded, {eventName, listener});\n\t\t\t}\n\t\t}\n\n\t\tconst off = () => {\n\t\t\tthis.off(eventNames, listener);\n\t\t\tsignal?.removeEventListener('abort', off);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', off, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toff();\n\t\t}\n\n\t\treturn off;\n\t}\n\n\toff(eventNames, listener) {\n\t\tassertListener(listener);\n\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t\tconst set = getListeners(this, eventName);\n\t\t\tif (set) {\n\t\t\t\tset.delete(listener);\n\t\t\t\tif (set.size === 0) {\n\t\t\t\t\tconst events = eventsMap.get(this);\n\t\t\t\t\tevents.delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.logIfDebugEnabled('unsubscribe', eventName, undefined);\n\n\t\t\tif (!isMetaEvent(eventName)) {\n\t\t\t\temitMetaEvent(this, listenerRemoved, {eventName, listener});\n\t\t\t}\n\t\t}\n\t}\n\n\tonce(eventNames) {\n\t\tlet off_;\n\n\t\tconst promise = new Promise(resolve => {\n\t\t\toff_ = this.on(eventNames, data => {\n\t\t\t\toff_();\n\t\t\t\tresolve(data);\n\t\t\t});\n\t\t});\n\n\t\tpromise.off = off_;\n\t\treturn promise;\n\t}\n\n\tevents(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tfor (const eventName of eventNames) {\n\t\t\tassertEventName(eventName);\n\t\t}\n\n\t\treturn iterator(this, eventNames);\n\t}\n\n\tasync emit(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emit', eventName, eventData);\n\n\t\tenqueueProducers(this, eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\tawait Promise.all([\n\t\t\t...staticListeners.map(async listener => {\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\treturn listener(eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t\t...staticAnyListeners.map(async listener => {\n\t\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\t\treturn listener(eventName, eventData);\n\t\t\t\t}\n\t\t\t}),\n\t\t]);\n\t}\n\n\tasync emitSerial(eventName, eventData) {\n\t\tassertEventName(eventName);\n\n\t\tif (isMetaEvent(eventName) && !canEmitMetaEvents) {\n\t\t\tthrow new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');\n\t\t}\n\n\t\tthis.logIfDebugEnabled('emitSerial', eventName, eventData);\n\n\t\tconst listeners = getListeners(this, eventName) ?? new Set();\n\t\tconst anyListeners = anyMap.get(this);\n\t\tconst staticListeners = [...listeners];\n\t\tconst staticAnyListeners = [...anyListeners];\n\n\t\tawait resolvedPromise;\n\t\t/* eslint-disable no-await-in-loop */\n\t\tfor (const listener of staticListeners) {\n\t\t\tif (listeners.has(listener)) {\n\t\t\t\tawait listener(eventData);\n\t\t\t}\n\t\t}\n\n\t\tfor (const listener of staticAnyListeners) {\n\t\t\tif (anyListeners.has(listener)) {\n\t\t\t\tawait listener(eventName, eventData);\n\t\t\t}\n\t\t}\n\t\t/* eslint-enable no-await-in-loop */\n\t}\n\n\tonAny(listener, {signal} = {}) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('subscribeAny', undefined, undefined);\n\n\t\tanyMap.get(this).add(listener);\n\t\temitMetaEvent(this, listenerAdded, {listener});\n\n\t\tconst offAny = () => {\n\t\t\tthis.offAny(listener);\n\t\t\tsignal?.removeEventListener('abort', offAny);\n\t\t};\n\n\t\tsignal?.addEventListener('abort', offAny, {once: true});\n\n\t\tif (signal?.aborted) {\n\t\t\toffAny();\n\t\t}\n\n\t\treturn offAny;\n\t}\n\n\tanyEvent() {\n\t\treturn iterator(this);\n\t}\n\n\toffAny(listener) {\n\t\tassertListener(listener);\n\n\t\tthis.logIfDebugEnabled('unsubscribeAny', undefined, undefined);\n\n\t\temitMetaEvent(this, listenerRemoved, {listener});\n\t\tanyMap.get(this).delete(listener);\n\t}\n\n\tclearListeners(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tthis.logIfDebugEnabled('clear', eventName, undefined);\n\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tconst set = getListeners(this, eventName);\n\t\t\t\tif (set) {\n\t\t\t\t\tset.clear();\n\t\t\t\t}\n\n\t\t\t\tconst producers = getEventProducers(this, eventName);\n\t\t\t\tif (producers) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tanyMap.get(this).clear();\n\n\t\t\t\tfor (const [eventName, listeners] of eventsMap.get(this).entries()) {\n\t\t\t\t\tlisteners.clear();\n\t\t\t\t\teventsMap.get(this).delete(eventName);\n\t\t\t\t}\n\n\t\t\t\tfor (const [eventName, producers] of producersMap.get(this).entries()) {\n\t\t\t\t\tfor (const producer of producers) {\n\t\t\t\t\t\tproducer.finish();\n\t\t\t\t\t}\n\n\t\t\t\t\tproducers.clear();\n\t\t\t\t\tproducersMap.get(this).delete(eventName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlistenerCount(eventNames) {\n\t\teventNames = Array.isArray(eventNames) ? eventNames : [eventNames];\n\t\tlet count = 0;\n\n\t\tfor (const eventName of eventNames) {\n\t\t\tif (isEventKeyType(eventName)) {\n\t\t\t\tcount += anyMap.get(this).size\n\t\t\t\t\t+ (getListeners(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this, eventName)?.size ?? 0)\n\t\t\t\t\t+ (getEventProducers(this)?.size ?? 0);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (eventName !== undefined) {\n\t\t\t\tassertEventName(eventName);\n\t\t\t}\n\n\t\t\tcount += anyMap.get(this).size;\n\n\t\t\tfor (const value of eventsMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\n\t\t\tfor (const value of producersMap.get(this).values()) {\n\t\t\t\tcount += value.size;\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tbindMethods(target, methodNames) {\n\t\tif (typeof target !== 'object' || target === null) {\n\t\t\tthrow new TypeError('`target` must be an object');\n\t\t}\n\n\t\tmethodNames = defaultMethodNamesOrAssert(methodNames);\n\n\t\tfor (const methodName of methodNames) {\n\t\t\tif (target[methodName] !== undefined) {\n\t\t\t\tthrow new Error(`The property \\`${methodName}\\` already exists on \\`target\\``);\n\t\t\t}\n\n\t\t\tObject.defineProperty(target, methodName, {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: this[methodName].bind(this),\n\t\t\t});\n\t\t}\n\t}\n}\n\nconst allEmitteryMethods = Object.getOwnPropertyNames(Emittery.prototype).filter(v => v !== 'constructor');\n\nObject.defineProperty(Emittery, 'listenerAdded', {\n\tvalue: listenerAdded,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\nObject.defineProperty(Emittery, 'listenerRemoved', {\n\tvalue: listenerRemoved,\n\twritable: false,\n\tenumerable: true,\n\tconfigurable: false,\n});\n","// declare const Buffer\n\nfunction byteToPercent(b: string) {\n return `%${`00${b.charCodeAt(0).toString(16)}`.slice(-2)}`\n}\n\nexport function base64decode(str: string): string | undefined {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\n\nexport async function sha1(str: string) {\n if (typeof crypto === 'object') {\n const hash = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(str))\n return Array.from(new Uint8Array(hash))\n .map((v) => v.toString(16).padStart(2, '0'))\n .join('')\n } else {\n return binb2hex(core_sha1(str2binb(str), str.length * chrsz))\n }\n}\n\nconst hexcase = 0 /* hex output format. 0 - lowercase; 1 - uppercase */\nconst b64pad = '' /* base-64 pad character. \"=\" for strict RFC compliance */\nconst chrsz = 8 /* bits per input character. 8 - ASCII; 16 - Unicode */\n\n/*\n * Calculate the SHA-1 of an array of big-endian words, and a bit length\n */\nfunction core_sha1(x: Array<number>, len: number) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - (len % 32))\n x[(((len + 64) >> 9) << 4) + 15] = len\n\n var w = Array(80)\n var a = 1732584193\n var b = -271733879\n var c = -1732584194\n var d = 271733878\n var e = -1009589776\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a\n var oldb = b\n var oldc = c\n var oldd = d\n var olde = e\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j]\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)\n var t = safe_add(\n safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n safe_add(safe_add(e, w[j]), sha1_kt(j))\n )\n e = d\n d = c\n c = rol(b, 30)\n b = a\n a = t\n }\n\n a = safe_add(a, olda)\n b = safe_add(b, oldb)\n c = safe_add(c, oldc)\n d = safe_add(d, oldd)\n e = safe_add(e, olde)\n }\n return Array(a, b, c, d, e)\n}\n\n/*\n * Perform the appropriate triplet combination function for the current\n * iteration\n */\nfunction sha1_ft(t: number, b: number, c: number, d: number) {\n if (t < 20) return (b & c) | (~b & d)\n if (t < 40) return b ^ c ^ d\n if (t < 60) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\n/*\n * Determine the appropriate additive constant for the current iteration\n */\nfunction sha1_kt(t: number) {\n return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514\n}\n\n/*\n * Calculate the HMAC-SHA1 of a key and some data\n */\nfunction core_hmac_sha1(key: string, data: string) {\n let bkey = str2binb(key)\n if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz)\n\n let ipad = Array(16),\n opad = Array(16)\n for (let i = 0; i < 16; i++) {\n ipad[i] = bkey[i] ^ 0x36363636\n opad[i] = bkey[i] ^ 0x5c5c5c5c\n }\n\n let hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz)\n return core_sha1(opad.concat(hash), 512 + 160)\n}\n\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\nfunction safe_add(x: number, y: number) {\n const lsw = (x & 0xffff) + (y & 0xffff)\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16)\n return (msw << 16) | (lsw & 0xffff)\n}\n\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\nfunction rol(num: number, cnt: number) {\n return (num << cnt) | (num >>> (32 - cnt))\n}\n\n/*\n * Convert an 8-bit or 16-bit string to an array of big-endian words\n * In 8-bit function, characters >255 have their hi-byte silently ignored.\n */\nfunction str2binb(str: string): Array<number> {\n const bin: Array<number> = []\n const mask = (1 << chrsz) - 1\n for (let i = 0; i < str.length * chrsz; i += chrsz)\n bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - (i % 32))\n return bin\n}\n\n/*\n * Convert an array of big-endian words to a string\n */\nfunction binb2str(bin: Array<number>): string {\n let str = ''\n let mask = (1 << chrsz) - 1\n for (let i = 0; i < bin.length * 32; i += chrsz)\n str += String.fromCharCode((bin[i >> 5] >>> (32 - chrsz - (i % 32))) & mask)\n return str\n}\n\n/*\n * Convert an array of big-endian words to a hex string.\n */\nfunction binb2hex(binarray: Array<number>) {\n let hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i++) {\n str +=\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) +\n hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf)\n }\n return str\n}\n\n/*\n * Convert an array of big-endian words to a base-64 string\n */\nfunction binb2b64(binarray: Array<number>) {\n let tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n let str = ''\n for (let i = 0; i < binarray.length * 4; i += 3) {\n let triplet =\n (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) << 16) |\n (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) & 0xff) << 8) |\n ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) & 0xff)\n for (let j = 0; j < 4; j++) {\n if (i * 8 + j * 6 > binarray.length * 32) str += b64pad\n else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)\n }\n }\n return str\n}\n","import { base64decode, sha1 } from './utils'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\n\nexport const STORE_CREDENTILAS_KEY = 'sdk-auth-credential'\n\ntype CredentialsCallback = (callback: Credentials) => void\ntype JSONCredentials = {\n access_token: string\n refresh_token: string\n expires_in: number\n expires_at: Date\n token_type: 'Bearer' | string\n}\n\nexport default class Credentials {\n static async fromStorage(storage: SecureStorageHandler): Promise<Credentials> {\n const str: string | null = await storage.getItem(STORE_CREDENTILAS_KEY)\n if (str == null || str == undefined) {\n throw new Error('No credentials found in storage.')\n }\n return Credentials.fromJSON(str)\n }\n\n static async toStorage(storage: SecureStorageHandler, credentials: Credentials): Promise<void> {\n await storage.setItem(STORE_CREDENTILAS_KEY, JSON.stringify(credentials))\n }\n\n static async clearFromStorage(storage: SecureStorageHandler): Promise<void> {\n await storage.deleteItem(STORE_CREDENTILAS_KEY)\n }\n\n static fromJSON(str: string): Credentials {\n const { access_token, refresh_token, expires_in } = JSON.parse(str)\n return new Credentials(access_token, refresh_token, expires_in)\n }\n\n static onStorageUpdate(storage: SecureStorageHandler, callback: CredentialsCallback): () => void {\n return storage.on(STORE_CREDENTILAS_KEY, (credentials: string | null) => {\n if (typeof credentials === 'string') {\n callback(Credentials.fromJSON(credentials))\n }\n })\n }\n\n static equals(a?: Credentials, b?: Credentials) {\n if (!a && !b) {\n return true\n }\n if ((a && !b) || (b && !a)) {\n return false\n }\n return (\n a?.access_token === b?.access_token &&\n a?._refresh_token === b?.refresh_token &&\n a?.expires_in === b?.expires_in\n )\n }\n\n /**\n * Used to access resources.\n */\n private _access_token: string\n /**\n * Used to obtain a new access token.\n */\n private _refresh_token: string\n /**\n * Number of seconds until the access token expires.\n * This value is calculated at the moment the access token is generated.\n */\n private _expires_in: number\n\n constructor(access_token: string, refresh_token: string, expires_in: number) {\n this._access_token = access_token\n this._refresh_token = refresh_token\n this._expires_in = expires_in\n }\n\n /**\n * Lists the claims present in the access token.\n */\n get claims() {\n const fallback = {}\n if (typeof this._access_token != 'string') {\n return fallback\n }\n const [, b64payload] = this._access_token.split('.')\n const payload = base64decode(b64payload)\n if (!payload) {\n return fallback\n }\n try {\n return JSON.parse(payload)\n } catch (err) {\n return {}\n }\n }\n\n get access_token(): string {\n return this._access_token\n }\n\n get refresh_token(): string {\n return this._refresh_token\n }\n\n get expires_in(): number {\n return this._expires_in\n }\n\n get token_type(): string {\n return 'Bearer'\n }\n\n get expires_at(): Date {\n if (typeof this.claims?.exp === 'number') {\n return new Date(this.claims?.exp * 1000)\n }\n const expiryDate = new Date()\n expiryDate.setSeconds(expiryDate.getSeconds() + this._expires_in)\n return expiryDate\n }\n\n isExpired(): boolean {\n return this.expires_at && new Date().getTime() > new Date(this.expires_at).getTime()\n }\n\n async getUepId(): Promise<string> {\n const { sub, uep_id: rawUepId } = this.claims \n if (!sub) {\n throw new Error(\"Missing 'sub' claim.\")\n }\n\n if (rawUepId) {\n return rawUepId\n }\n \n return await sha1(sub)\n }\n\n toJSON(): JSONCredentials {\n return {\n access_token: this._access_token,\n refresh_token: this._refresh_token,\n expires_in: this._expires_in,\n expires_at: this.expires_at,\n token_type: this.token_type,\n }\n }\n}\n","export interface JwtPayload {\n [key: string]: any\n iss?: string | undefined\n sub?: string | undefined\n aud?: string | string[] | undefined\n exp?: number | undefined\n nbf?: number | undefined\n iat?: number | undefined\n jti?: string | undefined\n}\n\nexport function decodeToken(token: string): JwtPayload {\n if (!token) {\n throw new Error('No token provided')\n }\n const parts = token.split('.')\n\n if (parts.length !== 3) {\n throw new Error('JWT must have 3 parts')\n }\n\n const decoded = urlBase64Decode(parts[1])\n if (!decoded) {\n throw new Error('Cannot decode the token')\n }\n\n return JSON.parse(decoded)\n}\n\nfunction urlBase64Decode(str: string): string {\n let output = str.replace(/-/g, '+').replace(/_/g, '/')\n switch (output.length % 4) {\n case 0: {\n break\n }\n case 2: {\n output += '=='\n break\n }\n case 3: {\n output += '='\n break\n }\n default: {\n // TODO\n throw new Error('Illegal base64url string!')\n }\n }\n return b64DecodeUnicode(output)\n}\n\nfunction b64DecodeUnicode(str: any): any {\n return decodeURIComponent(\n Array.prototype.map\n .call(b64decode(str), (c: any) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join('')\n )\n}\n\nexport function b64decode(str: string): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let output: string = ''\n\n str = String(str).replace(/={1,10}$/, '')\n\n if (str.length % 4 === 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\")\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // tslint:disable-next-line:no-conditional-assignment\n (buffer = str.charAt(idx++));\n // tslint:disable-next-line:no-bitwise\n ~buffer &&\n // tslint:disable-next-line:no-conditional-assignment\n ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)\n ? // tslint:disable-next-line:no-bitwise\n (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))\n : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer)\n }\n return output\n}\nexport function b64encode(input: string, encode = true) {\n let output = ''\n let chr1, chr2, chr3, enc1, enc2, enc3, enc4\n let i = 0\n const _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n if (encode) {\n input = _utf8_encode(input)\n }\n\n while (i < input.length) {\n chr1 = input.charCodeAt(i++)\n chr2 = input.charCodeAt(i++)\n chr3 = input.charCodeAt(i++)\n\n enc1 = chr1 >> 2\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)\n enc4 = chr3 & 63\n\n if (isNaN(chr2)) {\n enc3 = enc4 = 64\n } else if (isNaN(chr3)) {\n enc4 = 64\n }\n\n output =\n output +\n _keyStr.charAt(enc1) +\n _keyStr.charAt(enc2) +\n _keyStr.charAt(enc3) +\n _keyStr.charAt(enc4)\n }\n return output\n}\n\nexport function _utf8_encode(string: string) {\n string = string.replace(/\\r\\n/g, '\\n')\n let utftext = ''\n\n for (let n = 0; n < string.length; n++) {\n const c = string.charCodeAt(n)\n\n if (c < 128) {\n utftext += String.fromCharCode(c)\n } else if (c > 127 && c < 2048) {\n utftext += String.fromCharCode((c >> 6) | 192)\n utftext += String.fromCharCode((c & 63) | 128)\n } else {\n utftext += String.fromCharCode((c >> 12) | 224)\n utftext += String.fromCharCode(((c >> 6) & 63) | 128)\n utftext += String.fromCharCode((c & 63) | 128)\n }\n }\n return utftext\n}\n","export enum AuthenticatorEvents {\n CREDENTIALS = 'CREDENTIALS',\n ACCESS_TOKEN = 'ACCESS_TOKEN',\n JWT_PAYLOAD = 'JWT_PAYLOAD',\n STATE_CHANGE = 'STATE_CHANGE',\n ERROR = 'ERROR',\n}\n","import { Credentials } from '@dstny/scp-credentials'\n\nexport const STORE_CREDENTIALS_KEY = 'sdk-auth-credential'\nexport const STORE_REFRESH_SEPARATION_SECONDS = 'sdk-separation-seconds'\n\nexport type AuthenticatorState = boolean\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace'\nexport interface Logger {\n log(...arg: any[]): void\n error(...arg: any[]): void\n warn(...arg: any[]): void\n info(...arg: any[]): void\n debug(...arg: any[]): void\n trace(...arg: any[]): void\n\n setLevel(level: LogLevel, persist?: boolean): void\n resetLevel(): void\n}\n\nexport interface AuthenticatorOptions {\n /**\n * The authenticator library will try to use these credentials\n * when the setup method is invoked.\n *\n * This might be useful if you already have credentials available\n * and want to avoid doing the authentication procedure.\n */\n credentials?: Credentials\n /**\n * The authenticator library will use this logger instance for its\n * log statements.\n */\n logger?: Logger\n}\n","import { SecureStorageHandler } from '@dstny/scp-storage'\nimport { STORE_REFRESH_SEPARATION_SECONDS } from '../types'\n\nexport const getRefreshSeparationMilliseconds = async (\n storage: SecureStorageHandler\n): Promise<number> => {\n const next = parseInt((await storage.getItem(STORE_REFRESH_SEPARATION_SECONDS)) || '0') || 0\n await storage.setItem(STORE_REFRESH_SEPARATION_SECONDS, '' + ((next + 5) % 60))\n return next * 1000\n}\n\n\n","class TokenNetworkError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Network unavailable to refresh the network', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'NetworkError'\n }\n}\n\nexport default TokenNetworkError\n","/**\n * This kind of exceptions are using for reporting error cases for refresh token action such as update, request and ect.\n */\nclass RefreshTokenError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your token or session is expired.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'RefreshTokenError'\n }\n}\n\nexport default RefreshTokenError\n","/**\n * Use it for authorization specific errors\n * Depends on reason of exception use proper type\n */\nclass AuthorizationError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Authorization failed', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'AuthorizationError'\n }\n}\n\nexport default AuthorizationError\n","/**\n * This kind of is launched when the configured client is invalid\n */\nclass InvalidClientError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message || 'Your client is invalid.', options)\n Object.setPrototypeOf(this, new.target.prototype)\n this.name = 'InvalidClientError'\n }\n}\n\nexport default InvalidClientError\n","import Emittery from 'emittery'\n\nimport { Credentials } from '@dstny/scp-credentials'\nimport { SecureStorageHandler } from '@dstny/scp-storage'\nimport { AbstractAuthenticationApi } from './api/AbstractAuthenticationApi'\nimport { decodeToken, JwtPayload } from './utils/jwt'\nimport { AuthenticatorEvents } from './events'\nimport { AuthenticatorOptions, AuthenticatorState, Logger, STORE_CREDENTIALS_KEY } from './types'\nimport { getRefreshSeparationMilliseconds } from './utils/separation'\nimport TokenNetworkError from './errors/TokenNetworkError'\nimport RefreshTokenError from './errors/RefreshTokenError'\nimport AuthorizationError from './errors/AuthorizationError'\nimport InvalidClientError from './errors/InvalidClientError'\n\nconst INTERNAL_CREDENTIALS = 'INTERNAL_CREDENTIALS'\n\nclass Authenticator extends Emittery {\n private readonly api: AbstractAuthenticationApi\n private readonly secureStorage: SecureStorageHandler\n private readonly logger?: Logger\n private readonly initialCredentials?: Credentials\n\n private _state?: boolean = false\n private _credentials?: Credentials\n private _jwtPayload?: JwtPayload\n\n private isSetup: boolean = false\n private refreshTokenRunnerTimer?: any\n private refreshSeparationMilliseconds: number = 0\n private refreshTokenPromise?: Promise<Credentials>\n private removeCredentialStorageUpdates?: () => void\n private unsubscribeListenerAdded?: () => void\n private unsubscribeUpdateState?: () => void\n private timers: Map<ReturnType<typeof setTimeout>, (error: any) => void> = new Map()\n\n /**\n * In some cases we don't want to trigger the logout automatically\n * on refresh failure.\n *\n * When defined, this method will be invoked after the refresh failure\n * allowing you to define the behavior in that case.\n *\n * Example: You might not want sign out the user immediately\n * when your application is handling calls and you have ongoing calls.\n *\n * @returns {Promise<void>}\n */\n public delegateSignOutOnRefreshFailure?: () => Promise<void>\n\n public get jwtPayload(): JwtPayload | undefined {\n return this._jwtPayload\n }\n\n public get credentials(): Credentials | undefined {\n return this._credentials\n }\n\n public get state(): AuthenticatorState {\n return this._state ?? false\n }\n\n /**\n *\n * @param {ConnectEmitter} globalEmitter\n * @param {API} api\n * @param {string} oauthUrl\n */\n constructor(\n api: AbstractAuthenticationApi,\n secureStorage: SecureStorageHandler,\n options?: AuthenticatorOptions\n ) {\n super()\n this.api = api\n this.secureStorage = secureStorage\n this.logger = options?.logger\n this.initialCredentials = options?.credentials\n }\n\n /**\n * Starts the authenticator\n */\n async setup(): Promise<void> {\n let credentials\n\n if (this.initialCredentials) {\n credentials = this.initialCredentials\n } else {\n const localStorageCredentials = await this.secureStorage.getItem(STORE_CREDENTIALS_KEY)\n if (typeof localStorageCredentials === 'string') {\n credentials = Credentials.fromJSON(localStorageCredentials)\n }\n }\n\n // When loading a second instance of ConnectMe on the same browser,\n // the second instance cannot use the refresh token at the same time\n // as the first instance. In that case they will try to use the same\n // refresh_token and the instance that comes last will be returned an error.\n\n // Two mechanisms are put in place to mitigate this:\n // - The first instance to obtain the refresh token will save it to the SecureStorageHandler.\n // Other instances will be notified of the new token. When an instance recevices\n // credentials from another instance they will reset their _setupRefreshTokenRunner,\n // effectively becoming slave from the first instance.\n // - An instance separation delay is added, which separates the refresh of each instance\n // by 5 seconds. Up to 12 instance supported. 60 secs / 5 seconds delay\n this.removeCredentialStorageUpdates = Credentials.onStorageUpdate(\n this.secureStorage,\n (credentials: Credentials) => {\n this._signInWithCredentials(credentials, true)\n }\n )\n // _refreshSeparationMilliseconds is used in _setupRefreshTokenRunner\n this.refreshSeparationMilliseconds = await getRefreshSeparationMilliseconds(this.secureStorage)\n\n // Emit current credentials/access_token/jwt if they are defined when someone registers a listener\n this.unsubscribeListenerAdded = this.on(Emittery.listenerAdded, ({ listener, eventName }) => {\n if (eventName === AuthenticatorEvents.CREDENTIALS && this._credentials) {\n listener(this._credentials)\n } else if (eventName === AuthenticatorEvents.ACCESS_TOKEN && this._credentials) {\n listener(decodeToken(this._credentials.access_token))\n } else if (eventName === AuthenticatorEvents.JWT_PAYLOAD && this._jwtPayload) {\n listener(this._jwtPayload)\n }\n })\n\n // Update jwt payload and state, and re-broadcast credentials update\n this.unsubscribeUpdateState = this.on(\n INTERNAL_CREDENTIALS,\n async ({ credentials, isFromOtherInstance }) => {\n if (Credentials.equals(this._credentials, credentials)) {\n return\n }\n this._credentials = credentials\n this.emit(AuthenticatorEvents.CREDENTIALS, credentials)\n if (credentials) {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, credentials.access_token)\n this._jwtPayload = decodeToken(credentials.access_token)\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, this._jwtPayload)\n this._state = true\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n if (isFromOtherInstance === false) {\n this.storeCredentials(credentials)\n }\n } else {\n this.emit(AuthenticatorEvents.ACCESS_TOKEN, undefined)\n this._jwtPayload = undefined\n this.emit(AuthenticatorEvents.JWT_PAYLOAD, undefined)\n this._state = false\n this.emit(AuthenticatorEvents.STATE_CHANGE, this._state)\n // Credentials are not removed from the store here as the user\n // might only be stopping the authenticator, not necessarily signin out.\n }\n }\n )\n\n this.isSetup = true\n\n if (credentials) {\n this.logger?.log('Has credentials:', credentials)\n await this._signInWithCredentials(credentials)\n }\n }\n\n /**\n * Destroys the ConnectAuth module.\n * This method is called when the user signs-out.\n *\n * @returns {Promise}\n */\n async destroy(): Promise<void> {\n this.refreshTokenRunnerTimer && clearTimeout(this.refreshTokenRunnerTimer)\n\n await this.emit(INTERNAL_CREDENTIALS, { credentials: undefined, isFromOtherInstance: false })\n\n if (this.unsubscribeListenerAdded) {\n this.unsubscribeListenerAdded()\n }\n if (this.unsubscribeUpdateState) {\n this.unsubscribeUpdateState()\n }\n\n this.isSetup = false\n\n for (const [timer, reject] of this.timers.entries()) {\n clearTimeout(timer)\n reject(new Error('Authenticator is being destroyed. Wait functions are rejected.'))\n }\n this.timers.clear()\n }\n\n /**\n * Waits for the given number of milliseconds before resolving the promise.\n *\n * @param waitMilliseconds\n * @returns {Promise<void>}\n */\n private wait(waitMilliseconds: number): Promise<void> {\n try {\n this.assertIsSetup()\n } catch (err) {\n return Promise.reject(err)\n }\n return new Promise((resolve, reject) => {\n const fn = () => {\n this.timers.delete(timer)\n resolve()\n }\n const timer = setTimeout(fn, waitMilliseconds)\n this.timers.set(timer, reject)\n })\n }\n\n /**\n * Generates the login uri for OAuth authentication.\n * Supports escaux-oauth and SMG providers.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<string>} The authorization URI.\n *\n * The browser should be redirected to this URI.\n */\n async getLoginUrl(redirectUri: string): Promise<string> {\n this.assertIsSetup()\n const loginUrl: string = await this.api.getLoginUrl(redirectUri)\n return loginUrl\n }\n\n /**\n * Sign-in the user. Using the authorization code, an access and refresh token\n * is retrieved from the OAuth server. These are stored in an Credentials object.\n *\n * @param {string} authorizationCode - The autorization code recieved from OAuth\n * once the user has authorized the request.\n *\n * @param {string} redirectUri - The redirect uri.\n *\n * The URL that the OAuth needs to redirect the browser to once\n * the user has authorized the request.\n *\n * @returns {Promise<Credentials>} The user Crendetials\n */\n async signIn(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n this.assertIsSetup()\n try {\n const credentials: Credentials = await this.api.getToken(authorizationCode, redirectUri)\n return await this._signInWithCredentials(credentials)\n } catch (error) {\n const authorizationError = new AuthorizationError(\n 'Failed to sign in with authorization code and redirect uri',\n { cause: error }\n )\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * Signs the user out.\n *\n * @returns {Promise<void>}\n */\n async signOut(remote?: boolean): Promise<void> {\n this.assertIsSetup()\n await this.secureStorage.deleteItem(STORE_CREDENTIALS_KEY)\n if (this.removeCredentialStorageUpdates) {\n this.removeCredentialStorageUpdates()\n this.removeCredentialStorageUpdates = undefined\n }\n\n const credentials = this.credentials\n\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: undefined,\n isFromOtherInstance: false,\n })\n\n try {\n if (credentials && remote !== false) {\n const { refresh_token, access_token } = credentials\n await this.api.logout(refresh_token, access_token)\n } else {\n this.logger?.log('No credentials were available. No action was executed on logout.')\n }\n } catch (error) {\n const authorizationError = new AuthorizationError('Failed to sign out the user', {\n cause: error,\n })\n this.emit(AuthenticatorEvents.ERROR, authorizationError)\n this.logger?.error(authorizationError)\n throw authorizationError\n }\n }\n\n /**\n * On wake from sleep, we sign-in with the credentials to force the renewal of the credentials\n * if they expired during the sleep period.\n */\n public async sanityCheck(): Promise<void> {\n this.assertIsSetup()\n if (this._credentials) {\n try {\n await this._signInWithCredentials(this._credentials)\n } catch (error) {\n this.logger?.error('Failed to sign with credentials after sleep', error)\n }\n } else {\n this.logger?.info('No credentials available')\n }\n }\n\n /**\n * Indicates if there are valid credentials.\n *\n * Absent credentials or credentials which have expired are considered not valid.\n */\n public isTokenValid(): boolean {\n if (!this.credentials) {\n return false\n }\n return !this.credentials.isExpired()\n }\n\n public async signInWithCredentials(credentials: Credentials): Promise<Credentials> {\n this.assertIsSetup()\n return this._signInWithCredentials(credentials)\n }\n\n /**\n *\n * @param credentials\n * @returns {Promise<Credentials>}\n */\n private async _signInWithCredentials(\n credentials: Credentials,\n isFromOtherInstance: boolean = false\n ): Promise<Credentials> {\n this.logger?.log('signInWithCredentials')\n if (!credentials) {\n throw new Error('Invalid argument, credentials cannot be null or undefined.')\n }\n\n if (credentials?.isExpired()) {\n this._credentials = credentials\n await this.refreshTokenWithRetry()\n // _setupRefreshTokenRunner is setup in the refreshToken function\n } else {\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials,\n isFromOtherInstance,\n })\n this._setupRefreshTokenRunner()\n }\n\n if (!this._credentials) {\n throw new Error('Failed to authenticate')\n }\n\n return this._credentials\n }\n\n /**\n * Sets up a timeout which will automatically refresh the token.\n *\n * The timeout is calculated based on the value of the `expires_at` property of\n * the `Credentials`, the refresh is always scheduled at 80% of the token life-time.\n *\n * When there are multiple ConnectMe instances the refresh timeout can vary\n * up to 60 seconds.\n *\n * A token will never be refreshed before at least 60 seconds.\n *\n */\n private _setupRefreshTokenRunner(): void {\n clearTimeout(this.refreshTokenRunnerTimer)\n if (!this.credentials) {\n throw new Error('Unable to start refresh token runner without credentials')\n }\n const refreshIn: number = new Date(this.credentials.expires_at).getTime() - new Date().getTime()\n const refreshTimeout: number =\n this.refreshSeparationMilliseconds + Math.max(10_000, refreshIn - 10_000)\n this.logger?.info(\n `Setting timer to refresh token in ${Math.round(refreshTimeout / 1000)} seconds ` +\n `at ${new Date(new Date().getTime() + refreshTimeout).toTimeString()}`\n )\n this.refreshTokenRunnerTimer = setTimeout(async () => {\n try {\n await this.refreshToken()\n } catch (error) {\n const refreshTokenError = new RefreshTokenError(\n 'Refresh runner failed to refresh token with existing credentials',\n { cause: error }\n )\n this.emit(AuthenticatorEvents.ERROR, refreshTokenError)\n this.logger?.error(refreshTokenError)\n }\n }, refreshTimeout)\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method ensures that no parallel requests to refreshToken are done.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n async refreshToken(): Promise<Credentials> {\n this.assertIsSetup()\n if (this.refreshTokenPromise) {\n this.logger?.info('Refresh token already in progress: returning existing promise.')\n return await this.refreshTokenPromise\n }\n try {\n this.refreshTokenPromise = this._refreshToken()\n return await this.refreshTokenPromise\n } finally {\n this.refreshTokenPromise = undefined\n }\n }\n\n /**\n * Attempts the refresh the credentials.\n *\n * On failure it will throw an exception.\n * This method might end up signing the user out in case the refresh token are invalid.\n * It will not sign you out in case of network issues.\n *\n * @returns\n */\n async refreshTokenWithRetry(): Promise<Credentials> {\n this.assertIsSetup()\n const MAX_DEPTH = 7\n const MAX_TIMEOUT = 30 * 1000\n for (let depth = 0; depth < MAX_DEPTH; depth++) {\n try {\n return await this.refreshToken()\n } catch (err) {\n if (depth + 1 >= MAX_DEPTH) {\n throw err\n }\n if (err instanceof TokenNetworkError) {\n await this.wait(Math.min(2 ** depth * 1000, MAX_TIMEOUT))\n } else {\n throw err\n }\n }\n }\n return await this.refreshToken()\n }\n\n /**\n * Generate a new `access_token` and `refresh_token` using the existing `refresh_token`.\n *\n * This method should only be called by `refreshToken`.\n *\n * Use `refreshToken` method if you need to refresh the token.\n *\n * @returns {Promise<Credentials>} The new `Credentials` object.\n */\n private async _refreshToken(): Promise<Credentials> {\n this.logger?.info('Starting access token refresh')\n try {\n if (!this.credentials) {\n throw new Error('Failed to refresh token. No credentials available.')\n }\n const { refresh_token, access_token } = this.credentials\n const credentials = await this.api.refreshToken(refresh_token, access_token)\n this.logger?.info('Access token refreshed successfully')\n await this.emit(INTERNAL_CREDENTIALS, {\n credentials: credentials,\n isFromOtherInstance: false,\n })\n this._setupRefreshTokenRunner()\n return credentials\n } catch (error) {\n this.logger?.error('Failed to refresh token', error)\n if (error instanceof InvalidClientError) {\n if (typeof location !== 'undefined') {\n location.reload()\n } else {\n this.logger?.warn('Location reload not supported')\n throw error\n }\n }\n if (error instanceof RefreshTokenError) {\n if (this.delegateSignOutOnRefreshFailure) {\n await this.delegateSignOutOnRefreshFailure()\n } else {\n await this.signOut(false)\n }\n }\n throw error\n }\n }\n\n /**\n * Stores the credentials in secureStorage.\n *\n * @param {Credentials} credentials - The credentials to store in the secure storage.\n */\n private async storeCredentials(credentials: Credentials): Promise<void> {\n try {\n await this.secureStorage.setItem(STORE_CREDENTIALS_KEY, JSON.stringify(credentials))\n } catch (error: any) {\n this.logger?.error('Failed to store credentials in storage', error)\n }\n }\n\n private assertIsSetup() {\n if (!this.isSetup) {\n throw new Error('Authenticator needs to be setup before it can be used.')\n }\n }\n}\n\nexport default Authenticator\n","import { Credentials } from '@dstny/scp-credentials'\nimport axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\n\nexport abstract class AbstractAuthenticationApi {\n protected axiosInstance: AxiosInstance\n\n constructor(baseURL: string) {\n const config: AxiosRequestConfig = {\n baseURL,\n timeout: 50000,\n }\n this.axiosInstance = axios.create(config)\n }\n\n /**\n * Given a redirectUri it calculates the URL where the browser needs to be\n * redirected in other to authenticate\n *\n * @param {string} redirectUri\n * @returns {string} login url\n */\n abstract getLoginUrl(redirectUri: string): Promise<string>\n\n /**\n * Given the authorizationCode and the redirectUri this method will provide\n * credentials containing an access and refresh token\n *\n * @param {string} authorizationCode\n * @param {string} redirectUri\n * @returns {Promise<Credentials>}\n */\n abstract getToken(authorizationCode: string, redirectUri: string): Promise<Credentials>\n\n /**\n * Given a refresh token this method will provide a new set of credentials\n * containing an access token and a refresh token\n *\n * @param {string} refreshToken\n * @returns {Promise<Credentials>}\n */\n abstract refreshToken(refreshToken: string, accessToken: string): Promise<Credentials>\n\n /**\n * Given a access and refresh token, this method will logout the user from\n * the IAM\n *\n * @param {string} accessToken\n * @param {string} refreshToken\n * @returns {Promise<void>}\n */\n abstract logout(accessToken?: string, refreshToken?: string): Promise<void>\n}\n","/* eslint-disable no-async-promise-executor */\nimport { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport axios from 'axios'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetTokenResponse = {\n access_token: string\n refresh_token: string\n expires_in: number\n}\n\nexport class OAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly scope: string\n public readonly authorizationRoute: string\n\n private readonly baseURL: string\n\n constructor(baseURL: string, clientId: string, authorizationRoute: string, scope: string) {\n super(baseURL)\n this.baseURL = baseURL\n this.clientId = clientId\n this.authorizationRoute = authorizationRoute\n this.scope = scope\n }\n\n async getLoginUrl(redirectUri: string) {\n this.axiosInstance.getUri()\n return (\n `${this.baseURL}${this.authorizationRoute}` +\n `?client_id=${encodeURIComponent(this.clientId)}` +\n '&response_type=code' +\n `&redirect_uri=${encodeURIComponent(redirectUri)}` +\n (this.scope ? `&scope=${encodeURIComponent(this.scope)}` : '')\n )\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n code: authorizationCode,\n grant_type: 'authorization_code',\n redirect_uri: redirectUri,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async loginWithUsernamePassword(username: string, password: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'password',\n username,\n password,\n })\n )\n return new Credentials(data.access_token, data.refresh_token, data.expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const response = await this.axiosInstance.post<GetTokenResponse>(\n '/token',\n new URLSearchParams({\n client_id: this.clientId,\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n })\n )\n return new Credentials(\n response.data.access_token,\n response.data.refresh_token,\n response.data.expires_in\n )\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'unauthorized_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(_redirectUri?: string): Promise<void> {\n await this.axiosInstance.post('/logout', null, { withCredentials: true })\n }\n}\n","import { Credentials } from '@dstny/scp-credentials'\nimport { AbstractAuthenticationApi } from './AbstractAuthenticationApi'\nimport RefreshTokenError from '../errors/RefreshTokenError'\nimport TokenNetworkError from '../errors/TokenNetworkError'\nimport axios from 'axios'\nimport { decodeToken } from '../utils/jwt'\nimport InvalidClientError from '../errors/InvalidClientError'\n\ntype GetLoginUrlResponse = {\n loginUrl: string\n}\n\ntype GetTokenResponse = {\n refreshToken: string\n accessToken: string\n message: string\n status: string\n}\n\nexport class SmgAuthApi extends AbstractAuthenticationApi {\n public readonly clientId: string\n public readonly realm: string\n\n constructor(baseURL: string, realm: string, clientId: string) {\n super(baseURL)\n this.clientId = clientId\n this.realm = realm\n }\n\n async getLoginUrl(redirectUri: string) {\n const { data } = await this.axiosInstance.get<GetLoginUrlResponse>(\n `/login/getloginurl/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`\n )\n\n const baseUrl = new URL(data.loginUrl)\n // The redirect_uri provided by the SMG is inacurate, this needs to be rewritten with the actual\n // redirect uri.\n baseUrl.searchParams.set('redirect_uri', redirectUri)\n // The authentication pathname of the SMG cannot be trusted to be configured correctly.\n // Duplicate '/' characters in the authentication URL causes the authentication\n // prompt to be displayed twice. Once when coven attempts to obtain a token, and\n // again when connect me attempts to obtain a token.\n // vv\n // example: https://keycloak.development.aws.d4sp.com//auth/realms/syslab1/protocol/openid-connect/auth\n baseUrl.pathname = baseUrl.pathname.replace(/\\/\\/+/g, '/')\n\n return baseUrl.toString()\n }\n\n async getToken(authorizationCode: string, redirectUri: string): Promise<Credentials> {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/getaccesstoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n code: authorizationCode,\n redirectUri: redirectUri,\n }\n )\n const { refreshToken, accessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(accessToken)\n const expires_in = exp - iat\n const expires_at = new Date()\n expires_at.setSeconds(expires_at.getSeconds() + expires_in)\n return new Credentials(accessToken, refreshToken, expires_in)\n }\n\n async refreshToken(refreshToken: string, accessToken: string): Promise<Credentials> {\n try {\n const { data } = await this.axiosInstance.post<GetTokenResponse>(\n `/login/refreshtoken/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n const { refreshToken: newRefreshToken, accessToken: newAccessToken } = data\n\n const { iat = 0, exp = 0 } = decodeToken(newAccessToken)\n const expires_in = exp - iat\n return new Credentials(newAccessToken, newRefreshToken, expires_in)\n } catch (error) {\n if (axios.isAxiosError(error)) {\n if (error.message === 'Network Error') {\n throw new TokenNetworkError()\n }\n const statusCode = error.response?.status\n if (statusCode === 401 && error.response?.data?.error === 'invalid_client') {\n throw new InvalidClientError()\n }\n if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {\n throw new RefreshTokenError()\n }\n }\n throw error\n }\n }\n\n async logout(refreshToken: string, accessToken: string): Promise<void> {\n await this.axiosInstance.post(\n `/login/logout/realm/${encodeURIComponent(this.realm)}/client/${encodeURIComponent(\n this.clientId\n )}`,\n {\n jwt: accessToken,\n refreshToken: refreshToken,\n }\n )\n }\n}\n\nexport default SmgAuthApi\n","import Authenticator from './Authenticator'\n\nexport * from './types'\nexport * from './events'\n\nexport * from './api/AbstractAuthenticationApi'\nexport * from './api/OAuthApi'\nexport * from './api/SmgAuthApi'\n\nexport default Authenticator\n"],"mappings":";AAAO,IAAM,SAAS,oBAAI,QAAQ;AAC3B,IAAM,YAAY,oBAAI,QAAQ;AAC9B,IAAM,eAAe,oBAAI,QAAQ;;;ACAxC,IAAM,cAAc,OAAO,aAAa;AACxC,IAAM,kBAAkB,QAAQ,QAAQ;AAGxC,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,kBAAkB,OAAO,iBAAiB;AAEhD,IAAI,oBAAoB;AACxB,IAAI,uBAAuB;AAE3B,IAAM,iBAAiB,SAAO,OAAO,QAAQ,YAAY,OAAO,QAAQ,YAAY,OAAO,QAAQ;AAEnG,SAAS,gBAAgB,WAAW;AACnC,MAAI,CAAC,eAAe,SAAS,GAAG;AAC/B,UAAM,IAAI,UAAU,iDAAiD;AAAA,EACtE;AACD;AAEA,SAAS,eAAe,UAAU;AACjC,MAAI,OAAO,aAAa,YAAY;AACnC,UAAM,IAAI,UAAU,6BAA6B;AAAA,EAClD;AACD;AAEA,SAAS,aAAa,UAAU,WAAW;AAC1C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,CAAC,OAAO,IAAI,SAAS,GAAG;AAC3B;AAAA,EACD;AAEA,SAAO,OAAO,IAAI,SAAS;AAC5B;AAEA,SAAS,kBAAkB,UAAU,WAAW;AAC/C,QAAM,MAAM,eAAe,SAAS,IAAI,YAAY;AACpD,QAAM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OAAO,aAAa,KAAK;AAC3E,gBAAM,IAAI,0BAAkB;AAAA,QAC9B;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,cAAsB,aAAoC;AACrE,UAAM,KAAK,cAAc;AAAA,MACvB,uBAAuB,mBAAmB,KAAK,KAAK,CAAC,WAAW;AAAA,QAC9D,KAAK;AAAA,MACP,CAAC;AAAA,MACD;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACzGA,IAAO,cAAQ;","names":["eventName","AuthenticatorEvents","credentials","axios","axios","axios","axios"]}
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dstny/scp-authenticator",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
8
8
|
"files": [
|
|
9
|
-
"dist"
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md"
|
|
10
11
|
],
|
|
11
12
|
"scripts": {
|
|
12
13
|
"start": "tsup --watch",
|