@faybl/client 0.0.0-stage → 4.0.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/src/dataset.js ADDED
@@ -0,0 +1,189 @@
1
+ import * as R from 'ramda';
2
+ import {
3
+ assign,
4
+ createActor,
5
+ createMachine,
6
+ enqueueActions,
7
+ fromCallback,
8
+ fromPromise,
9
+ spawnChild,
10
+ stopChild,
11
+ waitFor,
12
+ } from 'xstate';
13
+
14
+ import { applyChange, compileFilter, createRecordMatcher, projectWith } from './datasetRecords.js';
15
+
16
+ const SUBSCRIPTION_ID = 'subscription';
17
+
18
+ // Subscribes to every change of the entity and says when the broker has acknowledged, so a change
19
+ // made while the dataset reads is held rather than lost.
20
+ const subscriptionActor = (client, entity) =>
21
+ fromCallback(({ sendBack }) => {
22
+ try {
23
+ const { ready, unsubscribe } = client.conf.subscribeWithAck({
24
+ entity,
25
+ callback: ({ operation, rid, record }) =>
26
+ sendBack({ type: 'change', operation, rid, record }),
27
+ });
28
+ const whenReady = async () => {
29
+ try {
30
+ await ready;
31
+ sendBack({ type: 'subscribed' });
32
+ } catch (error) {
33
+ sendBack({ type: 'subscription.failed', error });
34
+ }
35
+ };
36
+ whenReady();
37
+ return unsubscribe;
38
+ } catch (error) {
39
+ sendBack({ type: 'subscription.failed', error });
40
+ return undefined;
41
+ }
42
+ });
43
+
44
+ /**
45
+ * `Init` subscribes, waits for the acknowledgement, then reads. Changes that arrive meanwhile are
46
+ * held and applied on top of what was read, and only then is the dataset `Idle`.
47
+ */
48
+ const machineConfig = {
49
+ id: 'dataset',
50
+ context: { records: [], held: [], error: undefined },
51
+ initial: 'Init',
52
+ states: {
53
+ Init: {
54
+ entry: 'clearRecords',
55
+ initial: 'Checking',
56
+ on: { change: { actions: 'hold' } },
57
+ states: {
58
+ Checking: {
59
+ always: [
60
+ { guard: 'hasInvalidFilter', target: '#dataset.Error', actions: 'setFilterError' },
61
+ { target: 'Subscribing' },
62
+ ],
63
+ },
64
+ Subscribing: {
65
+ entry: 'subscribe',
66
+ on: {
67
+ subscribed: 'Loading',
68
+ 'subscription.failed': { target: '#dataset.Error', actions: 'setError' },
69
+ },
70
+ },
71
+ Loading: {
72
+ invoke: {
73
+ src: 'fetchRecords',
74
+ onDone: { target: '#dataset.Idle', actions: 'setRecords' },
75
+ onError: { target: '#dataset.Error', actions: 'setError' },
76
+ },
77
+ },
78
+ },
79
+ },
80
+ Idle: {
81
+ entry: 'clearError',
82
+ on: { change: { actions: 'applyChange' } },
83
+ },
84
+ Error: {
85
+ on: { retry: { target: 'Init', actions: 'unsubscribe' } },
86
+ },
87
+ },
88
+ };
89
+
90
+ const readArgsFor = ({ rids, filter, projection, ...rest }) => ({
91
+ ...rest,
92
+ ...(filter ? { filter } : {}),
93
+ ...(rids ? { rids } : {}),
94
+ ...(projection ? { projection } : {}),
95
+ });
96
+
97
+ /**
98
+ * A dataset holds the records of one entity that its `rids` and `filter` describe, at start and
99
+ * after every change conf publishes. `filter` is a MongoDB filter, evaluated on each changed record
100
+ * as conf evaluates it on a read. `recordFilter` from earlier versions is ignored.
101
+ */
102
+ export const createDatasetMachine = (client, spec, onChange = () => undefined) => {
103
+ const {
104
+ entity,
105
+ rids,
106
+ filter,
107
+ projection,
108
+ recordTransform = R.identity,
109
+ ...rest
110
+ } = R.omit(['recordFilter'], spec);
111
+ const readProjection = projection ? { ...projection, rid: 1 } : undefined;
112
+ const readArgs = readArgsFor({ ...rest, rids, filter, projection: readProjection });
113
+
114
+ const compiled = compileFilter(filter);
115
+ const change = applyChange({
116
+ matches: compiled.ok ? createRecordMatcher({ rids, test: compiled.value }) : R.F,
117
+ transform: R.pipe(readProjection ? projectWith(readProjection) : R.identity, recordTransform),
118
+ });
119
+ const applyAll = (records, changes) =>
120
+ changes.reduce((current, event) => change(current, event).records, records);
121
+
122
+ return createMachine(machineConfig, {
123
+ actors: {
124
+ fetchRecords: fromPromise(async () => client.conf[entity].read(readArgs)),
125
+ },
126
+ actions: {
127
+ subscribe: spawnChild(subscriptionActor(client, entity), { id: SUBSCRIPTION_ID }),
128
+ unsubscribe: stopChild(SUBSCRIPTION_ID),
129
+ clearRecords: assign({ records: [], held: [] }),
130
+ hold: assign({ held: ({ context: { held }, event }) => R.append(event, held) }),
131
+ setError: assign({ error: ({ event: { error } }) => error }),
132
+ setFilterError: assign({ error: () => Error(compiled.message) }),
133
+ clearError: assign({ error: undefined }),
134
+ setRecords: assign({
135
+ records: ({ context: { held }, event: { output } }) =>
136
+ applyAll(R.map(recordTransform)(output), held),
137
+ held: [],
138
+ }),
139
+ applyChange: enqueueActions(({ context: { records }, event, enqueue }) => {
140
+ const { records: next, notification } = change(records, event);
141
+ enqueue.assign({ records: next });
142
+ // Subscribers run after the transition, so getRecords already returns what they are told.
143
+ if (notification) enqueue(() => queueMicrotask(() => onChange(notification)));
144
+ }),
145
+ },
146
+ guards: {
147
+ hasInvalidFilter: () => !compiled.ok,
148
+ },
149
+ });
150
+ };
151
+
152
+ /**
153
+ * Settles once a dataset machine has loaded: with its records, or rejected with the error that
154
+ * stopped it.
155
+ */
156
+ export const datasetLoaded = async (datasetRef) => {
157
+ const snapshot = await waitFor(
158
+ datasetRef,
159
+ (state) => state.matches('Idle') || state.matches('Error'),
160
+ );
161
+ return snapshot.matches('Error')
162
+ ? Promise.reject(snapshot.context.error)
163
+ : snapshot.context.records;
164
+ };
165
+
166
+ export const createDataset = (client, spec) => {
167
+ // eslint-disable-next-line functional/no-let -- The dataset owns its subscriber list across independent subscribe, unsubscribe and machine events; each change replaces the array, so a list being iterated is never altered.
168
+ let callbacks = [];
169
+ const notify = (notification) => callbacks.forEach((callback) => callback(notification));
170
+ const machine = createActor(createDatasetMachine(client, spec, notify));
171
+ return {
172
+ machine,
173
+ init: async () => {
174
+ machine.start();
175
+ await datasetLoaded(machine);
176
+ },
177
+ subscribe: (callback) => {
178
+ callbacks = R.append(callback)(callbacks);
179
+ },
180
+ unsubscribe: (callback) => {
181
+ callbacks = callback ? R.without([callback])(callbacks) : [];
182
+ },
183
+ getRecords: () => machine.getSnapshot().context.records,
184
+ stop: () => {
185
+ callbacks = [];
186
+ machine.stop();
187
+ },
188
+ };
189
+ };
@@ -0,0 +1,76 @@
1
+ import * as R from 'ramda';
2
+ import sift from 'sift';
3
+
4
+ const isNonEmpty = R.complement(R.isEmpty);
5
+ const keysToInclude = R.pipe(R.pickBy(Boolean), R.keys);
6
+ const keysToExclude = R.pipe(R.pickBy(R.complement(Boolean)), R.keys);
7
+
8
+ const applyPickIfNeeded = (projection) => {
9
+ const keys = keysToInclude(projection);
10
+ return isNonEmpty(keys) ? R.pick(keys) : R.identity;
11
+ };
12
+
13
+ const applyOmitIfNeeded = (projection) => {
14
+ const keys = keysToExclude(projection);
15
+ return isNonEmpty(keys) ? R.omit(keys) : R.identity;
16
+ };
17
+
18
+ export const projectWith = (projection) =>
19
+ R.pipe(applyPickIfNeeded(projection), applyOmitIfNeeded(projection));
20
+
21
+ // `$where` runs JavaScript; a dataset filter only describes data. sift passes the operation's
22
+ // name fourth, after its parameters, the query that owns it and the options.
23
+ const refuseOperation = (...[, , , name]) => {
24
+ // eslint-disable-next-line functional/no-throw-statements -- sift's operation API reports an operation it cannot build by throwing; compileFilter turns it into a Result.
25
+ throw Error(`Unsupported operation: ${name}`);
26
+ };
27
+
28
+ /**
29
+ * Compiles a MongoDB filter into a test on a record, the same query language conf reads with.
30
+ * An operation sift cannot evaluate, such as `$text`, fails the compilation.
31
+ */
32
+ export const compileFilter = (filter = {}) => {
33
+ try {
34
+ return { ok: true, value: sift(filter, { operations: { $where: refuseOperation } }) };
35
+ } catch (error) {
36
+ return { ok: false, message: `Invalid dataset filter: ${error.message}` };
37
+ }
38
+ };
39
+
40
+ export const createRecordMatcher =
41
+ ({ rids, test }) =>
42
+ (record) =>
43
+ (rids === undefined || rids.includes(record.rid)) && test(record);
44
+
45
+ /**
46
+ * Applies one conf change to the records. A change carries the whole record as read after it, or
47
+ * only the rid for a delete, so a create or an update is an upsert and a delete of a rid that is
48
+ * not held changes nothing. A record that no longer matches leaves.
49
+ *
50
+ * Returns the records and the notification for subscribers, if anything changed.
51
+ */
52
+ export const applyChange =
53
+ ({ matches, transform }) =>
54
+ (records, { operation, rid, record }) => {
55
+ const index = records.findIndex((held) => held.rid === rid);
56
+ const previous = index === -1 ? undefined : records[index];
57
+ if (operation !== 'delete' && matches(record)) {
58
+ const next = transform(record);
59
+ return previous === undefined
60
+ ? { records: R.append(next, records), notification: { type: 'add', rid, record: next } }
61
+ : {
62
+ records: R.update(index, next, records),
63
+ notification: { type: 'update', rid, record: next, previous },
64
+ };
65
+ }
66
+ if (previous === undefined) return { records, notification: undefined };
67
+ return {
68
+ records: R.remove(index, 1, records),
69
+ notification: {
70
+ type: 'remove',
71
+ rid,
72
+ previous,
73
+ ...(operation === 'delete' ? {} : { record: transform(record) }),
74
+ },
75
+ };
76
+ };
package/src/fetch.js ADDED
@@ -0,0 +1,32 @@
1
+ import * as R from 'ramda';
2
+ import { biAsync } from 'tri-fp';
3
+
4
+ // Every request carries a JSON body, so the content type is set here rather than by each caller.
5
+ const JSON_HEADERS = { 'Content-Type': 'application/json' };
6
+
7
+ export const fetchCheckedJson = async (url, options, oidcHandler) => {
8
+ const jsonOptions = R.mergeDeepRight({ headers: JSON_HEADERS }, options);
9
+ const requestOptions = oidcHandler
10
+ ? R.assocPath(['headers', 'Authorization'])(`Bearer ${await oidcHandler.getToken()}`)(
11
+ jsonOptions,
12
+ )
13
+ : jsonOptions;
14
+
15
+ // Add 'credentials' option to include cookies for browser clients
16
+ const requestOptionsWithCredentials = {
17
+ ...requestOptions,
18
+ credentials: 'include',
19
+ };
20
+
21
+ const res = await globalThis.fetch(url, requestOptionsWithCredentials);
22
+ const { ok, status, statusText } = res;
23
+ if (!ok) {
24
+ const [err, json] = await biAsync(res.json.bind(res))();
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);
30
+ }
31
+ return res.json(); // throws if not json
32
+ };
package/src/index.js ADDED
@@ -0,0 +1,52 @@
1
+ import * as R from 'ramda';
2
+
3
+ import { clientOptionsError } from './clientOptions.js';
4
+ import { createClient as createServerClient } from './client.js';
5
+ import { createMqttClient } from './mqtt.js';
6
+ import { createOidcHandler } from './oidcHandler.js';
7
+ import { createReporter } from './report.js';
8
+
9
+ export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
10
+
11
+ const createMqttUrl = ({ tenantUrl, useWebsocket }) =>
12
+ useWebsocket ? `wss://ws.${tenantUrl}` : `mqtts://mqtt.${tenantUrl}`;
13
+
14
+ export const createClient = async (options = {}) => {
15
+ const optionsError = clientOptionsError(options);
16
+ if (optionsError) return Promise.reject(optionsError);
17
+ const {
18
+ tenantUrl,
19
+ confUrl,
20
+ dataHistoryUrl,
21
+ mqttUrl,
22
+ authenticatorUrl,
23
+ noMqtt,
24
+ authConfig,
25
+ useWebsocket,
26
+ noAuth,
27
+ onError,
28
+ } = options;
29
+
30
+ const report = createReporter(onError);
31
+ const oidcHandler = R.prop('issuerUrl')(authConfig) ? createOidcHandler(authConfig) : undefined;
32
+
33
+ const mqttClient = noMqtt
34
+ ? undefined
35
+ : await createMqttClient({
36
+ mqttUrl: mqttUrl || createMqttUrl({ tenantUrl, useWebsocket }),
37
+ authenticatorUrl: authenticatorUrl || `https://${tenantUrl}/authenticator`,
38
+ oidcHandler,
39
+ authConfig,
40
+ noAuth,
41
+ report,
42
+ });
43
+
44
+ return createServerClient({
45
+ authenticatorUrl: authenticatorUrl || `https://${tenantUrl}/authenticator`,
46
+ confUrl: confUrl || `https://${tenantUrl}/conf`,
47
+ dataHistoryUrl: dataHistoryUrl || `https://${tenantUrl}/data-history`,
48
+ mqttClient,
49
+ oidcHandler,
50
+ report,
51
+ });
52
+ };
package/src/mqtt.js ADDED
@@ -0,0 +1,75 @@
1
+ import mqtt from 'mqtt';
2
+
3
+ import { createMqttHandler } from './mqttUtils.js';
4
+ import { getMqttCredentials } from './mqttCredentials.js';
5
+
6
+ export const baseMqttOptions = {
7
+ keepAlive: 30,
8
+ reconnectPeriod: 5000,
9
+ // MQTT.js stops for good after a refused CONNACK. A refusal is usually passing, such as
10
+ // credentials the broker could not check yet, and the next attempt fetches fresh ones.
11
+ reconnectOnConnackError: true,
12
+ clean: true,
13
+ };
14
+
15
+ /**
16
+ * Makes every reconnect fetch fresh credentials first, since a token from the start of the
17
+ * connection has expired by then. MQTT.js reconnects by calling `client.connect` from a timer
18
+ * without waiting for it, and has no asynchronous hook for credentials, so `connect` is replaced.
19
+ *
20
+ * The replacement never rejects: a failed fetch is reported and the connection is attempted with
21
+ * the credentials it had, so the broker refuses and the next reconnect tries again. A reconnect
22
+ * that arrives while credentials are still being fetched is skipped.
23
+ */
24
+ const refreshCredentialsOnConnect = (client, credentialsSource) => {
25
+ const nativeConnect = client.connect.bind(client);
26
+ // eslint-disable-next-line functional/no-let -- One fetch at a time across reconnects that the MQTT.js timer starts independently.
27
+ let fetching = false;
28
+
29
+ /* 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. */
30
+ const applyCredentials = async () => {
31
+ try {
32
+ const { username, password } = await getMqttCredentials(credentialsSource);
33
+ if (username) client.options.username = username;
34
+ if (password) client.options.password = password;
35
+ } catch (error) {
36
+ credentialsSource.report(error, { source: 'credentials' });
37
+ }
38
+ };
39
+
40
+ client.connect = async (...args) => {
41
+ if (fetching) return client;
42
+ fetching = true;
43
+ try {
44
+ await applyCredentials();
45
+ } finally {
46
+ fetching = false;
47
+ }
48
+ return nativeConnect(...args);
49
+ };
50
+ /* eslint-enable functional/immutable-data */
51
+ };
52
+
53
+ export const createMqttClient = async ({
54
+ mqttUrl,
55
+ authenticatorUrl,
56
+ oidcHandler,
57
+ authConfig,
58
+ noAuth,
59
+ mqttOptions = {},
60
+ report = () => undefined,
61
+ }) => {
62
+ const credentialsSource = { authenticatorUrl, oidcHandler, authConfig, report };
63
+ const options = {
64
+ ...baseMqttOptions,
65
+ ...mqttOptions,
66
+ ...(noAuth ? {} : await getMqttCredentials(credentialsSource)),
67
+ clientId: `fayblClient_${Math.random().toString(16).slice(2, 12)}`,
68
+ };
69
+
70
+ const client = mqtt.connect(mqttUrl, options);
71
+ // An EventEmitter with no `error` listener throws, which would take the host process down.
72
+ client.on('error', (error) => report(error, { source: 'mqtt' }));
73
+ if (!noAuth) refreshCredentialsOnConnect(client, credentialsSource);
74
+ return createMqttHandler(client, { report });
75
+ };
@@ -0,0 +1,34 @@
1
+ import { fetchCheckedJson } from './fetch.js';
2
+
3
+ export const getMqttCredentials = async ({
4
+ authenticatorUrl,
5
+ oidcHandler,
6
+ authConfig,
7
+ report = () => undefined,
8
+ }) => {
9
+ if (oidcHandler) {
10
+ // JWT Authentication with Bearer token
11
+ return {
12
+ username: oidcHandler.clientId,
13
+ password: await oidcHandler.getToken(),
14
+ };
15
+ }
16
+ // SSO Authentication, fetching MQTT credentials from the authenticator service
17
+ const mqttCredentialsEndpoint = `${authenticatorUrl}/getMqttCredentials`;
18
+ try {
19
+ const id = authConfig?.clientId;
20
+ const credentials = await fetchCheckedJson(mqttCredentialsEndpoint, {
21
+ method: 'POST',
22
+ body: JSON.stringify(id ? { id } : {}),
23
+ });
24
+ return {
25
+ username: credentials.id,
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
+ }
34
+ };
@@ -0,0 +1,115 @@
1
+ import match from 'mqtt-match';
2
+ import * as R from 'ramda';
3
+ import { bi } from 'tri-fp';
4
+
5
+ const safeJsonParse = bi(JSON.parse);
6
+
7
+ // No `Buffer`: it is a Node global, and browsers have none. A Node Buffer is a typed array, so
8
+ // binary passes through on either side.
9
+ export const toPayload = (message) => {
10
+ if (message === undefined) return ''; // An empty payload clears a retained message
11
+ if (typeof message === 'string' || ArrayBuffer.isView(message)) return message;
12
+ return JSON.stringify(message);
13
+ };
14
+
15
+ const createStore = (initState = {}, reducer = () => initState) => {
16
+ // eslint-disable-next-line functional/no-let -- The subscription table must survive independently delivered subscribe calls and broker messages; the reducer keeps every transition pure.
17
+ let state = initState;
18
+ return {
19
+ getState: (key) => (key ? state[key] : state),
20
+ dispatch: (action) => (state = reducer(state, action)),
21
+ };
22
+ };
23
+
24
+ const actions = {
25
+ add: ({ topic, callback, preCallback }) =>
26
+ R.over(R.lens(R.prop(topic), R.assoc(topic)), R.append({ callback, preCallback })),
27
+ remove: ({ topic, callback }) =>
28
+ R.ifElse(
29
+ () => R.isNil(callback),
30
+ R.dissoc(topic),
31
+ R.when(
32
+ R.has(topic),
33
+ R.pipe(
34
+ R.over(R.lensProp(topic), R.reject(R.propEq(callback, 'callback'))),
35
+ R.when(R.propSatisfies(R.isEmpty, topic), R.dissoc(topic)),
36
+ ),
37
+ ),
38
+ ),
39
+ clear: () => () => ({}),
40
+ };
41
+
42
+ const reducer = (state, { type, ...rest }) => actions[type]?.(rest)(state) ?? state;
43
+
44
+ export const matchTopic = R.curryN(2, match);
45
+
46
+ export const getMatchingTopics = (topic) => R.pickBy((_, key) => matchTopic(key)(topic));
47
+
48
+ // A subscriber's failure is reported and stays its own: it neither reaches the
49
+ // other subscribers nor escapes as an unhandled rejection.
50
+ const deliver =
51
+ (report) =>
52
+ async ({ callback, preCallback }, message) => {
53
+ try {
54
+ const payload = preCallback ? await preCallback(message) : message;
55
+ await callback(payload);
56
+ } catch (error) {
57
+ report(error, { source: 'subscriber', topic: message.topic });
58
+ }
59
+ };
60
+
61
+ const messageHandler = (getState, report) => async (topic, jsonData) => {
62
+ // An empty payload clears a retained message; there is nothing to deliver.
63
+ if (jsonData.length === 0) return undefined;
64
+ const [error, data] = safeJsonParse(jsonData);
65
+
66
+ if (error) return report(error, { source: 'message', topic });
67
+ const subscribers = R.pipe(getState, getMatchingTopics(topic), R.values, R.flatten)();
68
+ await Promise.all(subscribers.map((subscriber) => deliver(report)(subscriber, { topic, data })));
69
+ return undefined;
70
+ };
71
+
72
+ export const createMqttHandler = (client, { report = () => undefined } = {}) => {
73
+ const { getState, dispatch } = createStore({}, reducer);
74
+
75
+ const handleMessage = messageHandler(getState, report);
76
+ client.on('message', handleMessage);
77
+ const unsubscribe = (topic, callback) => {
78
+ dispatch({ type: 'remove', topic, callback });
79
+ if (!getState(topic)) client.unsubscribe(topic);
80
+ };
81
+
82
+ const subscribe = (topic, callback, { preCallback, qos } = {}) => {
83
+ client.subscribe(topic, ...(qos === undefined ? [] : [{ qos }]));
84
+ dispatch({ type: 'add', topic, callback, preCallback });
85
+ return () => unsubscribe(topic, callback);
86
+ };
87
+
88
+ const subscribeWithAck = (topic, callback, { qos, preCallback } = {}) => {
89
+ dispatch({ type: 'add', topic, callback, preCallback });
90
+ const ready = new Promise((resolve, reject) => {
91
+ client.subscribe(topic, { qos }, (error, granted) => {
92
+ if (error) return reject(error);
93
+ if (granted?.[0]?.qos !== qos) {
94
+ return reject(Error(`MQTT subscription to ${topic} was not granted QoS ${qos}`));
95
+ }
96
+ return resolve();
97
+ });
98
+ });
99
+ return { ready, unsubscribe: () => unsubscribe(topic, callback) };
100
+ };
101
+
102
+ const publish = (topic, message, options) => client.publish(topic, toPayload(message), options);
103
+
104
+ const close = async () => {
105
+ dispatch({ type: 'clear' });
106
+ await client.endAsync();
107
+ };
108
+
109
+ return { client, publish, subscribe, subscribeWithAck, unsubscribe, close };
110
+ };
111
+
112
+ export const mqttDisabledWarning = () => {
113
+ // eslint-disable-next-line functional/no-throw-statements -- Stands in for subscribe and publish when MQTT is off; returning a Result would change what those public methods return, and calling them without MQTT is a programming error at the call site.
114
+ throw Error('MQTT is disabled');
115
+ };
@@ -0,0 +1,71 @@
1
+ import * as oc from 'openid-client';
2
+
3
+ const createOidcConfig = async ({ issuerUrl, clientId, clientSecret }) => {
4
+ // issuerUrl should be the issuer identifier, not the .well-known metadata URL
5
+ const configuration = await oc.discovery(new URL(issuerUrl), clientId, clientSecret);
6
+
7
+ // In-memory token cache
8
+ /* eslint-disable functional/no-let -- The token cache lives across independent getToken calls, and the in-flight request must be shared so concurrent callers make one token request. */
9
+ let currentTokens; // { access_token, expires_in, ... }
10
+ let expiresAt = 0; // epoch time in ms
11
+ let inflight; // prevent concurrent token requests
12
+ /* eslint-enable functional/no-let */
13
+
14
+ const getToken = async () => {
15
+ const now = Date.now();
16
+ if (currentTokens && now < expiresAt) return currentTokens;
17
+
18
+ // Reuse ongoing token request if present
19
+ if (inflight) {
20
+ await inflight;
21
+ return currentTokens;
22
+ }
23
+
24
+ inflight = (async () => {
25
+ const tokens = await oc.clientCredentialsGrant(configuration, {});
26
+ const skew = 5; // seconds safety margin
27
+ const ttlSec = Math.max((tokens.expires_in ?? 60) - skew, 1);
28
+ currentTokens = tokens;
29
+ expiresAt = now + ttlSec * 1000;
30
+ })();
31
+
32
+ try {
33
+ await inflight;
34
+ } finally {
35
+ inflight = undefined;
36
+ }
37
+ return currentTokens;
38
+ };
39
+
40
+ return { getToken };
41
+ };
42
+
43
+ // Client credentials grant for server-side clients. The Node entry point creates
44
+ // one when authConfig carries an issuerUrl; its token authenticates both HTTP
45
+ // requests and the MQTT connection. Discovery runs on the first token request,
46
+ // and a failed discovery is retried on the next one.
47
+ export const createOidcHandler = ({ issuerUrl, clientId, clientSecret }) => {
48
+ // eslint-disable-next-line functional/no-let -- Discovery is shared by every getToken call and must be dropped after a failure so the next call can retry it.
49
+ let configPromise;
50
+
51
+ const loadConfig = async () => {
52
+ const discovery = (configPromise ??= createOidcConfig({ issuerUrl, clientId, clientSecret }));
53
+ try {
54
+ return await discovery;
55
+ } catch (error) {
56
+ if (configPromise === discovery) configPromise = undefined;
57
+ return Promise.reject(error);
58
+ }
59
+ };
60
+
61
+ const getToken = async () => {
62
+ const config = await loadConfig();
63
+ const tokenSet = await config.getToken();
64
+ return tokenSet.access_token;
65
+ };
66
+
67
+ return {
68
+ getToken,
69
+ clientId,
70
+ };
71
+ };
@@ -0,0 +1,40 @@
1
+ import { mqttDisabledWarning } from './mqttUtils.js';
2
+ import { assertTopicSegment, assertTopicSegments } from './topicSegment.js';
3
+
4
+ const baseTopic = 'presence';
5
+
6
+ // One identity or several; a single string keeps the common call short.
7
+ const toIdentityIds = (identityIds) =>
8
+ Array.isArray(identityIds)
9
+ ? assertTopicSegments('identityIds', identityIds)
10
+ : [assertTopicSegment('identityId', identityIds)];
11
+
12
+ export const getPresenceApi = (mqttClient) => {
13
+ const preCallback = ({ topic, data }) => {
14
+ return { identityId: topic.replace(`${baseTopic}/`, ''), data };
15
+ };
16
+ const unsubscribe = (identityIds, callback) => {
17
+ toIdentityIds(identityIds).forEach((identityId) =>
18
+ mqttClient.unsubscribe(`${baseTopic}/${identityId}`, callback),
19
+ );
20
+ };
21
+ const subscribe = (identityIds, callback) => {
22
+ const checked = toIdentityIds(identityIds);
23
+ checked.forEach((identityId) =>
24
+ mqttClient.subscribe(`${baseTopic}/${identityId}`, callback, { preCallback }),
25
+ );
26
+ return () => unsubscribe(checked, callback);
27
+ };
28
+
29
+ return {
30
+ ...(mqttClient
31
+ ? {
32
+ subscribe,
33
+ unsubscribe,
34
+ }
35
+ : {
36
+ subscribe: mqttDisabledWarning,
37
+ unsubscribe: mqttDisabledWarning,
38
+ }),
39
+ };
40
+ };