@faybl/client 4.0.1 → 4.1.1
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 +31 -13
- package/package.json +1 -1
- package/src/auth.js +4 -3
- package/src/browser.js +9 -5
- package/src/channel.js +4 -3
- package/src/client.js +7 -3
- package/src/clientOptions.js +11 -8
- package/src/conf.js +4 -3
- package/src/fetch.js +48 -23
- package/src/index.js +9 -5
- package/src/mqtt.js +12 -6
- package/src/mqttCredentials.js +17 -20
- package/src/oidcHandler.js +15 -4
- package/src/session.js +38 -0
package/README.md
CHANGED
|
@@ -19,26 +19,36 @@ 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
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
|
26
|
-
|
|
|
27
|
-
| `
|
|
28
|
-
| `
|
|
29
|
-
| `
|
|
30
|
-
| `
|
|
31
|
-
| `
|
|
32
|
-
| `
|
|
22
|
+
valid tenant nor the endpoints needed to connect, when `onError` is not a function, or when the MQTT credentials
|
|
23
|
+
cannot be fetched.
|
|
24
|
+
|
|
25
|
+
| Option | Meaning |
|
|
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. |
|
|
28
|
+
| `confUrl`, `dataHistoryUrl`, `authenticatorUrl`, `mqttUrl` | Override one endpoint. Without a `tenantUrl`, only `mqttUrl` and, when the authenticator hands out the MQTT credentials, `authenticatorUrl` are required; a call that needs an endpoint left out rejects. |
|
|
29
|
+
| `noMqtt` | Do not connect to MQTT. The bus-facing methods then throw `MQTT is disabled`, and datasets do not load. |
|
|
30
|
+
| `noAuth` | Connect to MQTT without credentials. Without it the client never connects anonymously. |
|
|
31
|
+
| `onError(error, { source, topic })` | Receives what goes wrong after `createClient` has resolved. See [Errors](#errors). |
|
|
32
|
+
| `authConfig` (Node) | `{ issuerUrl, clientId, clientSecret }` authenticates with the OIDC client credentials grant. With only `clientId`, see below. |
|
|
33
|
+
| `useWebsocket` (Node) | Connect to MQTT over WebSocket instead of MQTTS. |
|
|
33
34
|
|
|
34
35
|
Authentication:
|
|
35
36
|
|
|
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
|
package/package.json
CHANGED
package/src/auth.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { fetchCheckedJson } from './fetch.js';
|
|
1
|
+
import { fetchCheckedJson, missingEndpoint } from './fetch.js';
|
|
2
2
|
|
|
3
|
-
export const getAuthApi = (authenticatorUrl,
|
|
3
|
+
export const getAuthApi = (authenticatorUrl, http) => {
|
|
4
4
|
const getUserInfo = async () => {
|
|
5
|
+
if (!authenticatorUrl) return missingEndpoint('authenticatorUrl');
|
|
5
6
|
return fetchCheckedJson(
|
|
6
7
|
`${authenticatorUrl}/getUserInfo`,
|
|
7
8
|
{
|
|
8
9
|
method: 'POST',
|
|
9
10
|
},
|
|
10
|
-
|
|
11
|
+
http,
|
|
11
12
|
);
|
|
12
13
|
};
|
|
13
14
|
|
package/src/browser.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { clientOptionsError } from './clientOptions.js';
|
|
1
|
+
import { clientOptionsError, tenantServiceUrl } 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,21 +12,24 @@ 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
|
|
17
19
|
: await createMqttClient({
|
|
18
20
|
mqttUrl: mqttUrl || `wss://ws.${tenantUrl}`,
|
|
19
|
-
authenticatorUrl: authenticatorUrl ||
|
|
21
|
+
authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
|
|
20
22
|
noAuth,
|
|
21
23
|
report,
|
|
24
|
+
session,
|
|
22
25
|
});
|
|
23
26
|
|
|
24
27
|
return createBrowserClient({
|
|
25
|
-
authenticatorUrl: authenticatorUrl ||
|
|
26
|
-
confUrl: confUrl ||
|
|
27
|
-
dataHistoryUrl: dataHistoryUrl ||
|
|
28
|
+
authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
|
|
29
|
+
confUrl: confUrl || tenantServiceUrl(tenantUrl, '/conf'),
|
|
30
|
+
dataHistoryUrl: dataHistoryUrl || tenantServiceUrl(tenantUrl, '/data-history'),
|
|
28
31
|
mqttClient,
|
|
32
|
+
session,
|
|
29
33
|
report,
|
|
30
34
|
});
|
|
31
35
|
};
|
package/src/channel.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mqttDisabledWarning } from './mqttUtils.js';
|
|
2
2
|
import { assertTopicSegment } from './topicSegment.js';
|
|
3
|
-
import { fetchCheckedJson } from './fetch.js';
|
|
3
|
+
import { fetchCheckedJson, missingEndpoint } from './fetch.js';
|
|
4
4
|
|
|
5
5
|
const baseTopic = 'channel';
|
|
6
6
|
|
|
@@ -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
|
};
|
|
@@ -23,13 +23,14 @@ export const getChannelApi = (dataHistoryUrl, mqttClient, oidcHandler) => {
|
|
|
23
23
|
const publish = (rid, pl, other) => mqttClient.publish(topicFor(rid), createPubMsg(pl, other));
|
|
24
24
|
|
|
25
25
|
const read = (args) => {
|
|
26
|
+
if (!dataHistoryUrl) return missingEndpoint('dataHistoryUrl');
|
|
26
27
|
return fetchCheckedJson(
|
|
27
28
|
`${dataHistoryUrl}/read`,
|
|
28
29
|
{
|
|
29
30
|
body: JSON.stringify(args),
|
|
30
31
|
method: 'POST',
|
|
31
32
|
},
|
|
32
|
-
|
|
33
|
+
http,
|
|
33
34
|
);
|
|
34
35
|
};
|
|
35
36
|
|
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/clientOptions.js
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// scheme or a subdomain, so a scheme or a path in it would produce a broken URL.
|
|
3
3
|
const TENANT_HOST = /^[^\s/:]+(:\d+)?$/;
|
|
4
4
|
|
|
5
|
+
// A service's URL under the tenant, or undefined without one.
|
|
6
|
+
export const tenantServiceUrl = (tenantUrl, path) =>
|
|
7
|
+
tenantUrl === undefined ? undefined : `https://${tenantUrl}${path}`;
|
|
8
|
+
|
|
5
9
|
const tenantUrlError = (tenantUrl) =>
|
|
6
10
|
typeof tenantUrl === 'string' && TENANT_HOST.test(tenantUrl)
|
|
7
11
|
? undefined
|
|
@@ -9,12 +13,11 @@ const tenantUrlError = (tenantUrl) =>
|
|
|
9
13
|
`Invalid tenantUrl ${JSON.stringify(tenantUrl)}: it must be a host name such as 'tenant.faybl.online', without scheme or path`,
|
|
10
14
|
);
|
|
11
15
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
];
|
|
16
|
+
// Only what connecting needs is required up front: the broker, and the authenticator when it hands
|
|
17
|
+
// out the MQTT credentials. Any other endpoint left out fails only the calls that use it, so a
|
|
18
|
+
// service names the endpoints it talks to and no others.
|
|
19
|
+
const requiredEndpoints = ({ noMqtt, noAuth, authConfig }) =>
|
|
20
|
+
noMqtt ? [] : ['mqttUrl', ...(noAuth || authConfig?.issuerUrl ? [] : ['authenticatorUrl'])];
|
|
18
21
|
|
|
19
22
|
const endpointsError = (options) => {
|
|
20
23
|
if (options.tenantUrl !== undefined) return tenantUrlError(options.tenantUrl);
|
|
@@ -30,7 +33,7 @@ const onErrorError = ({ onError }) =>
|
|
|
30
33
|
: Error('Invalid onError: it must be a function');
|
|
31
34
|
|
|
32
35
|
/**
|
|
33
|
-
* Returns the Error createClient rejects with, or undefined when the options name
|
|
34
|
-
*
|
|
36
|
+
* Returns the Error createClient rejects with, or undefined when the options name either a tenant
|
|
37
|
+
* or the endpoints the client needs to connect.
|
|
35
38
|
*/
|
|
36
39
|
export const clientOptionsError = (options) => onErrorError(options) ?? endpointsError(options);
|
package/src/conf.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as R from 'ramda';
|
|
2
2
|
|
|
3
3
|
import { mqttDisabledWarning } from './mqttUtils.js';
|
|
4
|
-
import { fetchCheckedJson } from './fetch.js';
|
|
4
|
+
import { fetchCheckedJson, missingEndpoint } from './fetch.js';
|
|
5
5
|
import { assertTopicSegment, assertTopicSegmentOneOf } from './topicSegment.js';
|
|
6
6
|
|
|
7
7
|
const ENTITIES = [
|
|
@@ -37,15 +37,16 @@ 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
|
+
if (!confUrl) return missingEndpoint('confUrl');
|
|
42
43
|
return fetchCheckedJson(
|
|
43
44
|
`${confUrl}/${entityClass}/${operation}`,
|
|
44
45
|
{
|
|
45
46
|
body: JSON.stringify(args),
|
|
46
47
|
method: 'POST',
|
|
47
48
|
},
|
|
48
|
-
|
|
49
|
+
http,
|
|
49
50
|
);
|
|
50
51
|
};
|
|
51
52
|
|
package/src/fetch.js
CHANGED
|
@@ -2,31 +2,56 @@ 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
|
+
// An endpoint createClient was not given fails the call that needs it, not the whole client.
|
|
13
|
+
export const missingEndpoint = (name) =>
|
|
14
|
+
Promise.reject(Error(`createClient was given no ${name} or tenantUrl, which this call needs`));
|
|
15
|
+
|
|
16
|
+
const withToken = async (options, oidcHandler) =>
|
|
17
|
+
oidcHandler
|
|
18
|
+
? R.assocPath(['headers', 'Authorization'])(`Bearer ${await oidcHandler.getToken()}`)(options)
|
|
19
|
+
: options;
|
|
20
|
+
|
|
21
|
+
const requestFailure = async (response) => {
|
|
22
|
+
const { status, statusText } = response;
|
|
23
|
+
const [err, json] = await biAsync(response.json.bind(response))();
|
|
24
|
+
return Object.assign(Error(`Request failed: ${status} ${statusText}`), {
|
|
25
|
+
response: { status, statusText, body: err ? {} : json },
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Sends a JSON request and resolves with the JSON response. A 401 with a client credentials token
|
|
31
|
+
* gets one more try with a fresh token, since the cached one may have been revoked or rotated; a
|
|
32
|
+
* 401 that stands is reported to `session` and rejects like any other failure.
|
|
33
|
+
*/
|
|
34
|
+
export const fetchCheckedJson = async (url, options, { oidcHandler, session } = {}) => {
|
|
35
|
+
// Cookies go along so a browser client is authenticated by its login session.
|
|
36
|
+
const jsonOptions = {
|
|
37
|
+
...R.mergeDeepRight({ headers: JSON_HEADERS }, options),
|
|
18
38
|
credentials: 'include',
|
|
19
39
|
};
|
|
40
|
+
const send = async () => globalThis.fetch(url, await withToken(jsonOptions, oidcHandler));
|
|
41
|
+
|
|
42
|
+
const retryWithFreshToken = async (first) => {
|
|
43
|
+
if (first.status !== UNAUTHORIZED || !oidcHandler) return first;
|
|
44
|
+
oidcHandler.invalidateToken();
|
|
45
|
+
return send();
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const response = await retryWithFreshToken(await send());
|
|
20
49
|
|
|
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);
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
const failure = await requestFailure(response);
|
|
52
|
+
if (response.status === UNAUTHORIZED) session?.lost(failure);
|
|
53
|
+
return Promise.reject(failure);
|
|
30
54
|
}
|
|
31
|
-
|
|
55
|
+
session?.confirmed();
|
|
56
|
+
return response.json();
|
|
32
57
|
};
|
package/src/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import * as R from 'ramda';
|
|
2
2
|
|
|
3
|
-
import { clientOptionsError } from './clientOptions.js';
|
|
3
|
+
import { clientOptionsError, tenantServiceUrl } from './clientOptions.js';
|
|
4
4
|
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,25 +29,28 @@ 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
|
|
34
36
|
? undefined
|
|
35
37
|
: await createMqttClient({
|
|
36
38
|
mqttUrl: mqttUrl || createMqttUrl({ tenantUrl, useWebsocket }),
|
|
37
|
-
authenticatorUrl: authenticatorUrl ||
|
|
39
|
+
authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
|
|
38
40
|
oidcHandler,
|
|
39
41
|
authConfig,
|
|
40
42
|
noAuth,
|
|
41
43
|
report,
|
|
44
|
+
session,
|
|
42
45
|
});
|
|
43
46
|
|
|
44
47
|
return createServerClient({
|
|
45
|
-
authenticatorUrl: authenticatorUrl ||
|
|
46
|
-
confUrl: confUrl ||
|
|
47
|
-
dataHistoryUrl: dataHistoryUrl ||
|
|
48
|
+
authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
|
|
49
|
+
confUrl: confUrl || tenantServiceUrl(tenantUrl, '/conf'),
|
|
50
|
+
dataHistoryUrl: dataHistoryUrl || tenantServiceUrl(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/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
|
+
};
|