@faybl/client 4.0.0 → 4.1.0
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 +24 -30
- package/package.json +1 -1
- package/src/auth.js +2 -2
- package/src/browser.js +4 -0
- package/src/channel.js +2 -2
- package/src/client.js +7 -3
- package/src/conf.js +2 -2
- package/src/fetch.js +44 -23
- package/src/index.js +4 -0
- package/src/mqtt.js +12 -6
- package/src/mqttCredentials.js +17 -20
- package/src/mqttUtils.js +1 -1
- package/src/oidcHandler.js +15 -4
- package/src/session.js +38 -0
package/README.md
CHANGED
|
@@ -19,14 +19,15 @@ const unsubscribe = client.channel.subscribe(ovens[0].channels.temperature, ({ d
|
|
|
19
19
|
|
|
20
20
|
Resolves with a client once its MQTT connection is set up; the connection itself completes in the
|
|
21
21
|
background, which [`connection`](#connection) follows. Rejects when the options name neither a
|
|
22
|
-
valid tenant nor every endpoint,
|
|
22
|
+
valid tenant nor every endpoint, when `onError` is not a function, or when the MQTT credentials
|
|
23
|
+
cannot be fetched.
|
|
23
24
|
|
|
24
25
|
| Option | Meaning |
|
|
25
26
|
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
|
26
27
|
| `tenantUrl` | Host name of the tenant, such as `atenant.faybl.online`, without scheme or path. Every endpoint defaults to a URL built from it. |
|
|
27
28
|
| `confUrl`, `dataHistoryUrl`, `authenticatorUrl`, `mqttUrl` | Override one endpoint. Without a `tenantUrl`, all of them are required (`mqttUrl` only when MQTT is on). |
|
|
28
29
|
| `noMqtt` | Do not connect to MQTT. The bus-facing methods then throw `MQTT is disabled`, and datasets do not load. |
|
|
29
|
-
| `noAuth` | Connect to MQTT without credentials.
|
|
30
|
+
| `noAuth` | Connect to MQTT without credentials. Without it the client never connects anonymously. |
|
|
30
31
|
| `onError(error, { source, topic })` | Receives what goes wrong after `createClient` has resolved. See [Errors](#errors). |
|
|
31
32
|
| `authConfig` (Node) | `{ issuerUrl, clientId, clientSecret }` authenticates with the OIDC client credentials grant. With only `clientId`, see below. |
|
|
32
33
|
| `useWebsocket` (Node) | Connect to MQTT over WebSocket instead of MQTTS. |
|
|
@@ -36,9 +37,18 @@ Authentication:
|
|
|
36
37
|
- With an `issuerUrl`, every HTTP request carries the client's access token, and the MQTT
|
|
37
38
|
connection uses the client id and the token as username and password.
|
|
38
39
|
- Otherwise HTTP requests go with the browser's cookies, and MQTT credentials come from the
|
|
39
|
-
authenticator, as the session's identity, or as `authConfig.clientId` when it is given.
|
|
40
|
-
an identity the MQTT connection is anonymous.
|
|
40
|
+
authenticator, as the session's identity, or as `authConfig.clientId` when it is given.
|
|
41
41
|
- Every reconnect fetches fresh credentials, so an expired token does not keep the client out.
|
|
42
|
+
- A service that answers 401 to a client credentials token gets the request once more with a new
|
|
43
|
+
token.
|
|
44
|
+
|
|
45
|
+
Every request asks for JSON, so the login proxy answers an expired browser session with 401
|
|
46
|
+
instead of a redirect to the login page. The client then reports `session` to `onError`, once,
|
|
47
|
+
tells [`session`](#session) subscribers, and holds off MQTT reconnects until credentials can be
|
|
48
|
+
fetched again. Sending the user to the
|
|
49
|
+
login is the app's part, for instance with a top-level navigation to
|
|
50
|
+
`/oauth2/start?rd=<the current URL>`, which comes straight back while the identity provider still
|
|
51
|
+
has a session.
|
|
42
52
|
|
|
43
53
|
## Errors
|
|
44
54
|
|
|
@@ -49,6 +59,7 @@ involved:
|
|
|
49
59
|
| `source` | What failed |
|
|
50
60
|
| ------------- | ----------------------------------------------------------------------------------- |
|
|
51
61
|
| `mqtt` | The MQTT connection: a refused connection, a keepalive timeout, a missing CONNACK. |
|
|
62
|
+
| `session` | A request was refused with 401: the login session is gone. Once until one succeeds. |
|
|
52
63
|
| `credentials` | Fetching MQTT credentials. The client connects with what it has and tries again. |
|
|
53
64
|
| `message` | A message that is not JSON. An empty message clears a retained one and is not this. |
|
|
54
65
|
| `subscriber` | A subscription's callback threw or rejected. The other subscribers still get it. |
|
|
@@ -140,6 +151,13 @@ across provider restarts. A call made while no provider is connected is not kept
|
|
|
140
151
|
- `connection.subscribe(callback)` calls back with `{ connected }` at once, and again whenever the
|
|
141
152
|
MQTT connection comes up or goes down. Returns the function that undoes it.
|
|
142
153
|
|
|
154
|
+
## `session`
|
|
155
|
+
|
|
156
|
+
- `session.subscribe(callback)` calls back with `{ expired }` at once, and again whenever it
|
|
157
|
+
changes: `true` once a request is refused with 401, `false` again once one succeeds. Returns the
|
|
158
|
+
function that undoes it. This is what an app shows a "logged out" notice from; `onError` gets the
|
|
159
|
+
same expiry as `session`.
|
|
160
|
+
|
|
143
161
|
## `auth`
|
|
144
162
|
|
|
145
163
|
- `auth.getUserInfo()` resolves with `{ id, firstName, lastName, email }` of whoever the request
|
|
@@ -155,7 +173,8 @@ subscription may be a filter with wildcards.
|
|
|
155
173
|
MQTT.js's, such as `{ qos, retain }`.
|
|
156
174
|
- `mqttClient.subscribe(topic, callback, { qos })` returns the function that undoes it. The
|
|
157
175
|
callback gets `{ topic, data }`, with `data` parsed from JSON.
|
|
158
|
-
- `mqttClient.subscribeWithAck(topic, callback, { qos })` returns `{ ready, unsubscribe }
|
|
176
|
+
- `mqttClient.subscribeWithAck(topic, callback, { qos })` returns `{ ready, unsubscribe }`; `ready`
|
|
177
|
+
resolves once the broker has granted the QoS asked for, 0 by default.
|
|
159
178
|
- `mqttClient.unsubscribe(topic, callback)`. Without a callback it removes every callback on the
|
|
160
179
|
topic.
|
|
161
180
|
|
|
@@ -217,31 +236,6 @@ machine of your own. It is in `Init` while it loads, then `Idle`, or `Error` wit
|
|
|
217
236
|
`datasetLoaded(actorRef)` resolves with the records once it is `Idle`, and rejects with the error
|
|
218
237
|
when it ends in `Error`.
|
|
219
238
|
|
|
220
|
-
## Releasing
|
|
221
|
-
|
|
222
|
-
```
|
|
223
|
-
npm version patch # or minor, major, or an exact version
|
|
224
|
-
npm version prerelease --preid=rc
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
`.npmrc` sets `tag-version-prefix=version/`, so the tag is `version/4.0.0`. `preversion` runs
|
|
228
|
-
`npm run verify`, and `postversion` says what to do next; nothing is pushed or published on its
|
|
229
|
-
own. Then either publish from here:
|
|
230
|
-
|
|
231
|
-
```
|
|
232
|
-
npm run release
|
|
233
|
-
```
|
|
234
|
-
|
|
235
|
-
or push the tag, and CI publishes it through npm trusted publishing:
|
|
236
|
-
|
|
237
|
-
```
|
|
238
|
-
git push --follow-tags
|
|
239
|
-
```
|
|
240
|
-
|
|
241
|
-
`npm run release` refuses to upload unless the working tree is clean, HEAD carries the tag of the
|
|
242
|
-
current version and there is an npm login or a CI token. A version already on the registry is
|
|
243
|
-
skipped, so publishing locally and then pushing the tag is a no-op in CI.
|
|
244
|
-
|
|
245
239
|
## License
|
|
246
240
|
|
|
247
241
|
MIT, see [LICENSE](LICENSE).
|
package/package.json
CHANGED
package/src/auth.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { fetchCheckedJson } from './fetch.js';
|
|
2
2
|
|
|
3
|
-
export const getAuthApi = (authenticatorUrl,
|
|
3
|
+
export const getAuthApi = (authenticatorUrl, http) => {
|
|
4
4
|
const getUserInfo = async () => {
|
|
5
5
|
return fetchCheckedJson(
|
|
6
6
|
`${authenticatorUrl}/getUserInfo`,
|
|
7
7
|
{
|
|
8
8
|
method: 'POST',
|
|
9
9
|
},
|
|
10
|
-
|
|
10
|
+
http,
|
|
11
11
|
);
|
|
12
12
|
};
|
|
13
13
|
|
package/src/browser.js
CHANGED
|
@@ -2,6 +2,7 @@ import { clientOptionsError } from './clientOptions.js';
|
|
|
2
2
|
import { createClient as createBrowserClient } from './client.js';
|
|
3
3
|
import { createMqttClient } from './mqtt.js';
|
|
4
4
|
import { createReporter } from './report.js';
|
|
5
|
+
import { createSession } from './session.js';
|
|
5
6
|
|
|
6
7
|
export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
|
|
7
8
|
|
|
@@ -11,6 +12,7 @@ export const createClient = async (options = {}) => {
|
|
|
11
12
|
const { tenantUrl, confUrl, dataHistoryUrl, mqttUrl, authenticatorUrl, noMqtt, noAuth, onError } =
|
|
12
13
|
options;
|
|
13
14
|
const report = createReporter(onError);
|
|
15
|
+
const session = createSession(report);
|
|
14
16
|
|
|
15
17
|
const mqttClient = noMqtt
|
|
16
18
|
? undefined
|
|
@@ -19,6 +21,7 @@ export const createClient = async (options = {}) => {
|
|
|
19
21
|
authenticatorUrl: authenticatorUrl || `https://${tenantUrl}/authenticator`,
|
|
20
22
|
noAuth,
|
|
21
23
|
report,
|
|
24
|
+
session,
|
|
22
25
|
});
|
|
23
26
|
|
|
24
27
|
return createBrowserClient({
|
|
@@ -26,6 +29,7 @@ export const createClient = async (options = {}) => {
|
|
|
26
29
|
confUrl: confUrl || `https://${tenantUrl}/conf`,
|
|
27
30
|
dataHistoryUrl: dataHistoryUrl || `https://${tenantUrl}/data-history`,
|
|
28
31
|
mqttClient,
|
|
32
|
+
session,
|
|
29
33
|
report,
|
|
30
34
|
});
|
|
31
35
|
};
|
package/src/channel.js
CHANGED
|
@@ -10,7 +10,7 @@ const createPubMsg = (pl, other = {}) => ({
|
|
|
10
10
|
...other,
|
|
11
11
|
});
|
|
12
12
|
|
|
13
|
-
export const getChannelApi = (dataHistoryUrl, mqttClient,
|
|
13
|
+
export const getChannelApi = (dataHistoryUrl, mqttClient, http) => {
|
|
14
14
|
const preCallback = ({ topic, data }) => {
|
|
15
15
|
return { rid: topic.replace(`${baseTopic}/`, ''), data };
|
|
16
16
|
};
|
|
@@ -29,7 +29,7 @@ export const getChannelApi = (dataHistoryUrl, mqttClient, oidcHandler) => {
|
|
|
29
29
|
body: JSON.stringify(args),
|
|
30
30
|
method: 'POST',
|
|
31
31
|
},
|
|
32
|
-
|
|
32
|
+
http,
|
|
33
33
|
);
|
|
34
34
|
};
|
|
35
35
|
|
package/src/client.js
CHANGED
|
@@ -11,11 +11,14 @@ export const createClient = ({
|
|
|
11
11
|
dataHistoryUrl,
|
|
12
12
|
mqttClient,
|
|
13
13
|
oidcHandler,
|
|
14
|
+
session,
|
|
14
15
|
report,
|
|
15
16
|
}) => {
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
const
|
|
17
|
+
// What every HTTP call is sent with: the token for a service, and where a refused login goes.
|
|
18
|
+
const http = { oidcHandler, session };
|
|
19
|
+
const auth = getAuthApi(authenticatorUrl, http);
|
|
20
|
+
const channel = getChannelApi(dataHistoryUrl, mqttClient, http);
|
|
21
|
+
const conf = getConfApi(confUrl, mqttClient, http);
|
|
19
22
|
const procedure = getProcedureApi(mqttClient, report);
|
|
20
23
|
const presence = getPresenceApi(mqttClient);
|
|
21
24
|
const connection = getConnectionApi(mqttClient);
|
|
@@ -29,6 +32,7 @@ export const createClient = ({
|
|
|
29
32
|
procedure,
|
|
30
33
|
presence,
|
|
31
34
|
connection,
|
|
35
|
+
session: { subscribe: session.subscribe },
|
|
32
36
|
mqttClient,
|
|
33
37
|
close,
|
|
34
38
|
};
|
package/src/conf.js
CHANGED
|
@@ -37,7 +37,7 @@ const ridPart = topicPart((rid) => assertTopicSegment('rid', rid));
|
|
|
37
37
|
const getConfTopic = (entity, operation, rid) =>
|
|
38
38
|
`conf/${entityPart(entity)}/${operationPart(operation)}/${ridPart(rid)}`;
|
|
39
39
|
|
|
40
|
-
export const getConfApi = (confUrl, mqttClient,
|
|
40
|
+
export const getConfApi = (confUrl, mqttClient, http) => {
|
|
41
41
|
const crudEntity = (entityClass, operation) => (args) => {
|
|
42
42
|
return fetchCheckedJson(
|
|
43
43
|
`${confUrl}/${entityClass}/${operation}`,
|
|
@@ -45,7 +45,7 @@ export const getConfApi = (confUrl, mqttClient, oidcHandler) => {
|
|
|
45
45
|
body: JSON.stringify(args),
|
|
46
46
|
method: 'POST',
|
|
47
47
|
},
|
|
48
|
-
|
|
48
|
+
http,
|
|
49
49
|
);
|
|
50
50
|
};
|
|
51
51
|
|
package/src/fetch.js
CHANGED
|
@@ -2,31 +2,52 @@ import * as R from 'ramda';
|
|
|
2
2
|
import { biAsync } from 'tri-fp';
|
|
3
3
|
|
|
4
4
|
// Every request carries a JSON body, so the content type is set here rather than by each caller.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
5
|
+
// Asking for JSON makes the login proxy answer an expired session with 401 instead of a redirect
|
|
6
|
+
// to the login page, which fetch would follow into a cross-origin failure with no status.
|
|
7
|
+
// `*/*` keeps any service from refusing the request with 406.
|
|
8
|
+
const JSON_HEADERS = { 'Content-Type': 'application/json', Accept: 'application/json, */*' };
|
|
9
|
+
|
|
10
|
+
const UNAUTHORIZED = 401;
|
|
11
|
+
|
|
12
|
+
const withToken = async (options, oidcHandler) =>
|
|
13
|
+
oidcHandler
|
|
14
|
+
? R.assocPath(['headers', 'Authorization'])(`Bearer ${await oidcHandler.getToken()}`)(options)
|
|
15
|
+
: options;
|
|
16
|
+
|
|
17
|
+
const requestFailure = async (response) => {
|
|
18
|
+
const { status, statusText } = response;
|
|
19
|
+
const [err, json] = await biAsync(response.json.bind(response))();
|
|
20
|
+
return Object.assign(Error(`Request failed: ${status} ${statusText}`), {
|
|
21
|
+
response: { status, statusText, body: err ? {} : json },
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Sends a JSON request and resolves with the JSON response. A 401 with a client credentials token
|
|
27
|
+
* gets one more try with a fresh token, since the cached one may have been revoked or rotated; a
|
|
28
|
+
* 401 that stands is reported to `session` and rejects like any other failure.
|
|
29
|
+
*/
|
|
30
|
+
export const fetchCheckedJson = async (url, options, { oidcHandler, session } = {}) => {
|
|
31
|
+
// Cookies go along so a browser client is authenticated by its login session.
|
|
32
|
+
const jsonOptions = {
|
|
33
|
+
...R.mergeDeepRight({ headers: JSON_HEADERS }, options),
|
|
18
34
|
credentials: 'include',
|
|
19
35
|
};
|
|
36
|
+
const send = async () => globalThis.fetch(url, await withToken(jsonOptions, oidcHandler));
|
|
37
|
+
|
|
38
|
+
const retryWithFreshToken = async (first) => {
|
|
39
|
+
if (first.status !== UNAUTHORIZED || !oidcHandler) return first;
|
|
40
|
+
oidcHandler.invalidateToken();
|
|
41
|
+
return send();
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const response = await retryWithFreshToken(await send());
|
|
20
45
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const body = err ? {} : json;
|
|
26
|
-
const error = Object.assign(Error(`Request failed: ${status} ${statusText}`), {
|
|
27
|
-
response: { status, statusText, body },
|
|
28
|
-
});
|
|
29
|
-
return Promise.reject(error);
|
|
46
|
+
if (!response.ok) {
|
|
47
|
+
const failure = await requestFailure(response);
|
|
48
|
+
if (response.status === UNAUTHORIZED) session?.lost(failure);
|
|
49
|
+
return Promise.reject(failure);
|
|
30
50
|
}
|
|
31
|
-
|
|
51
|
+
session?.confirmed();
|
|
52
|
+
return response.json();
|
|
32
53
|
};
|
package/src/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { createClient as createServerClient } from './client.js';
|
|
|
5
5
|
import { createMqttClient } from './mqtt.js';
|
|
6
6
|
import { createOidcHandler } from './oidcHandler.js';
|
|
7
7
|
import { createReporter } from './report.js';
|
|
8
|
+
import { createSession } from './session.js';
|
|
8
9
|
|
|
9
10
|
export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
|
|
10
11
|
|
|
@@ -28,6 +29,7 @@ export const createClient = async (options = {}) => {
|
|
|
28
29
|
} = options;
|
|
29
30
|
|
|
30
31
|
const report = createReporter(onError);
|
|
32
|
+
const session = createSession(report);
|
|
31
33
|
const oidcHandler = R.prop('issuerUrl')(authConfig) ? createOidcHandler(authConfig) : undefined;
|
|
32
34
|
|
|
33
35
|
const mqttClient = noMqtt
|
|
@@ -39,6 +41,7 @@ export const createClient = async (options = {}) => {
|
|
|
39
41
|
authConfig,
|
|
40
42
|
noAuth,
|
|
41
43
|
report,
|
|
44
|
+
session,
|
|
42
45
|
});
|
|
43
46
|
|
|
44
47
|
return createServerClient({
|
|
@@ -47,6 +50,7 @@ export const createClient = async (options = {}) => {
|
|
|
47
50
|
dataHistoryUrl: dataHistoryUrl || `https://${tenantUrl}/data-history`,
|
|
48
51
|
mqttClient,
|
|
49
52
|
oidcHandler,
|
|
53
|
+
session,
|
|
50
54
|
report,
|
|
51
55
|
});
|
|
52
56
|
};
|
package/src/mqtt.js
CHANGED
|
@@ -17,9 +17,11 @@ export const baseMqttOptions = {
|
|
|
17
17
|
* connection has expired by then. MQTT.js reconnects by calling `client.connect` from a timer
|
|
18
18
|
* without waiting for it, and has no asynchronous hook for credentials, so `connect` is replaced.
|
|
19
19
|
*
|
|
20
|
-
* The replacement never rejects
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* The replacement never rejects. A refused login, a 401, means the session is gone: it has been
|
|
21
|
+
* reported to `session`, and no connection is attempted until a later reconnect finds credentials
|
|
22
|
+
* again. Any other failure is reported and the connection is attempted with the credentials it had,
|
|
23
|
+
* so the broker decides. A reconnect that arrives while credentials are still being fetched is
|
|
24
|
+
* skipped.
|
|
23
25
|
*/
|
|
24
26
|
const refreshCredentialsOnConnect = (client, credentialsSource) => {
|
|
25
27
|
const nativeConnect = client.connect.bind(client);
|
|
@@ -27,13 +29,17 @@ const refreshCredentialsOnConnect = (client, credentialsSource) => {
|
|
|
27
29
|
let fetching = false;
|
|
28
30
|
|
|
29
31
|
/* eslint-disable functional/immutable-data -- The MQTT.js client is a mutable platform object; its reconnect path calls client.connect and reads client.options, so fresh credentials can only reach it by patching those in place. */
|
|
32
|
+
// Resolves with whether to connect.
|
|
30
33
|
const applyCredentials = async () => {
|
|
31
34
|
try {
|
|
32
35
|
const { username, password } = await getMqttCredentials(credentialsSource);
|
|
33
36
|
if (username) client.options.username = username;
|
|
34
37
|
if (password) client.options.password = password;
|
|
38
|
+
return true;
|
|
35
39
|
} catch (error) {
|
|
40
|
+
if (error.response?.status === 401) return false;
|
|
36
41
|
credentialsSource.report(error, { source: 'credentials' });
|
|
42
|
+
return true;
|
|
37
43
|
}
|
|
38
44
|
};
|
|
39
45
|
|
|
@@ -41,11 +47,10 @@ const refreshCredentialsOnConnect = (client, credentialsSource) => {
|
|
|
41
47
|
if (fetching) return client;
|
|
42
48
|
fetching = true;
|
|
43
49
|
try {
|
|
44
|
-
await applyCredentials();
|
|
50
|
+
return (await applyCredentials()) ? nativeConnect(...args) : client;
|
|
45
51
|
} finally {
|
|
46
52
|
fetching = false;
|
|
47
53
|
}
|
|
48
|
-
return nativeConnect(...args);
|
|
49
54
|
};
|
|
50
55
|
/* eslint-enable functional/immutable-data */
|
|
51
56
|
};
|
|
@@ -58,8 +63,9 @@ export const createMqttClient = async ({
|
|
|
58
63
|
noAuth,
|
|
59
64
|
mqttOptions = {},
|
|
60
65
|
report = () => undefined,
|
|
66
|
+
session,
|
|
61
67
|
}) => {
|
|
62
|
-
const credentialsSource = { authenticatorUrl, oidcHandler, authConfig, report };
|
|
68
|
+
const credentialsSource = { authenticatorUrl, oidcHandler, authConfig, report, session };
|
|
63
69
|
const options = {
|
|
64
70
|
...baseMqttOptions,
|
|
65
71
|
...mqttOptions,
|
package/src/mqttCredentials.js
CHANGED
|
@@ -1,34 +1,31 @@
|
|
|
1
1
|
import { fetchCheckedJson } from './fetch.js';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Resolves with the username and password for the MQTT connection, or rejects when there are none
|
|
5
|
+
* to be had. There is no anonymous fallback: a connection without credentials is asked for with
|
|
6
|
+
* `noAuth`, never the result of a failure. A 401 from the authenticator means the login session
|
|
7
|
+
* is gone, and is reported to `session` on the way.
|
|
8
|
+
*/
|
|
3
9
|
export const getMqttCredentials = async ({
|
|
4
10
|
authenticatorUrl,
|
|
5
11
|
oidcHandler,
|
|
6
12
|
authConfig,
|
|
7
|
-
|
|
13
|
+
session,
|
|
8
14
|
}) => {
|
|
9
15
|
if (oidcHandler) {
|
|
10
|
-
// JWT Authentication with Bearer token
|
|
11
16
|
return {
|
|
12
17
|
username: oidcHandler.clientId,
|
|
13
18
|
password: await oidcHandler.getToken(),
|
|
14
19
|
};
|
|
15
20
|
}
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
password: credentials.token,
|
|
27
|
-
};
|
|
28
|
-
} catch (error) {
|
|
29
|
-
// 401 means the authenticator found no identity, and the connection is
|
|
30
|
-
// anonymous by design. Anything else is a failure worth reporting.
|
|
31
|
-
if (error.response?.status !== 401) report(error, { source: 'credentials' });
|
|
32
|
-
return {};
|
|
33
|
-
}
|
|
21
|
+
const id = authConfig?.clientId;
|
|
22
|
+
const credentials = await fetchCheckedJson(
|
|
23
|
+
`${authenticatorUrl}/getMqttCredentials`,
|
|
24
|
+
{ method: 'POST', body: JSON.stringify(id ? { id } : {}) },
|
|
25
|
+
{ session },
|
|
26
|
+
);
|
|
27
|
+
return {
|
|
28
|
+
username: credentials.id,
|
|
29
|
+
password: credentials.token,
|
|
30
|
+
};
|
|
34
31
|
};
|
package/src/mqttUtils.js
CHANGED
|
@@ -85,7 +85,7 @@ export const createMqttHandler = (client, { report = () => undefined } = {}) =>
|
|
|
85
85
|
return () => unsubscribe(topic, callback);
|
|
86
86
|
};
|
|
87
87
|
|
|
88
|
-
const subscribeWithAck = (topic, callback, { qos, preCallback } = {}) => {
|
|
88
|
+
const subscribeWithAck = (topic, callback, { qos = 0, preCallback } = {}) => {
|
|
89
89
|
dispatch({ type: 'add', topic, callback, preCallback });
|
|
90
90
|
const ready = new Promise((resolve, reject) => {
|
|
91
91
|
client.subscribe(topic, { qos }, (error, granted) => {
|
package/src/oidcHandler.js
CHANGED
|
@@ -11,9 +11,10 @@ const createOidcConfig = async ({ issuerUrl, clientId, clientSecret }) => {
|
|
|
11
11
|
let inflight; // prevent concurrent token requests
|
|
12
12
|
/* eslint-enable functional/no-let */
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
// `fresh` skips the cache, for a token the service has just refused.
|
|
15
|
+
const getToken = async ({ fresh = false } = {}) => {
|
|
15
16
|
const now = Date.now();
|
|
16
|
-
if (currentTokens && now < expiresAt) return currentTokens;
|
|
17
|
+
if (!fresh && currentTokens && now < expiresAt) return currentTokens;
|
|
17
18
|
|
|
18
19
|
// Reuse ongoing token request if present
|
|
19
20
|
if (inflight) {
|
|
@@ -45,8 +46,10 @@ const createOidcConfig = async ({ issuerUrl, clientId, clientSecret }) => {
|
|
|
45
46
|
// requests and the MQTT connection. Discovery runs on the first token request,
|
|
46
47
|
// and a failed discovery is retried on the next one.
|
|
47
48
|
export const createOidcHandler = ({ issuerUrl, clientId, clientSecret }) => {
|
|
48
|
-
|
|
49
|
+
/* eslint-disable functional/no-let -- Discovery is shared by every getToken call and must be dropped after a failure so the next call can retry it; a refused token must be replaced on the next request, whichever call makes it. */
|
|
49
50
|
let configPromise;
|
|
51
|
+
let refused = false;
|
|
52
|
+
/* eslint-enable functional/no-let */
|
|
50
53
|
|
|
51
54
|
const loadConfig = async () => {
|
|
52
55
|
const discovery = (configPromise ??= createOidcConfig({ issuerUrl, clientId, clientSecret }));
|
|
@@ -60,12 +63,20 @@ export const createOidcHandler = ({ issuerUrl, clientId, clientSecret }) => {
|
|
|
60
63
|
|
|
61
64
|
const getToken = async () => {
|
|
62
65
|
const config = await loadConfig();
|
|
63
|
-
const
|
|
66
|
+
const fresh = refused;
|
|
67
|
+
refused = false;
|
|
68
|
+
const tokenSet = await config.getToken({ fresh });
|
|
64
69
|
return tokenSet.access_token;
|
|
65
70
|
};
|
|
66
71
|
|
|
72
|
+
// A service answered 401 to the current token, so the next getToken asks for a new one.
|
|
73
|
+
const invalidateToken = () => {
|
|
74
|
+
refused = true;
|
|
75
|
+
};
|
|
76
|
+
|
|
67
77
|
return {
|
|
68
78
|
getToken,
|
|
79
|
+
invalidateToken,
|
|
69
80
|
clientId,
|
|
70
81
|
};
|
|
71
82
|
};
|
package/src/session.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Follows whether the caller's login is still accepted. A request refused with 401 marks the
|
|
3
|
+
* session expired: it is reported to `onError` as `session` once, and subscribers get
|
|
4
|
+
* `{ expired: true }`. The next request that succeeds marks it alive again. However many calls
|
|
5
|
+
* were in flight, one expiry is one report and one change.
|
|
6
|
+
*/
|
|
7
|
+
export const createSession = (report = () => undefined) => {
|
|
8
|
+
/* eslint-disable functional/no-let -- The session's state and its subscribers outlive the independent requests and subscribe calls that change them; each change replaces the value. */
|
|
9
|
+
let expired = false;
|
|
10
|
+
let callbacks = [];
|
|
11
|
+
/* eslint-enable functional/no-let */
|
|
12
|
+
|
|
13
|
+
const notify = () => callbacks.forEach((callback) => callback({ expired }));
|
|
14
|
+
|
|
15
|
+
const lost = (error) => {
|
|
16
|
+
if (expired) return;
|
|
17
|
+
expired = true;
|
|
18
|
+
report(error, { source: 'session' });
|
|
19
|
+
notify();
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const confirmed = () => {
|
|
23
|
+
if (!expired) return;
|
|
24
|
+
expired = false;
|
|
25
|
+
notify();
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// Calls back at once with the current state, and again whenever it changes.
|
|
29
|
+
const subscribe = (callback) => {
|
|
30
|
+
callbacks = [...callbacks, callback];
|
|
31
|
+
callback({ expired });
|
|
32
|
+
return () => {
|
|
33
|
+
callbacks = callbacks.filter((subscribed) => subscribed !== callback);
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
return { lost, confirmed, subscribe };
|
|
38
|
+
};
|