@devicechain/client 1.6.0-rc.1 → 1.7.0-rc.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 CHANGED
@@ -59,9 +59,11 @@ identity token. `areaPath(area)` returns the HTTP path and `areaKey(area)` the
59
59
  functional area before any slash.
60
60
 
61
61
  Failures arrive as a `GraphQLRequestError` carrying the HTTP status and the
62
- GraphQL error list. `isForbiddenError(err)` is the one classification worth
63
- special-casing, because "you may not do that" is a different thing to show a
64
- user than "the request did not arrive".
62
+ GraphQL error list. `isForbiddenError(err)` distinguishes a permission refusal
63
+ from a failed request. `isStaleWrite(err)` recognizes an optimistic-concurrency
64
+ refusal by `extensions.code: STALE_WRITE`, with the phrase `modified by another
65
+ writer` as a fallback for older servers. Keep the unsaved draft and ask the user
66
+ to reload before retrying; a stale write is distinct from a uniqueness `CONFLICT`.
65
67
 
66
68
  ## Authentication
67
69
 
@@ -95,7 +97,7 @@ const session = createSessionTokens({
95
97
  (await gql('user-management', REFRESH, { refreshToken }, { anonymous: true })).refresh,
96
98
  onEnd: (err) => {
97
99
  store.pair = null;
98
- showSignIn(err); // refused, lapsed, or offline past expiry
100
+ showSignIn(err); // the server refused the refresh, or the refresh token lapsed
99
101
  },
100
102
  });
101
103
  setAuthTokenGetter(session.getAccessToken);
@@ -105,14 +107,64 @@ const stop = session.startAutoRefresh(); // optional: refresh on a timer, not on
105
107
  ```
106
108
 
107
109
  A refusal from the server, such as an invalid or revoked refresh token, ends the
108
- session at once. A transient failure does not: no response, a 5xx, or a 429. While
109
- the access token is still valid, callers keep getting it, and
110
- `startAutoRefresh` retries with jittered backoff. The session ends only when the
111
- access token actually expires.
110
+ session at once. A transient failure never does: no response, a 5xx, or a 429. While
111
+ the access token is still valid, callers keep getting it. Once it has expired,
112
+ `getAccessToken` resolves to `null` for that call, the session is kept, and the next
113
+ call tries again. `startAutoRefresh` retries with jittered backoff for as long as the
114
+ refresh token is valid. A session that only ever fails transiently ends when its
115
+ refresh token lapses.
116
+
117
+ A `null` sends the request without a token, so the server answers it with a 401. To
118
+ fail it with the outage instead, opt in with `transientRefreshErrors: 'throw'`:
119
+
120
+ ```ts
121
+ const session = createSessionTokens({ ...options, transientRefreshErrors: 'throw' });
122
+ ```
123
+
124
+ `getAccessToken` then rejects with the transient error (a `GraphQLRequestError` with
125
+ status 0, 429 or 5xx) in that window, and still resolves to `null` when signed out or
126
+ after a refusal. `gql` rejects with that error, and a subscription reconnect retries
127
+ it with its usual back-off. The console and the dashboard app run in this mode.
112
128
 
113
129
  `decodeToken`, `isExpired` and `hasAuthority` are exported for reading claims
114
130
  client-side. They decode, they do not verify — the server is the authority.
115
131
 
132
+ HTTP 401 recovery is opt-in through `setUnauthorizedHandler({ refresh, onEnd })`.
133
+ For an authenticated request, `refresh(token, identity)` may return a new bearer
134
+ for **one replay** of the same operation. Use `session.forceRefresh(token)` for
135
+ tenant tokens (`createSessionTokens` returns a `ManagedSessionTokens`, on which it is
136
+ always present; it is optional on `SessionTokens`, so an object a host builds to that
137
+ v1.6 type still type-checks): it bypasses the expiry check, shares an in-flight refresh, and never
138
+ returns the rejected token. When the server refuses the refresh it ends the session
139
+ and returns null; when the refresh fails transiently (no response, a 5xx or a 429)
140
+ it throws that error and keeps the session, whatever `transientRefreshErrors` says. It
141
+ returns null for a token belonging to a replaced session. Identity tokens have no
142
+ refresh path; return null for that lane. Anonymous login/refresh requests never
143
+ invoke the handler. If recovery returns null or the replay also gets 401,
144
+ `onEnd(error, token, identity)` runs; only clear the session still owning that token.
145
+ If recovery throws, the request fails with that error and `onEnd` does not run.
146
+ Unregister with `setUnauthorizedHandler(null)` on teardown. Without a handler,
147
+ the existing `GraphQLRequestError` with status 401 is unchanged. A replay that
148
+ fails with a network error or another HTTP status follows ordinary error handling.
149
+
150
+ Refresh tokens rotate, and the server honours each one once. An operation of your own
151
+ that spends the refresh token, such as a step-up that trades it with a second-factor code
152
+ for an elevated pair, must go through `session.exchange(spend)` rather than reading the
153
+ token and calling the server itself; otherwise a refresh running at the same moment (a
154
+ forced one after a 401 starts whatever the access token's expiry) spends it too, and the
155
+ loser's refusal ends the session:
156
+
157
+ ```ts
158
+ await session.exchange((refreshToken) => stepUp(refreshToken, code)); // resolves to the new access token
159
+ ```
160
+
161
+ `exchange` waits for a refresh already running and spends the token it left; while
162
+ `spend` runs, every refresh asked for waits for it and takes the pair it yields, which is
163
+ applied like a refreshed one. If `spend` fails, it rejects with that error and the session
164
+ is kept. While it runs, `getAccessToken` hands out the held token without waiting (spend's
165
+ own request needs one), and a `forceRefresh` naming that token as rejected throws a 401
166
+ error and keeps the session instead of waiting on it.
167
+
116
168
  ## Subscriptions
117
169
 
118
170
  ```ts
@@ -142,7 +194,11 @@ The socket carries subscriptions only; send queries and mutations over HTTP. The
142
194
  server closes it with code `4401` when the access token it opened with expires.
143
195
  `subscribe` handles that close for you: it reconnects once with a freshly resolved
144
196
  token, subscribes again, and reports the reconnect as `connected(true)`, so re-query
145
- anything you must not miss when you see it.
197
+ anything you must not miss when you see it. A reconnect whose token getter rejects
198
+ with a transient refresh error (as `getAccessToken` does under
199
+ `transientRefreshErrors: 'throw'` when the access token has expired and the refresh got
200
+ no response, a 5xx or a 429) is retried with the same back-off as a dropped network, rather than ending the
201
+ subscription with that error. A refused refresh still ends the session.
146
202
 
147
203
  For a subscription with no variables, the third argument is still required:
148
204
  `subscribe(area, document, undefined, sink)`. Call the returned `unsubscribe()`
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** True for an optimistic-concurrency refusal. Keeps the phrase fallback for older servers. */
2
+ export declare function isStaleWrite(err: unknown): boolean;
1
3
  /**
2
4
  * True when the server REFUSED the request for lack of an authority, as opposed
3
5
  * to failing it. Callers use this to render a permission state rather than an
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { gql, areaPath, areaKey, AREAS, resolveAuthToken, setAuthTokenGetter, setIdentityTokenGetter, GraphQLRequestError, type GraphQLErrorEntry, type Area, type RequestOptions, type TypedDocument, } from './transport';
2
- export { isForbiddenError, isScopeUnsupportedError, errorCode } from './errors';
1
+ export { gql, areaPath, areaKey, AREAS, resolveAuthToken, setAuthTokenGetter, setIdentityTokenGetter, setUnauthorizedHandler, type UnauthorizedHandler, GraphQLRequestError, type GraphQLErrorEntry, type Area, type RequestOptions, type TypedDocument, } from './transport';
2
+ export { isForbiddenError, isScopeUnsupportedError, isStaleWrite, errorCode } from './errors';
3
3
  export { resolveBasemap, renderableBasemap, fallbackView, type Basemap, type ResolvedBasemap, } from './basemap';
4
4
  export { subscribe, disposeSubscriptions, type SubscriptionSink } from './subscribe';
5
- export { createSessionTokens, type SessionTokens, type SessionTokensOptions, type TokenPair, } from './session';
5
+ export { createSessionTokens, type ManagedSessionTokens, type SessionTokens, type SessionTokensOptions, type TokenPair, } from './session';
6
6
  export { decodeToken, isExpired, hasAuthority, isScoped, scopeAnchorRefs, type DecodedClaims, type ScopeAnchorRef, } from './jwt';
7
7
  export { generateToken, normalizeToken, conformsToMask, maskToRegExp, parseMask, resolveMask, isValidToken, sampleToken, validateMask, MAX_TOKEN_LEN, type GenerateOptions, type MaskSegment, type MaskProblem, } from './tokens';
package/dist/index.js CHANGED
@@ -31,6 +31,10 @@ var identityTokenGetter = null;
31
31
  function setIdentityTokenGetter(getter) {
32
32
  identityTokenGetter = getter;
33
33
  }
34
+ var unauthorizedHandler = null;
35
+ function setUnauthorizedHandler(handler) {
36
+ unauthorizedHandler = handler;
37
+ }
34
38
  async function resolveAuthToken() {
35
39
  return tokenGetter ? tokenGetter() : null;
36
40
  }
@@ -44,26 +48,46 @@ var GraphQLRequestError = class extends Error {
44
48
  };
45
49
  async function gql(area, document, ...[variables, options]) {
46
50
  const headers = { "Content-Type": "application/json" };
51
+ const useIdentity = options?.identity ?? isIdentityArea(area);
52
+ const handler = unauthorizedHandler;
53
+ let token = null;
47
54
  if (!options?.anonymous) {
48
- const useIdentity = options?.identity ?? isIdentityArea(area);
49
55
  const getter = useIdentity ? identityTokenGetter : tokenGetter;
50
56
  if (getter) {
51
- const token = await getter();
57
+ token = await getter();
52
58
  if (token) headers["Authorization"] = `Bearer ${token}`;
53
59
  }
54
60
  }
55
- let res;
56
- try {
57
- res = await fetch(areaPath(area), {
58
- method: "POST",
59
- headers,
60
- body: JSON.stringify({ query: document.toString(), variables })
61
- });
62
- } catch (err) {
63
- throw new GraphQLRequestError(
64
- err instanceof Error ? err.message : "Network request failed",
65
- 0
66
- );
61
+ const bodyText = JSON.stringify({ query: document.toString(), variables });
62
+ const send = async () => {
63
+ try {
64
+ return await fetch(areaPath(area), {
65
+ method: "POST",
66
+ headers: { ...headers },
67
+ body: bodyText
68
+ });
69
+ } catch (err) {
70
+ throw new GraphQLRequestError(
71
+ err instanceof Error ? err.message : "Network request failed",
72
+ 0
73
+ );
74
+ }
75
+ };
76
+ let res = await send();
77
+ if (res.status === 401 && token && handler && !options?.anonymous) {
78
+ const rejectedToken = token;
79
+ token = await handler.refresh(rejectedToken, useIdentity);
80
+ if (token) {
81
+ headers["Authorization"] = `Bearer ${token}`;
82
+ res = await send();
83
+ }
84
+ if (res.status === 401) {
85
+ handler.onEnd(
86
+ new GraphQLRequestError("Request failed (401)", 401),
87
+ token ?? rejectedToken,
88
+ useIdentity
89
+ );
90
+ }
67
91
  }
68
92
  if (!res.ok) {
69
93
  throw new GraphQLRequestError(`Request failed (${res.status})`, res.status);
@@ -79,6 +103,14 @@ async function gql(area, document, ...[variables, options]) {
79
103
  }
80
104
 
81
105
  // src/errors.ts
106
+ function isStaleWrite(err) {
107
+ if (err instanceof GraphQLRequestError && err.errors?.length) {
108
+ return err.errors.some(
109
+ (entry) => entry.extensions?.code === "STALE_WRITE" || !entry.extensions?.code && entry.message.includes("modified by another writer")
110
+ );
111
+ }
112
+ return err instanceof Error && err.message.includes("modified by another writer");
113
+ }
82
114
  var FORBIDDEN_PREFIX = /^forbidden\b/i;
83
115
  function isForbiddenError(err) {
84
116
  if (Array.isArray(err)) return err.some(isForbiddenEntry);
@@ -156,123 +188,6 @@ function fallbackView(b) {
156
188
 
157
189
  // src/subscribe.ts
158
190
  import { createClient } from "graphql-ws";
159
- var CLOSE_UNAUTHORIZED = 4401;
160
- function wsUrl(area) {
161
- const scheme = window.location.protocol === "https:" ? "wss" : "ws";
162
- return `${scheme}://${window.location.host}${areaPath(area)}`;
163
- }
164
- var RETRY_CEILING_MS = 3e4;
165
- function retryDelayMs(retries, random = Math.random) {
166
- const ceiling = Math.min(1e3 * 2 ** retries, RETRY_CEILING_MS);
167
- return ceiling / 2 * (1 + random());
168
- }
169
- var clients = /* @__PURE__ */ new Map();
170
- function clientFor(area) {
171
- let entry = clients.get(area);
172
- if (!entry) {
173
- const client = createClient({
174
- url: wsUrl(area),
175
- connectionParams: async () => {
176
- const token = await resolveAuthToken();
177
- return token ? { Authorization: `Bearer ${token}` } : {};
178
- },
179
- // 🔴 Keep reconnecting for as long as anything is subscribed. Left to its defaults,
180
- // graphql-ws gives up after 5 attempts (about 40 s; in a browser, after the first one
181
- // that fails, see shouldRetry) and then errors every operation, and nothing reopened
182
- // them: a wall display that lost its network for a minute showed
183
- // "Data unavailable" until someone reloaded it. One socket per area carries every
184
- // operation, so each attempt is ONE connection however many widgets are waiting, and
185
- // graphql-ws resubscribes all of them on it once it is acknowledged.
186
- retryAttempts: Infinity,
187
- retryWait: (retries) => new Promise((resolve) => setTimeout(resolve, retryDelayMs(retries))),
188
- // graphql-ws retries only close events by default, and a browser reports a handshake
189
- // that failed (the server or the network still down) as an `error` event first, so
190
- // the first failed attempt would end every operation however many were allowed. A
191
- // socket's own error event is a network problem and is retried; an Error thrown in
192
- // this client is not. The closes that say the request itself is wrong (4400, 4401,
193
- // 4409, 4429) are fatal inside graphql-ws whatever this answers, so an expired or
194
- // refused token still reaches subscribe() below and the session flow, never a loop.
195
- shouldRetry: (err) => typeof Event != "undefined" && err instanceof Event || hasCode(err)
196
- });
197
- const state = { client, acked: false, lastCloseWasAcked: false };
198
- client.on("connecting", () => {
199
- state.acked = false;
200
- });
201
- client.on("connected", () => {
202
- state.acked = true;
203
- });
204
- client.on("closed", () => {
205
- state.lastCloseWasAcked = state.acked;
206
- state.acked = false;
207
- });
208
- entry = state;
209
- clients.set(area, entry);
210
- }
211
- return entry;
212
- }
213
- function hasCode(err) {
214
- return typeof err === "object" && err !== null && "code" in err;
215
- }
216
- function isUnauthorizedClose(err) {
217
- return hasCode(err) && err.code === CLOSE_UNAUTHORIZED;
218
- }
219
- function subscribe(area, document, variables, sink) {
220
- const entry = clientFor(area);
221
- const { client } = entry;
222
- let reauth = false;
223
- const disposers = [];
224
- if (sink.connected) {
225
- disposers.push(
226
- client.on("connected", (_socket, _payload, wasRetry) => {
227
- const retried = wasRetry || reauth;
228
- reauth = false;
229
- sink.connected(retried);
230
- })
231
- );
232
- }
233
- if (sink.closed) {
234
- disposers.push(client.on("closed", () => sink.closed()));
235
- }
236
- const payload = {
237
- query: document.toString(),
238
- variables
239
- };
240
- let disposed = false;
241
- let current = null;
242
- const start = () => {
243
- const previous = current;
244
- current = client.subscribe(payload, {
245
- next: (result) => {
246
- if (result.data != null) sink.next(result.data);
247
- },
248
- error: (err) => {
249
- if (disposed) return;
250
- if (isUnauthorizedClose(err) && entry.lastCloseWasAcked) {
251
- reauth = true;
252
- start();
253
- return;
254
- }
255
- sink.error?.(err);
256
- },
257
- complete: () => sink.complete?.()
258
- });
259
- previous?.();
260
- };
261
- start();
262
- disposers.push(() => {
263
- disposed = true;
264
- current?.();
265
- });
266
- return () => {
267
- for (const dispose of disposers) dispose();
268
- };
269
- }
270
- function disposeSubscriptions() {
271
- for (const { client } of clients.values()) {
272
- void client.dispose();
273
- }
274
- clients.clear();
275
- }
276
191
 
277
192
  // src/jwt.ts
278
193
  function base64UrlDecode(segment) {
@@ -339,7 +254,14 @@ function expiryMs(token) {
339
254
  }
340
255
  function createSessionTokens(opts) {
341
256
  const skew = opts.skewSeconds ?? DEFAULT_SKEW_SECONDS;
257
+ const mode = opts.transientRefreshErrors;
258
+ if (mode !== void 0 && mode !== "null" && mode !== "throw") {
259
+ throw new TypeError(`createSessionTokens: transientRefreshErrors must be 'null' or 'throw', not ${String(mode)}`);
260
+ }
261
+ const throwTransient = mode === "throw";
342
262
  let inFlight = null;
263
+ let exchanging = null;
264
+ let lastRefresh = null;
343
265
  const skewFor = (token) => {
344
266
  const c = decodeToken(token);
345
267
  if (c?.exp === void 0 || c.iat === void 0) return skew;
@@ -350,25 +272,40 @@ function createSessionTokens(opts) {
350
272
  inFlight = null;
351
273
  opts.onEnd(err);
352
274
  };
353
- const refreshShared = (current) => {
354
- if (!inFlight) {
355
- inFlight = (async () => {
356
- try {
357
- const pair = await opts.refresh(current.refreshToken);
358
- if (opts.read() !== current) return { kind: "stale" };
359
- opts.apply({ accessToken: pair.accessToken, refreshToken: pair.refreshToken });
360
- return { kind: "ok", token: pair.accessToken };
361
- } catch (err) {
362
- if (opts.read() !== current) return { kind: "stale" };
363
- if (isTransientRefreshError(err)) return { kind: "transient", err };
364
- end(err);
365
- return { kind: "ended" };
366
- } finally {
275
+ const run = (current, spend, isExchange) => {
276
+ let settled = false;
277
+ let p = void 0;
278
+ p = (async () => {
279
+ try {
280
+ const pair = await spend(current.refreshToken);
281
+ if (opts.read() !== current) return { kind: "stale" };
282
+ const next = { accessToken: pair.accessToken, refreshToken: pair.refreshToken };
283
+ opts.apply(next);
284
+ lastRefresh = { from: current.accessToken, pair: next };
285
+ return { kind: "ok", token: pair.accessToken };
286
+ } catch (err) {
287
+ if (isExchange) return { kind: "declined", err };
288
+ if (opts.read() !== current) return { kind: "stale" };
289
+ if (isTransientRefreshError(err)) return { kind: "transient", err };
290
+ end(err);
291
+ return { kind: "ended" };
292
+ } finally {
293
+ settled = true;
294
+ if (p === void 0 || inFlight === p) {
367
295
  inFlight = null;
296
+ exchanging = null;
368
297
  }
369
- })();
298
+ }
299
+ })();
300
+ if (!settled) inFlight = p;
301
+ return p;
302
+ };
303
+ const refreshShared = async (current) => {
304
+ for (; ; ) {
305
+ const out = await (inFlight ?? run(current, opts.refresh, false));
306
+ if (out.kind !== "declined") return out;
307
+ if (opts.read() !== current) return { kind: "stale" };
370
308
  }
371
- return inFlight;
372
309
  };
373
310
  const getAccessToken = async () => {
374
311
  const current = opts.read();
@@ -378,12 +315,13 @@ function createSessionTokens(opts) {
378
315
  return null;
379
316
  }
380
317
  if (!due(current.accessToken)) return current.accessToken;
318
+ if (exchanging !== null && !isExpired(current.accessToken, 0)) return current.accessToken;
381
319
  const out = await refreshShared(current);
382
320
  if (out.kind === "ok") return out.token;
383
321
  if (out.kind !== "transient") return null;
384
322
  if (opts.read() !== current) return null;
385
323
  if (!isExpired(current.accessToken, 0)) return current.accessToken;
386
- end(out.err);
324
+ if (throwTransient) throw out.err;
387
325
  return null;
388
326
  };
389
327
  const startAutoRefresh = () => {
@@ -422,14 +360,15 @@ function createSessionTokens(opts) {
422
360
  }
423
361
  if (out.kind !== "transient") return;
424
362
  if (opts.read() !== current) return;
363
+ const backoff = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** failures) * (0.5 + Math.random() / 2);
364
+ failures++;
425
365
  const left = (expiryMs(current.accessToken) ?? 0) - RETRY_EXPIRY_MARGIN_MS - Date.now();
426
- if (left <= 0) {
427
- end(out.err);
366
+ if (left > 0) {
367
+ arm(left - backoff < RETRY_BASE_MS ? left : backoff);
428
368
  return;
429
369
  }
430
- const backoff = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** failures) * (0.5 + Math.random() / 2);
431
- failures++;
432
- arm(left - backoff < RETRY_BASE_MS ? left : backoff);
370
+ const refreshLeft = (expiryMs(current.refreshToken) ?? 0) - Date.now();
371
+ arm(Math.min(backoff, refreshLeft));
433
372
  };
434
373
  schedule();
435
374
  return () => {
@@ -439,13 +378,179 @@ function createSessionTokens(opts) {
439
378
  };
440
379
  return {
441
380
  getAccessToken,
381
+ forceRefresh: async (rejectedToken) => {
382
+ const current = opts.read();
383
+ if (!current) return null;
384
+ if (rejectedToken !== void 0 && current.accessToken !== rejectedToken) {
385
+ return lastRefresh?.pair === current && lastRefresh.from === rejectedToken ? current.accessToken : null;
386
+ }
387
+ if (isExpired(current.refreshToken, 0)) {
388
+ end();
389
+ return null;
390
+ }
391
+ if (exchanging !== null && rejectedToken === exchanging) {
392
+ throw new GraphQLRequestError("Request failed (401)", 401);
393
+ }
394
+ const out = await refreshShared(current);
395
+ if (out.kind === "ok") return out.token;
396
+ if (out.kind !== "transient") return null;
397
+ if (opts.read() !== current) return null;
398
+ throw out.err;
399
+ },
400
+ exchange: async (spend) => {
401
+ if (!await getAccessToken()) throw new Error("session unavailable");
402
+ while (inFlight) await inFlight;
403
+ const current = opts.read();
404
+ if (!current) throw new Error("session unavailable");
405
+ if (isExpired(current.refreshToken, 0)) {
406
+ end();
407
+ throw new Error("session unavailable");
408
+ }
409
+ exchanging = current.accessToken;
410
+ const out = await run(current, spend, true);
411
+ if (out.kind === "ok") return out.token;
412
+ if (out.kind === "declined") throw out.err;
413
+ throw new Error("session changed");
414
+ },
442
415
  reset: () => {
443
416
  inFlight = null;
417
+ exchanging = null;
418
+ lastRefresh = null;
444
419
  },
445
420
  startAutoRefresh
446
421
  };
447
422
  }
448
423
 
424
+ // src/subscribe.ts
425
+ var CLOSE_UNAUTHORIZED = 4401;
426
+ function wsUrl(area) {
427
+ const scheme = window.location.protocol === "https:" ? "wss" : "ws";
428
+ return `${scheme}://${window.location.host}${areaPath(area)}`;
429
+ }
430
+ var RETRY_CEILING_MS = 3e4;
431
+ function retryDelayMs(retries, random = Math.random) {
432
+ const ceiling = Math.min(1e3 * 2 ** retries, RETRY_CEILING_MS);
433
+ return ceiling / 2 * (1 + random());
434
+ }
435
+ var clients = /* @__PURE__ */ new Map();
436
+ function clientFor(area) {
437
+ let entry = clients.get(area);
438
+ if (!entry) {
439
+ const client = createClient({
440
+ url: wsUrl(area),
441
+ connectionParams: async () => {
442
+ const token = await resolveAuthToken();
443
+ return token ? { Authorization: `Bearer ${token}` } : {};
444
+ },
445
+ // 🔴 Keep reconnecting for as long as anything is subscribed. Left to its defaults,
446
+ // graphql-ws gives up after 5 attempts (about 40 s; in a browser, after the first one
447
+ // that fails, see shouldRetry) and then errors every operation, and nothing reopened
448
+ // them: a wall display that lost its network for a minute showed
449
+ // "Data unavailable" until someone reloaded it. One socket per area carries every
450
+ // operation, so each attempt is ONE connection however many widgets are waiting, and
451
+ // graphql-ws resubscribes all of them on it once it is acknowledged.
452
+ retryAttempts: Infinity,
453
+ retryWait: (retries) => new Promise((resolve) => setTimeout(resolve, retryDelayMs(retries))),
454
+ // graphql-ws retries only close events by default, and a browser reports a handshake
455
+ // that failed (the server or the network still down) as an `error` event first, so
456
+ // the first failed attempt would end every operation however many were allowed. A
457
+ // socket's own error event is a network problem and is retried; an Error thrown in
458
+ // this client is not. The closes that say the request itself is wrong (4400, 4401,
459
+ // 4409, 4429) are fatal inside graphql-ws whatever this answers, so an expired or
460
+ // refused token still reaches subscribe() below and the session flow, never a loop.
461
+ //
462
+ // 🔴 And a token that could not be had FOR NOW. The session's getAccessToken, under
463
+ // transientRefreshErrors: 'throw', throws when the held access token has expired and the
464
+ // refresh failed transiently (no response, a 5xx, a 429): nothing was refused and the
465
+ // session is kept. connectionParams lets that
466
+ // throw reach graphql-ws, which reports it here first and then closes the socket with
467
+ // 4005; answering false made every subscription on the area error out over an outage of
468
+ // the identity service, and nothing reopened them. It is retried like a dropped socket,
469
+ // with the same back-off. A refused refresh is not transient: the session ends, the next
470
+ // connect carries no token, and the server's 4401 at connect is surfaced as before.
471
+ shouldRetry: (err) => typeof Event != "undefined" && err instanceof Event || hasCode(err) || isTransientRefreshError(err)
472
+ });
473
+ const state = { client, acked: false, lastCloseWasAcked: false };
474
+ client.on("connecting", () => {
475
+ state.acked = false;
476
+ });
477
+ client.on("connected", () => {
478
+ state.acked = true;
479
+ });
480
+ client.on("closed", () => {
481
+ state.lastCloseWasAcked = state.acked;
482
+ state.acked = false;
483
+ });
484
+ entry = state;
485
+ clients.set(area, entry);
486
+ }
487
+ return entry;
488
+ }
489
+ function hasCode(err) {
490
+ return typeof err === "object" && err !== null && "code" in err;
491
+ }
492
+ function isUnauthorizedClose(err) {
493
+ return hasCode(err) && err.code === CLOSE_UNAUTHORIZED;
494
+ }
495
+ function subscribe(area, document, variables, sink) {
496
+ const entry = clientFor(area);
497
+ const { client } = entry;
498
+ let reauth = false;
499
+ const disposers = [];
500
+ if (sink.connected) {
501
+ disposers.push(
502
+ client.on("connected", (_socket, _payload, wasRetry) => {
503
+ const retried = wasRetry || reauth;
504
+ reauth = false;
505
+ sink.connected(retried);
506
+ })
507
+ );
508
+ }
509
+ if (sink.closed) {
510
+ disposers.push(client.on("closed", () => sink.closed()));
511
+ }
512
+ const payload = {
513
+ query: document.toString(),
514
+ variables
515
+ };
516
+ let disposed = false;
517
+ let current = null;
518
+ const start = () => {
519
+ const previous = current;
520
+ current = client.subscribe(payload, {
521
+ next: (result) => {
522
+ if (result.errors?.length) sink.errors?.(result.errors);
523
+ if (result.data != null) sink.next(result.data);
524
+ },
525
+ error: (err) => {
526
+ if (disposed) return;
527
+ if (isUnauthorizedClose(err) && entry.lastCloseWasAcked) {
528
+ reauth = true;
529
+ start();
530
+ return;
531
+ }
532
+ sink.error?.(err);
533
+ },
534
+ complete: () => sink.complete?.()
535
+ });
536
+ previous?.();
537
+ };
538
+ start();
539
+ disposers.push(() => {
540
+ disposed = true;
541
+ current?.();
542
+ });
543
+ return () => {
544
+ for (const dispose of disposers) dispose();
545
+ };
546
+ }
547
+ function disposeSubscriptions() {
548
+ for (const { client } of clients.values()) {
549
+ void client.dispose();
550
+ }
551
+ clients.clear();
552
+ }
553
+
449
554
  // src/tokens.ts
450
555
  var READABLE_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
451
556
  var DIGITS = "0123456789";
@@ -580,6 +685,7 @@ export {
580
685
  isForbiddenError,
581
686
  isScopeUnsupportedError,
582
687
  isScoped,
688
+ isStaleWrite,
583
689
  isValidToken,
584
690
  maskToRegExp,
585
691
  normalizeToken,
@@ -592,6 +698,7 @@ export {
592
698
  scopeAnchorRefs,
593
699
  setAuthTokenGetter,
594
700
  setIdentityTokenGetter,
701
+ setUnauthorizedHandler,
595
702
  subscribe,
596
703
  validateMask
597
704
  };
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/transport.ts", "../src/errors.ts", "../src/basemap.ts", "../src/subscribe.ts", "../src/jwt.ts", "../src/session.ts", "../src/tokens.ts"],
4
- "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// A tiny GraphQL-over-fetch client, in the spirit of a REST `fetchJson` helper —\n// no Apollo. Each DeviceChain functional area serves its own /graphql endpoint;\n// `area` selects which one. Requests carry the access-token Bearer when one is\n// available (see setAuthTokenGetter); login/refresh run with no token (the\n// GraphQL handler lets an absent token through with no tenant).\n\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\n\n// DeviceChain functional areas that expose a GraphQL endpoint. An \"area\" ending in\n// `/admin` is a service's instance-scoped admin API (ADR-033), served by that\n// service at a second path and authenticated with the identity token rather than a\n// tenant access token (see the `identity` request option).\n//\n// `ai-inference` has no `/admin` sibling here because it has no tenant-facing\n// surface a console would call: its data plane serves exactly one mutation, reached\n// by event-processing's service token, never by a browser. Its whole console-facing\n// surface is the operator provider list (ADR-065).\n// Declared as a const array with the type derived from it, rather than as a bare\n// union, so the set is enumerable at RUNTIME. That is what lets a test walk every\n// member and check it against the deployment catalog the Helm chart uses — a\n// union alone erases at compile time, leaving the check to a hand-kept copy of\n// this list, which is the drift this whole mechanism exists to prevent.\nexport const AREAS = [\n 'user-management',\n 'user-management/admin',\n 'user-management/settings',\n 'device-management',\n 'event-management',\n 'event-processing',\n 'device-state',\n 'command-delivery',\n 'dashboard-management',\n 'outbound-connectors',\n 'notification-management',\n 'update-management',\n 'ai-inference/admin',\n] as const;\n\nexport type Area = (typeof AREAS)[number];\n\n// Relative URL matching the cluster ingress contract: the ingress routes\n// https://<host>/api/<area>/graphql to each functional-area service and serves\n// the SPA at \"/\". In `vite dev` the same path is handled by the config proxy.\n// 'user-management/admin' resolves to /api/user-management/admin/graphql.\nexport function areaPath(area: Area): string {\n return `/api/${area}/graphql`;\n}\n\n/**\n * The deployed functional area an Area is served by — the segment before the\n * first slash, since a suffix like `/admin` or `/settings` names a PLANE of an\n * area rather than an area of its own.\n *\n * This is the join between an Area (a client-side routing convention) and the\n * area vocabulary the server reports from what the chart actually deployed, so\n * the console can tell \"never deployed here\" apart from a transport failure.\n * Note it is deliberately many-to-one: `user-management`,\n * `user-management/admin` and `user-management/settings` all key to\n * `user-management`, and the reverse direction does not exist — plenty of\n * deployed areas (event-sources, sparkplug-ingest) have no Area member.\n */\nexport function areaKey(area: Area): string {\n return area.split('/')[0];\n}\n\n// Whether an area is served on an instance-scoped lane that authenticates with the\n// IDENTITY token rather than a tenant access token (ADR-033). Those endpoints accept\n// nothing else, so the credential follows from the area and is not a per-call\n// choice: deriving it here means a new admin call cannot silently ride the tenant\n// token and 401 (or, worse, be given a tenant token that some future endpoint\n// accepts). Callers may still pass `identity` explicitly; this is the default, not\n// an override.\nexport function isIdentityArea(area: Area): boolean {\n return area.endsWith('/admin') || area.endsWith('/settings');\n}\n\n// ── Auth token injection ────────────────────────────────────────────────\n//\n// A host (e.g. the console's AuthProvider) registers a getter so the client can\n// attach a fresh access token — refreshing it first if near expiry — without the\n// SDK owning React state or storage.\n\nlet tokenGetter: (() => Promise<string | null>) | null = null;\n\nexport function setAuthTokenGetter(getter: (() => Promise<string | null>) | null) {\n tokenGetter = getter;\n}\n\n// The identity-token getter feeds the admin API (ADR-033): admin requests carry\n// the instance-scoped identity token, not the tenant access token. Registered\n// alongside setAuthTokenGetter; selected per request via the `identity` option.\nlet identityTokenGetter: (() => Promise<string | null>) | null = null;\n\nexport function setIdentityTokenGetter(getter: (() => Promise<string | null>) | null) {\n identityTokenGetter = getter;\n}\n\n// resolveAuthToken returns the current access token (refreshing via the getter),\n// or null. Internal to the SDK — the ws subscribe path (subscribe.ts) reuses it\n// so subscriptions authenticate with the same token as queries.\nexport async function resolveAuthToken(): Promise<string | null> {\n return tokenGetter ? tokenGetter() : null;\n}\n\n// ── Errors ──────────────────────────────────────────────────────────────\n\nexport class GraphQLRequestError extends Error {\n constructor(\n message: string,\n /** HTTP status, or 0 for a transport-level failure. */\n public status: number,\n /** The raw `errors` array from a GraphQL response, when present. */\n public errors?: GraphQLErrorEntry[],\n ) {\n super(message);\n this.name = 'GraphQLRequestError';\n }\n}\n\n/**\n * One entry of a GraphQL response's `errors` array. `extensions` carries the server's\n * machine-readable detail when it sends any — for example `code: \"THROTTLED\"` with\n * `retryAfterSeconds` on a sign-in refused by the per-account backoff — so a caller can\n * branch on a code instead of matching the message text.\n */\nexport interface GraphQLErrorEntry {\n message: string;\n extensions?: Record<string, unknown>;\n}\n\ninterface GraphQLResponse<T> {\n data?: T;\n errors?: GraphQLErrorEntry[];\n}\n\nexport interface RequestOptions {\n /** Skip attaching the Bearer token (login / refresh run unauthenticated). */\n anonymous?: boolean;\n /**\n * Authenticate with the identity token instead of the tenant access token —\n * for the instance-scoped admin API (ADR-033). Ignored when `anonymous`.\n *\n * Rarely needed: an `/admin` or `/settings` area defaults to the identity token\n * already (see isIdentityArea). Pass it only to force the lane for an area whose\n * name does not say so.\n */\n identity?: boolean;\n}\n\n// A GraphQL document tagged with its result/variable types — what gql()/subscribe()\n// accept. A code-generated `TypedDocumentString` (client preset) satisfies it, and\n// so does a hand-authored query string cast to it: the SDK runs in documentMode\n// 'string', calling only `toString()` to get the query text, so the phantom result\n// (`TResult`) and variable (`TVariables`) generics are all that distinguish them.\n// Exported so packages/apps without codegen (dashboards, widgets, the dash app)\n// hand-author typed documents against one shared alias instead of re-inlining it.\nexport type TypedDocument<TResult, TVariables> = DocumentTypeDecoration<TResult, TVariables> & {\n toString(): string;\n};\n\n// `document` is a code-generated typed document (a `TypedDocumentString` from the\n// GraphQL Code Generator client preset). It implements\n// `DocumentTypeDecoration<TResult, TVariables>`, which carries the result and\n// variable types as phantom generics, and stringifies (via `toString()`) to the\n// raw query text the server expects. The structural `& { toString(): string }`\n// keeps this accepting a document from ANY service while still inferring both the\n// result (`TResult`) and the variables (`TVariables`).\nexport async function gql<TResult, TVariables>(\n area: Area,\n document: TypedDocument<TResult, TVariables>,\n ...[variables, options]: TVariables extends Record<string, never>\n ? [variables?: undefined, options?: RequestOptions]\n : [variables: TVariables, options?: RequestOptions]\n): Promise<TResult> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\n if (!options?.anonymous) {\n const useIdentity = options?.identity ?? isIdentityArea(area);\n const getter = useIdentity ? identityTokenGetter : tokenGetter;\n if (getter) {\n const token = await getter();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n }\n\n let res: Response;\n try {\n res = await fetch(areaPath(area), {\n method: 'POST',\n headers,\n body: JSON.stringify({ query: document.toString(), variables }),\n });\n } catch (err) {\n throw new GraphQLRequestError(\n err instanceof Error ? err.message : 'Network request failed',\n 0,\n );\n }\n\n if (!res.ok) {\n throw new GraphQLRequestError(`Request failed (${res.status})`, res.status);\n }\n\n const body = (await res.json()) as GraphQLResponse<TResult>;\n if (body.errors && body.errors.length > 0) {\n throw new GraphQLRequestError(body.errors[0].message, res.status, body.errors);\n }\n if (body.data === undefined) {\n throw new GraphQLRequestError('Empty GraphQL response', res.status);\n }\n return body.data;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Classification of transport failures a caller has to render differently.\n//\n// Most errors are one shape to a screen (\"something went wrong\"), but a refusal\n// is not: \"you may not see this\" and \"this could not be loaded\" call for\n// different copy, and collapsing them makes a permission boundary look like an\n// outage.\n//\n// This lives beside GraphQLRequestError rather than in a host app because more\n// than one consumer needs it: the console renders a device's position panel from\n// it, and the dashboard runtime's location channel turns the same refusal into a\n// first-class snapshot state (location:read is deliberately outside the read-only\n// viewer baseline, so being refused is an ordinary state rather than a fault).\n\nimport { GraphQLRequestError } from './transport';\n\n// The backend's authorization gate returns core/auth's ErrForbidden, whose text\n// is \"forbidden: missing required authority\"; graphql-go surfaces a resolver\n// error verbatim as the entry's `message`, over HTTP 200. Anchoring the match at\n// the START of the message keeps it from firing on an unrelated error that\n// merely mentions the word (an entity literally named \"forbidden-zone\", say).\nconst FORBIDDEN_PREFIX = /^forbidden\\b/i;\n\n/**\n * True when the server REFUSED the request for lack of an authority, as opposed\n * to failing it. Callers use this to render a permission state rather than an\n * error state.\n */\nexport function isForbiddenError(err: unknown): boolean {\n // A subscription's refusal arrives from graphql-ws as the bare list of GraphQL errors, not\n // wrapped in a GraphQLRequestError; it is the same refusal and reads the same way.\n if (Array.isArray(err)) return err.some(isForbiddenEntry);\n if (!(err instanceof GraphQLRequestError)) return false;\n // A transport-level 403 counts even with no GraphQL body to read.\n if (err.status === 403) return true;\n // The server names the refusal by code (FORBIDDEN, with a reason such as\n // SCOPE_UNSUPPORTED for a member limited to part of the tenant); the message match\n // below stays for a server that predates the code.\n if (err.errors?.some((e) => e.extensions?.code === 'FORBIDDEN')) return true;\n const messages = err.errors?.length ? err.errors.map((e) => e.message) : [err.message];\n return messages.some((m) => FORBIDDEN_PREFIX.test(m.trim()));\n}\n\n// One entry of a GraphQL error list: refused by code, or (from a server that predates the code)\n// by the message prefix.\nfunction isForbiddenEntry(e: unknown): boolean {\n if (!e || typeof e !== 'object') return false;\n const entry = e as { message?: unknown; extensions?: { code?: unknown } };\n if (entry.extensions?.code === 'FORBIDDEN') return true;\n return typeof entry.message === 'string' && FORBIDDEN_PREFIX.test(entry.message.trim());\n}\n\n/**\n * True when the server refused the request because the caller is a member limited to part\n * of the tenant (a customer user) and the operation is not offered to such members at all\n * (`FORBIDDEN` with reason `SCOPE_UNSUPPORTED`). Distinct from an ordinary refusal: nothing\n * the member could be granted inside their scope would change the answer, so a caller\n * renders \"not available for customer users\" rather than \"you do not have access\".\n */\nexport function isScopeUnsupportedError(err: unknown): boolean {\n if (!(err instanceof GraphQLRequestError)) return false;\n return (err.errors ?? []).some(\n (e) => e.extensions?.code === 'FORBIDDEN' && e.extensions?.reason === 'SCOPE_UNSUPPORTED',\n );\n}\n\n/**\n * The machine-readable code the server put on a refusal (`extensions.code` of the first\n * error that carries one), such as `NOT_FOUND`, `CONFLICT`, `ESCALATION` or `LAST_ADMIN`;\n * null when the error carries none or is not a GraphQL response at all. Branch on this,\n * never on the message text.\n */\nexport function errorCode(err: unknown): string | null {\n if (!(err instanceof GraphQLRequestError)) return null;\n for (const e of err.errors ?? []) {\n const code = e.extensions?.code;\n if (typeof code === 'string' && code) return code;\n }\n return null;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The client half of the basemap cascade (ADR-079).\n//\n// The SERVER resolves a tenant's override over the operator's instance default and\n// hands back one effective value. This module resolves the last tier — a per-surface\n// override, set on the widget or held as a personal preference in the browser — over\n// that tenant value, and turns the result into something a renderer can use.\n//\n// It lives in the SDK rather than in either app because THREE surfaces need the\n// identical answer: the console's geofence editor, the dashboard map widget, and the\n// `/dash` viewer app, which has its own login and would otherwise be the one place\n// that quietly disagrees.\n\n/** A basemap at any tier: the tile source, and a fallback view. */\nexport interface Basemap {\n tileUrl?: string | null;\n attribution?: string | null;\n centerLat?: number | null;\n centerLon?: number | null;\n zoom?: number | null;\n}\n\n/** A resolved basemap that definitely has a tile source, so a renderer can draw it. */\nexport interface ResolvedBasemap {\n tileUrl: string;\n attribution: string | null;\n centerLat: number | null;\n centerLon: number | null;\n zoom: number | null;\n}\n\n/** Treat blank and whitespace-only strings as unset — an emptied form field means \"inherit\". */\nfunction text(v: string | null | undefined): string | null {\n if (typeof v !== 'string') return null;\n const trimmed = v.trim();\n return trimmed === '' ? null : trimmed;\n}\n\nfunction num(v: number | null | undefined): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n\n/**\n * Fold a per-surface override over the tenant's effective basemap.\n *\n * 🔴 The TILE SOURCE is atomic, exactly as it is on the server. If the override names\n * a tile URL, its attribution comes from the override too — never from the tenant. A\n * per-field fold would credit the tenant's provider for the override's tiles, which\n * is a licence violation manufactured by the merge rather than a cosmetic mismatch.\n * This is the same rule as basemap.Merge in user-management, and it has to be\n * restated here because this tier never reaches the server.\n *\n * The camera folds per field: a widget that only wants to open closer in should not\n * have to restate a provider to keep it.\n */\nexport function resolveBasemap(override: Basemap | null | undefined, tenant: Basemap | null | undefined): Basemap {\n const o = override ?? {};\n const t = tenant ?? {};\n\n // 🔴 AN INCOMPLETE OVERRIDE IS NOT AN OVERRIDE. A tile URL with no credit line is\n // refused outright by the server at the tenant and instance tiers — the two halves\n // are stored as one value or not at all — but THIS tier never reaches the server: a\n // widget's own options and the fence editor's browser-local fields are entered\n // client-side and rendered directly.\n //\n // Without this the atomic fold below did its job and still produced the defect it\n // exists to prevent: it correctly refused to lend the tenant's credit line to the\n // override's tiles, and then drew those tiles with NO credit line at all. Correct\n // about the cross-crediting, wrong about the licence.\n //\n // So an override naming tiles without their attribution is discarded whole, and the\n // surface falls back to the tenant's properly-credited basemap. Failing closed to a\n // map that is credited beats honouring a preference that cannot legally be shown.\n //\n // On an ordinary instance the fallback is a real map, because a shipped default\n // means some tier below almost always has one. On an instance whose operator\n // deliberately stored `{}` there is nothing below, and the surface falls through to\n // the bundled schematic world — which is the correct outcome for the same reason,\n // just a less pretty one.\n const overrideAttribution = text(o.attribution);\n const overrideTiles = overrideAttribution === null ? null : text(o.tileUrl);\n const tileUrl = overrideTiles ?? text(t.tileUrl);\n const attribution = overrideTiles ? overrideAttribution : text(t.attribution);\n\n // Latitude and longitude move as a pair for the same reason: half a coordinate\n // from each tier names a point neither one chose.\n const hasOverrideCentre = num(o.centerLat) !== null || num(o.centerLon) !== null;\n const centerLat = hasOverrideCentre ? num(o.centerLat) : num(t.centerLat);\n const centerLon = hasOverrideCentre ? num(o.centerLon) : num(t.centerLon);\n\n return {\n tileUrl,\n attribution,\n centerLat,\n centerLon,\n zoom: num(o.zoom) ?? num(t.zoom),\n };\n}\n\n/**\n * Narrow a folded basemap to one that can actually be rendered, or null.\n *\n * A basemap with a camera but no tile source is legitimate — an operator may set a\n * starting view before choosing a provider — but there is nothing to draw, and the\n * caller should say so rather than request tiles from an empty URL.\n */\nexport function renderableBasemap(b: Basemap | null | undefined): ResolvedBasemap | null {\n const tileUrl = text(b?.tileUrl);\n if (!tileUrl) return null;\n return {\n tileUrl,\n attribution: text(b?.attribution),\n centerLat: num(b?.centerLat),\n centerLon: num(b?.centerLon),\n zoom: num(b?.zoom),\n };\n}\n\n/**\n * The fallback view a surface opens at when it has nothing of its own to fit to.\n *\n * 🔴 A FALLBACK, never an override (ADR-079 §5). A surface with real content — an\n * existing fence's ring, a widget's markers — fits that and ignores this entirely.\n * Returns null when no tier declared a centre, so the caller keeps its own default\n * rather than being moved to 0,0.\n */\nexport function fallbackView(b: Basemap | null | undefined): { center: [number, number]; zoom: number | null } | null {\n const lat = num(b?.centerLat);\n const lon = num(b?.centerLon);\n if (lat === null || lon === null) return null;\n return { center: [lon, lat], zoom: num(b?.zoom) };\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// GraphQL subscriptions over the graphql-transport-ws protocol (ADR-037) — the\n// live half of the client wire, consumed by dashboards (the ADR-039 Hub) for\n// live telemetry. The backend serves subscriptions on the same /api/<area>/graphql\n// path via a WebSocket upgrade; a client derives the ws:// URL from the http one.\n//\n// This is the low-level SDK primitive: one lazily-created graphql-ws client per\n// area (connection reuse), and a subscribe() that binds a typed document to a\n// sink. The dashboard Hub layers subscription multiplexing on top (many widgets,\n// one connection).\n//\n// The server accepts only SUBSCRIPTION operations on this socket — queries and\n// mutations go over HTTP — and it closes the socket with 4401 when the access token\n// it authenticated with expires. subscribe() handles that close itself: when a\n// socket that had been acknowledged is closed with 4401, it re-issues the operation\n// once, which opens a new socket whose connection_init carries a freshly resolved\n// token, and reports the reconnect to the sink as connected(true) so a consumer\n// re-queries whatever it may have missed. graphql-ws treats 4401 as fatal and does\n// not retry it on its own. Any other dropped socket is retried for as long as the\n// operation is wanted, with a capped, jittered back-off (clientFor).\n\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\nimport { createClient, type Client } from 'graphql-ws';\n\nimport { areaPath, resolveAuthToken, type Area } from './transport';\n\n// The graphql-transport-ws close code for an unauthorized connection. Mid-session\n// it means the token the socket authenticated with has expired.\nconst CLOSE_UNAUTHORIZED = 4401;\n\n// wsUrl builds the absolute ws(s):// URL for an area from the current origin,\n// mirroring the relative http path so dev proxy and prod ingress both work.\nfunction wsUrl(area: Area): string {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}${areaPath(area)}`;\n}\n\n// An area's shared graphql-ws client, plus what subscribe() needs to know about its\n// socket to decide whether a 4401 close is worth one re-subscribe.\ninterface AreaClient {\n client: Client;\n // The current socket has received connection_ack.\n acked: boolean;\n // The most recently closed socket had been acknowledged. A 4401 on an\n // acknowledged socket is an expiry mid-session, which a fresh token cures; a 4401\n // on one that was never acknowledged is the server refusing the token presented\n // at connect, which re-subscribing would only repeat.\n lastCloseWasAcked: boolean;\n}\n\n// The longest wait between two reconnect attempts. graphql-ws doubles its wait on each\n// attempt, so without a ceiling an outage of a few minutes would push the next attempt\n// hours away.\nexport const RETRY_CEILING_MS = 30_000;\n\n// retryDelayMs is the wait before reconnect attempt `retries` (0-based): doubling from one\n// second up to RETRY_CEILING_MS, then a random point in the upper half of that. The random\n// half spreads out every screen that lost the same server at the same moment, so they do\n// not all come back on the same tick; the fixed half keeps attempts from bunching near zero.\nexport function retryDelayMs(retries: number, random: () => number = Math.random): number {\n const ceiling = Math.min(1000 * 2 ** retries, RETRY_CEILING_MS);\n return (ceiling / 2) * (1 + random());\n}\n\n// One graphql-ws client per area — the WebSocket (and its connection_init auth)\n// is reused across every subscription to that area. connectionParams is a\n// function so the token is re-resolved on each (re)connect, surviving refresh.\nconst clients = new Map<Area, AreaClient>();\n\nfunction clientFor(area: Area): AreaClient {\n let entry = clients.get(area);\n if (!entry) {\n const client = createClient({\n url: wsUrl(area),\n connectionParams: async () => {\n const token = await resolveAuthToken();\n return token ? { Authorization: `Bearer ${token}` } : {};\n },\n // 🔴 Keep reconnecting for as long as anything is subscribed. Left to its defaults,\n // graphql-ws gives up after 5 attempts (about 40 s; in a browser, after the first one\n // that fails, see shouldRetry) and then errors every operation, and nothing reopened\n // them: a wall display that lost its network for a minute showed\n // \"Data unavailable\" until someone reloaded it. One socket per area carries every\n // operation, so each attempt is ONE connection however many widgets are waiting, and\n // graphql-ws resubscribes all of them on it once it is acknowledged.\n retryAttempts: Infinity,\n retryWait: (retries) => new Promise((resolve) => setTimeout(resolve, retryDelayMs(retries))),\n // graphql-ws retries only close events by default, and a browser reports a handshake\n // that failed (the server or the network still down) as an `error` event first, so\n // the first failed attempt would end every operation however many were allowed. A\n // socket's own error event is a network problem and is retried; an Error thrown in\n // this client is not. The closes that say the request itself is wrong (4400, 4401,\n // 4409, 4429) are fatal inside graphql-ws whatever this answers, so an expired or\n // refused token still reaches subscribe() below and the session flow, never a loop.\n shouldRetry: (err) => (typeof Event != 'undefined' && err instanceof Event) || hasCode(err),\n });\n const state: AreaClient = { client, acked: false, lastCloseWasAcked: false };\n // Registered once, here, before any subscription can register its own — so on a\n // close this runs first and every sink's error handler (which graphql-ws delivers\n // later, through a rejected promise) reads the same lastCloseWasAcked. That holds\n // even after the first of them re-subscribes and a new socket starts connecting.\n client.on('connecting', () => {\n state.acked = false;\n });\n client.on('connected', () => {\n state.acked = true;\n });\n client.on('closed', () => {\n state.lastCloseWasAcked = state.acked;\n state.acked = false;\n });\n entry = state;\n clients.set(area, entry);\n }\n return entry;\n}\n\n// hasCode reports whether a graphql-ws error is a close event (anything with a close code).\nfunction hasCode(err: unknown): err is { code: unknown } {\n return typeof err === 'object' && err !== null && 'code' in err;\n}\n\n// isUnauthorizedClose reports whether a graphql-ws sink error is a 4401 close event.\nfunction isUnauthorizedClose(err: unknown): boolean {\n return hasCode(err) && err.code === CLOSE_UNAUTHORIZED;\n}\n\nexport interface SubscriptionSink<T> {\n next: (data: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n // Connection-level signals for the shared per-area socket, distinct from the\n // per-operation next/error/complete above. `connected` fires on each successful\n // connection_ack — `wasRetry` distinguishes a reconnect (after a dropped socket,\n // or after the server closed an expired session) from the first connect; `closed`\n // fires on each socket close (graphql-ws then auto-retries a transient close). A\n // consumer that only needs data can omit both; a live-status indicator uses them\n // to tell \"connected but idle\" from \"offline\", and a consumer that must not miss\n // events re-queries on connected(true).\n connected?: (wasRetry: boolean) => void;\n closed?: () => void;\n}\n\n// subscribe binds a typed subscription document to a sink and returns an\n// unsubscribe function. The document is the same code-generated typed document\n// the query path uses, so the result type is inferred; it must be a subscription,\n// since the server refuses anything else on this socket. Errors from the operation\n// (or the socket) surface via sink.error; normal termination via sink.complete. A\n// 4401 close of an acknowledged socket — the server ending an expired session — is\n// not surfaced: the operation is re-issued once on a new socket with a fresh token.\nexport function subscribe<TResult, TVariables>(\n area: Area,\n document: DocumentTypeDecoration<TResult, TVariables> & { toString(): string },\n variables: TVariables extends Record<string, never> ? undefined : TVariables,\n sink: SubscriptionSink<TResult>,\n): () => void {\n const entry = clientFor(area);\n const { client } = entry;\n // Set when this operation is re-issued after an expiry, so the next connection_ack\n // reaches the sink as a reconnect: graphql-ws itself reports it as a first connect,\n // because a fatal close ends its retry state.\n let reauth = false;\n // Client-level connection events are registered per subscribe() and torn down with\n // it, alongside the operation itself, so a single dispose() call releases both.\n const disposers: Array<() => void> = [];\n if (sink.connected) {\n disposers.push(\n client.on('connected', (_socket, _payload, wasRetry) => {\n const retried = wasRetry || reauth;\n reauth = false;\n sink.connected!(retried);\n }),\n );\n }\n if (sink.closed) {\n disposers.push(client.on('closed', () => sink.closed!()));\n }\n\n const payload = {\n query: document.toString(),\n variables: variables as Record<string, unknown> | undefined,\n };\n let disposed = false;\n let current: (() => void) | null = null;\n const start = (): void => {\n const previous = current;\n current = client.subscribe<TResult>(payload, {\n next: (result) => {\n if (result.data != null) sink.next(result.data);\n },\n error: (err) => {\n if (disposed) return;\n if (isUnauthorizedClose(err) && entry.lastCloseWasAcked) {\n reauth = true;\n start();\n return;\n }\n sink.error?.(err);\n },\n complete: () => sink.complete?.(),\n });\n // Release the ended operation only once its replacement holds the client, so the\n // client's count of live operations never touches zero in between (graphql-ws\n // does not release an operation that ended in a fatal close by itself).\n previous?.();\n };\n start();\n disposers.push(() => {\n disposed = true;\n current?.();\n });\n return () => {\n for (const dispose of disposers) dispose();\n };\n}\n\n// disposeSubscriptions tears down every cached area client (their sockets). A\n// host calls this on sign-out so a stale token's socket does not linger.\nexport function disposeSubscriptions(): void {\n for (const { client } of clients.values()) {\n void client.dispose();\n }\n clients.clear();\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Client-side decode of the DeviceChain access token (ADR-008 JWT). This reads\n// the payload for display + routing only; it does NOT verify the signature —\n// every protected operation is still enforced server-side by the token's\n// authorities. Never trust these claims for authorization decisions beyond what\n// the UI shows.\n\nexport interface DecodedClaims {\n /** Tenant the subject acts within (authoritative server-side). */\n tenant: string;\n /** Human-readable subject identifier. */\n username: string;\n /** Assigned role names — display/audit only; enforcement is on authorities. */\n roles: string[];\n /** Effective capabilities (e.g. \"device:write\", or \"*\" for super-authority). */\n authorities: string[];\n /** \"access\" | \"refresh\". */\n typ: string;\n /** Expiry, epoch seconds (from the standard `exp` claim). */\n exp?: number;\n /** Issue time, epoch seconds (from the standard `iat` claim). */\n iat?: number;\n /**\n * The membership's scope, from the `scp` claim: anchors such as `customer:acme` that\n * limit the subject to part of the tenant. Empty when the subject sees the whole tenant.\n *\n * Deliberately NOT named `scope`: an OAuth access token carries its own `scope` claim (a\n * space-separated grant string), and the two mean unrelated things. Optional so a\n * hand-built claims object (a test fixture, an older caller) still type-checks; an\n * absent value means the same as an empty one.\n */\n scopeAnchors?: string[];\n}\n\n/** One anchor of a scope, split into its kind and token. */\nexport interface ScopeAnchorRef {\n /** `customer` or `group`. */\n kind: string;\n token: string;\n}\n\nfunction base64UrlDecode(segment: string): string {\n const padded = segment.replace(/-/g, '+').replace(/_/g, '/');\n const json = atob(padded);\n // Handle UTF-8 payloads.\n return decodeURIComponent(\n Array.prototype.map\n .call(json, (c: string) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n}\n\n/** Decode a JWT's payload, or null if it is malformed. */\nexport function decodeToken(token: string): DecodedClaims | null {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1]));\n return {\n tenant: payload.tenant ?? '',\n username: payload.username ?? '',\n roles: payload.roles ?? [],\n authorities: payload.authorities ?? [],\n typ: payload.typ ?? '',\n exp: payload.exp,\n iat: payload.iat,\n scopeAnchors: Array.isArray(payload.scp) ? payload.scp.filter((a: unknown) => typeof a === 'string') : [],\n };\n } catch {\n return null;\n }\n}\n\n/** True if the token is missing, malformed, or within `skewSeconds` of expiry. */\nexport function isExpired(token: string, skewSeconds = 30): boolean {\n const claims = decodeToken(token);\n if (!claims || claims.exp === undefined) return true;\n const nowSeconds = Date.now() / 1000;\n return claims.exp - skewSeconds <= nowSeconds;\n}\n\n/** True if the claims grant the authority (the super-authority \"*\" passes all). */\nexport function hasAuthority(claims: DecodedClaims | null, required: string): boolean {\n if (!claims) return false;\n return claims.authorities.some((a) => a === '*' || a === required);\n}\n\n/**\n * True when the claims limit the subject to part of the tenant (a non-empty `scp`). The\n * server enforces the scope on every request; this only lets a client stop offering what\n * the server would refuse.\n */\nexport function isScoped(claims: DecodedClaims | null): boolean {\n return (claims?.scopeAnchors?.length ?? 0) > 0;\n}\n\n/**\n * The claims' scope anchors split into kind and token (`customer:acme` → customer/acme).\n * An anchor with no `:` is dropped rather than guessed at.\n */\nexport function scopeAnchorRefs(claims: DecodedClaims | null): ScopeAnchorRef[] {\n return (claims?.scopeAnchors ?? []).flatMap((a) => {\n const i = a.indexOf(':');\n return i > 0 ? [{ kind: a.slice(0, i), token: a.slice(i + 1) }] : [];\n });\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The tenant session's access-token lifecycle, framework-free. A host owns WHERE\n// the token pair lives (React state + localStorage in the console, memory in /dash)\n// and WHAT the refresh call is; this owns WHEN to refresh and how concurrent callers\n// share one refresh:\n//\n// - getAccessToken() returns the held access token while it is comfortably valid,\n// and otherwise refreshes first.\n// - concurrent callers share ONE in-flight refresh. Refresh tokens rotate, so two\n// parallel refreshes would spend the same token twice and the second would fail.\n// - a result that arrives after the session was cleared or replaced is dropped, so a\n// slow refresh can never resurrect a dead session.\n// - a lapsed refresh token, or a DEFINITIVE refresh failure (the server answered and\n// refused: a GraphQL error such as an invalid, revoked or SSO-gated refresh token, or\n// any 4xx but 429), ends the session through onEnd and the caller gets null. The host\n// decides what \"ended\" looks like.\n// - a TRANSIENT refresh failure (no response at all, a 5xx, or a 429) does not end a\n// session whose access token is still valid: the caller is handed that token, and the\n// next call (or the auto-refresh retry below) tries again. Only once the access token\n// has actually expired does a transient failure end the session, since there is then\n// nothing left to authenticate with.\n// - startAutoRefresh() refreshes ahead of expiry without waiting for a caller, and\n// retries a transient failure with jittered exponential backoff until the access\n// token actually expires. A display that only holds a websocket makes no request that\n// would trigger the lazy path, so without this it would sit on a token that is about\n// to expire, and a network blip at the wrong moment would end an unattended session.\n\nimport { isExpired, decodeToken } from './jwt';\nimport { GraphQLRequestError } from './transport';\n\nexport interface TokenPair {\n accessToken: string;\n refreshToken: string;\n}\n\nexport interface SessionTokensOptions {\n /** The held pair, or null when signed out. Must return the same object until it is replaced. */\n read: () => TokenPair | null;\n /** Stores a refreshed pair. */\n apply: (next: TokenPair) => void;\n /** Exchanges a refresh token for a new pair. */\n refresh: (refreshToken: string) => Promise<TokenPair>;\n /**\n * The session can no longer be sustained: the refresh token lapsed (`err` undefined), the\n * server refused the refresh (`err` is what it threw), or transient failures outlasted the\n * access token (`err` is the last one). The host clears its session here.\n */\n onEnd: (err?: unknown) => void;\n /**\n * Refresh this many seconds before the access token expires. Default 30. A larger value\n * gives startAutoRefresh's retries a longer window to ride out a network outage. It is\n * capped at half the token's lifetime (`exp - iat`), so a server configured with short-lived\n * tokens never hands out one that is already due, which would refresh on every call.\n */\n skewSeconds?: number;\n}\n\nexport interface SessionTokens {\n /** A usable access token, refreshing first when it is within the skew of expiry; null when signed out or ended. */\n getAccessToken: () => Promise<string | null>;\n /** Forget any in-flight refresh (the host cleared or replaced the session itself). */\n reset: () => void;\n /**\n * Refresh ahead of expiry on a timer, retrying a transient failure with backoff until the\n * access token expires. Returns a stop function.\n */\n startAutoRefresh: () => () => void;\n}\n\nconst DEFAULT_SKEW_SECONDS = 30;\n// setTimeout stores its delay in a signed 32-bit int; a longer one fires immediately.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n// Auto-refresh retry backoff: 1 s doubling to 30 s, each scaled by a random 50-100 % so a\n// fleet of displays that lost the network together does not come back in lockstep.\nconst RETRY_BASE_MS = 1_000;\nconst RETRY_CAP_MS = 30_000;\n// The last retry is aimed this far ahead of the access token's expiry, not at it. No retry is\n// armed within RETRY_BASE_MS before that aim: one that would be is moved onto it instead.\nconst RETRY_EXPIRY_MARGIN_MS = 1_000;\n// The shortest gap between two scheduled refreshes. A backstop: if the held token still\n// looks due right after a refresh (the device clock runs well ahead of the server's), the\n// timer must not turn into a refresh loop against the server.\nconst MIN_REFRESH_GAP_MS = 10_000;\n\n/**\n * Whether a refresh failure is worth retrying: the request never got a response (status 0),\n * or the server answered 5xx or 429 without a GraphQL error. Anything else (a GraphQL error\n * such as an invalid or revoked refresh token or SSO_REQUIRED, a 400 or 401, or an error that\n * is not a transport error at all) is the server's answer, and asking again would repeat it.\n */\nfunction isTransientRefreshError(err: unknown): boolean {\n if (!(err instanceof GraphQLRequestError)) return false;\n if (err.errors && err.errors.length > 0) return false;\n return err.status === 0 || err.status === 429 || err.status >= 500;\n}\n\ntype Outcome =\n | { kind: 'ok'; token: string }\n | { kind: 'stale' } // the session was cleared or replaced while the refresh ran\n | { kind: 'ended' }\n | { kind: 'transient'; err: unknown };\n\nfunction expiryMs(token: string): number | undefined {\n const exp = decodeToken(token)?.exp;\n return exp === undefined ? undefined : exp * 1000;\n}\n\nexport function createSessionTokens(opts: SessionTokensOptions): SessionTokens {\n const skew = opts.skewSeconds ?? DEFAULT_SKEW_SECONDS;\n let inFlight: Promise<Outcome> | null = null;\n\n // The skew for one access token: the configured one, or half its lifetime if that is less.\n const skewFor = (token: string): number => {\n const c = decodeToken(token);\n if (c?.exp === undefined || c.iat === undefined) return skew;\n return Math.min(skew, Math.max(0, (c.exp - c.iat) / 2));\n };\n const due = (token: string): boolean => isExpired(token, skewFor(token));\n\n const end = (err?: unknown) => {\n inFlight = null;\n opts.onEnd(err);\n };\n\n // One refresh of `current`, shared by every caller that asks while it runs.\n const refreshShared = (current: TokenPair): Promise<Outcome> => {\n if (!inFlight) {\n inFlight = (async (): Promise<Outcome> => {\n try {\n const pair = await opts.refresh(current.refreshToken);\n // A promise cannot be cancelled, so guard here: if the live session is no\n // longer the one this refresh started from, drop the result.\n if (opts.read() !== current) return { kind: 'stale' };\n opts.apply({ accessToken: pair.accessToken, refreshToken: pair.refreshToken });\n return { kind: 'ok', token: pair.accessToken };\n } catch (err) {\n // Only end the session this refresh belonged to, not one since replaced.\n if (opts.read() !== current) return { kind: 'stale' };\n if (isTransientRefreshError(err)) return { kind: 'transient', err };\n end(err);\n return { kind: 'ended' };\n } finally {\n inFlight = null;\n }\n })();\n }\n return inFlight;\n };\n\n const getAccessToken = async (): Promise<string | null> => {\n const current = opts.read();\n if (!current) return null;\n if (isExpired(current.refreshToken, 0)) {\n end();\n return null;\n }\n if (!due(current.accessToken)) return current.accessToken;\n\n const out = await refreshShared(current);\n if (out.kind === 'ok') return out.token;\n if (out.kind !== 'transient') return null;\n // A transient failure: the held token is still good if it has not actually expired.\n if (opts.read() !== current) return null;\n if (!isExpired(current.accessToken, 0)) return current.accessToken;\n end(out.err);\n return null;\n };\n\n const startAutoRefresh = (): (() => void) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stopped = false;\n let failures = 0;\n\n const arm = (delay: number) => {\n timer = setTimeout(() => void fire(), Math.min(Math.max(0, delay), MAX_TIMER_MS));\n };\n\n // Arm for the next refresh of whatever pair is held now, no sooner than `floor` ms.\n const schedule = (floor = 0) => {\n if (stopped) return;\n const current = opts.read();\n const exp = current ? expiryMs(current.accessToken) : undefined;\n if (!current || exp === undefined) return; // signed out, or nothing to time against\n arm(Math.max(floor, exp - skewFor(current.accessToken) * 1000 - Date.now()));\n };\n\n const fire = async () => {\n if (stopped) return;\n const current = opts.read();\n if (!current) return;\n if (isExpired(current.refreshToken, 0)) {\n end();\n return;\n }\n // Someone else refreshed already (a request took the lazy path): time against that.\n if (!due(current.accessToken)) {\n failures = 0;\n schedule(MIN_REFRESH_GAP_MS);\n return;\n }\n const out = await refreshShared(current);\n if (stopped) return;\n if (out.kind === 'ok') {\n failures = 0;\n schedule(MIN_REFRESH_GAP_MS);\n return;\n }\n if (out.kind !== 'transient') return; // ended, or the host replaced the session\n if (opts.read() !== current) return;\n\n const left = (expiryMs(current.accessToken) ?? 0) - RETRY_EXPIRY_MARGIN_MS - Date.now();\n if (left <= 0) {\n end(out.err);\n return;\n }\n const backoff = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** failures) * (0.5 + Math.random() / 2);\n failures++;\n // A retry that would land within RETRY_BASE_MS of the final retry's aim (or past it) is\n // moved onto that aim. Otherwise a backoff that happens to land just short of the aim leaves\n // the aimed retry following it moments later: two requests back to back, against a\n // server that may have just answered 429.\n arm(left - backoff < RETRY_BASE_MS ? left : backoff);\n };\n\n schedule();\n return () => {\n stopped = true;\n if (timer !== undefined) clearTimeout(timer);\n };\n };\n\n return {\n getAccessToken,\n reset: () => {\n inFlight = null;\n },\n startAutoRefresh,\n };\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Token masks (ADR-042 P3): the client-side template language that mints, and\n// soft-validates, entity tokens. A mask is literal text plus typed placeholders,\n// and one mask drives three operations:\n//\n// generate fill placeholders to produce a concrete token\n// normalize kebab-case a human string into a {slug}\n// validate does a token conform to the mask's shape (soft, UI-only)\n//\n// Masks are advisory: the backend enforces only the security grammar\n// (isValidToken below mirrors rdb.ValidateToken). Style — lowercase-kebab,\n// prefixes — lives in the mask, applied here in the console, never on the wire.\n\n// The human-readable alphabet for generated ids: lowercase letters + digits minus\n// the ambiguous 0 o 1 l i, so a minted token can be read back off a label without\n// transcription errors.\nconst READABLE_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';\nconst DIGITS = '0123456789';\n\n// The security grammar the backend enforces (rdb.ValidateToken): letters (either\n// case), digits, hyphen and underscore, starting alphanumeric. Kept in sync by\n// hand — the same regex, mirrored for a pre-submit check so the user sees a bad\n// token before the server rejects it.\nconst TOKEN_GRAMMAR = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\n\n/** The maximum token length (mirrors rdb.MaxTokenLen). */\nexport const MAX_TOKEN_LEN = 128;\n\n/** isValidToken mirrors the backend security grammar for a pre-submit check. */\nexport function isValidToken(token: string): boolean {\n return token.length > 0 && token.length <= MAX_TOKEN_LEN && TOKEN_GRAMMAR.test(token);\n}\n\n/** A parsed mask segment: a literal run, or a typed placeholder. */\nexport type MaskSegment =\n | { kind: 'literal'; text: string }\n | { kind: 'placeholder'; type: 'alphanumeric' | 'numeric' | 'slug' | 'uuid' | 'unknown'; n?: number; raw: string };\n\nconst PLACEHOLDER = /\\{([a-zA-Z]+)(?:-(\\d+))?\\}/g;\nconst KNOWN = ['alphanumeric', 'numeric', 'slug', 'uuid'] as const;\n\n/** parseMask splits a mask into its literal and placeholder segments. */\nexport function parseMask(mask: string): MaskSegment[] {\n const segments: MaskSegment[] = [];\n let last = 0;\n for (const m of mask.matchAll(PLACEHOLDER)) {\n const at = m.index ?? 0;\n if (at > last) segments.push({ kind: 'literal', text: mask.slice(last, at) });\n const name = m[1].toLowerCase();\n const type = (KNOWN as readonly string[]).includes(name) ? (name as 'alphanumeric') : 'unknown';\n segments.push({ kind: 'placeholder', type, n: m[2] ? parseInt(m[2], 10) : undefined, raw: m[0] });\n last = at + m[0].length;\n }\n if (last < mask.length) segments.push({ kind: 'literal', text: mask.slice(last) });\n return segments;\n}\n\nexport interface GenerateOptions {\n /** A human string (e.g. the entity's name) that fills {slug} placeholders. */\n seed?: string;\n /** Injectable RNG in [0,1) for deterministic tests; defaults to Math.random. */\n random?: () => number;\n /** Injectable uuid for deterministic tests; defaults to crypto.randomUUID. */\n uuid?: () => string;\n}\n\nfunction randomUUID(): string {\n const g = globalThis as { crypto?: { randomUUID?: () => string } };\n if (g.crypto?.randomUUID) return g.crypto.randomUUID();\n // Fallback for environments without Web Crypto (not the console; belt & braces).\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n/**\n * generateToken fills a mask's placeholders to produce a concrete token:\n * {alphanumeric-N} → N readable chars, {numeric-N} → N digits, {uuid} → a uuid,\n * {slug} → the normalized seed (or a short readable id when no seed is given, so\n * a \"regenerate\" button always yields something). Literals pass through.\n */\nexport function generateToken(mask: string, opts: GenerateOptions = {}): string {\n const rand = opts.random ?? Math.random;\n const uuid = opts.uuid ?? randomUUID;\n // 🔴 The width is bounded before it is used. A mask may name any width the\n // regexp matches, and `Array.from({length: 1e20})` THROWS RangeError — which\n // made this function, called during render by the settings editor and by every\n // create form, a way to kill the page from a stored value. No width past\n // MAX_TOKEN_LEN can mint a legal token anyway, so an absurd one contributes\n // nothing rather than exploding. validateMask refuses such a mask outright;\n // this keeps generation safe for a mask stored before it did.\n const pick = (alphabet: string, n: number) =>\n n > MAX_TOKEN_LEN\n ? ''\n : Array.from({ length: n }, () => alphabet[Math.floor(rand() * alphabet.length)]).join('');\n\n return parseMask(mask)\n .map((seg) => {\n if (seg.kind === 'literal') return seg.text;\n switch (seg.type) {\n case 'alphanumeric':\n return pick(READABLE_ALPHABET, seg.n ?? 8);\n case 'numeric':\n return pick(DIGITS, seg.n ?? 4);\n case 'slug':\n return opts.seed ? normalizeToken(opts.seed) : pick(READABLE_ALPHABET, 6);\n case 'uuid':\n return uuid();\n default:\n return ''; // an unknown placeholder contributes nothing to a generated token\n }\n })\n .join('');\n}\n\n/**\n * normalizeToken kebab-cases a human string into a slug: lower-case, spaces and\n * underscores to hyphens, drop anything else, collapse and trim hyphens.\n * \"Ops Overview\" → \"ops-overview\".\n */\nexport function normalizeToken(input: string): string {\n return trimHyphens(\n input\n .toLowerCase()\n .trim()\n .replace(/[\\s_]+/g, '-')\n .replace(/[^a-z0-9-]+/g, '')\n .replace(/-+/g, '-'),\n );\n}\n\n/** Strips leading and trailing hyphens in linear time (no backtracking pattern). */\nfunction trimHyphens(s: string): string {\n let start = 0;\n let end = s.length;\n while (start < end && s.charCodeAt(start) === 45) start++;\n while (end > start && s.charCodeAt(end - 1) === 45) end--;\n return s.slice(start, end);\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * maskToRegExp compiles a mask into a whole-string RegExp for soft, UI-only\n * conformance checking. It is intentionally lenient (accepts either case in\n * alphanumeric/uuid segments) — the backend, not this, is the authority.\n */\nexport function maskToRegExp(mask: string): RegExp {\n const body = parseMask(mask)\n .map((seg) => {\n if (seg.kind === 'literal') return escapeRegExp(seg.text);\n switch (seg.type) {\n case 'alphanumeric':\n return `[A-Za-z0-9]{${seg.n ?? 8}}`;\n case 'numeric':\n return `[0-9]{${seg.n ?? 4}}`;\n case 'slug':\n return `[a-z0-9]+(?:-[a-z0-9]+)*`;\n case 'uuid':\n return `[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`;\n default:\n return escapeRegExp(seg.raw); // unknown placeholder must match itself literally\n }\n })\n .join('');\n return new RegExp(`^${body}$`);\n}\n\n/** conformsToMask reports whether a token matches the mask's shape (soft check). */\nexport function conformsToMask(mask: string, token: string): boolean {\n return maskToRegExp(mask).test(token);\n}\n\n/** The fixed seed sampleToken fills {slug} placeholders from. */\nconst SAMPLE_SEED = 'Sample Name';\n\n/**\n * sampleToken generates the token a mask would mint, deterministically. Same\n * generator as generateToken — a pinned RNG and uuid rather than a second\n * implementation, so a sample can never disagree with what a create form\n * actually produces.\n */\nexport function sampleToken(mask: string, seed: string = SAMPLE_SEED): string {\n return generateToken(mask, {\n seed,\n random: () => 0,\n uuid: () => '3f2b8c14-9d7e-4a51-b6c2-0e8d5a1f7b93',\n });\n}\n\n/**\n * Why a mask cannot mint usable tokens. Structured rather than a message\n * because this package is consumed by localized apps — the caller maps a reason\n * to its own wording.\n */\nexport type MaskProblem =\n | { reason: 'empty' }\n | { reason: 'unknownPlaceholder'; placeholder: string }\n | { reason: 'noPlaceholder' }\n | { reason: 'widthTooLarge'; placeholder: string; max: number }\n | { reason: 'invalidToken'; sample: string };\n\n/**\n * validateMask reports why a mask is unusable, or null when it is fine. It\n * mirrors the server (the tokenmask Go package), which is the authority and\n * refuses the same four things — every one of which fails SILENTLY otherwise:\n *\n * empty nothing to mint from\n * unknownPlaceholder contributes nothing, so \"dev-{sulg}\" mints \"dev-\"\n * noPlaceholder every entity mints the SAME token; the second create collides\n * invalidToken the minted sample is not a legal token (a space, a slash…)\n *\n * 🔴 Keep this NO STRICTER than the server. A check the server does not make\n * would refuse a mask the platform accepts, and the operator would have no way\n * to get past it.\n */\nexport function validateMask(mask: string): MaskProblem | null {\n if (mask === '') return { reason: 'empty' };\n let placeholders = 0;\n for (const seg of parseMask(mask)) {\n if (seg.kind !== 'placeholder') continue;\n if (seg.type === 'unknown') return { reason: 'unknownPlaceholder', placeholder: seg.raw };\n // 🔴 Checked BEFORE anything samples the mask. This function is called during\n // render, per keystroke — a width of 5e7 froze the tab for seconds building a\n // string nobody would ever see, and 1e20 threw RangeError and killed the\n // page. Neither reached the `invalidToken` check below, which is where a\n // reader would expect an over-long token to be caught.\n if (seg.n !== undefined && seg.n > MAX_TOKEN_LEN) {\n return { reason: 'widthTooLarge', placeholder: seg.raw, max: MAX_TOKEN_LEN };\n }\n placeholders++;\n }\n if (placeholders === 0) return { reason: 'noPlaceholder' };\n const sample = sampleToken(mask);\n if (!isValidToken(sample)) return { reason: 'invalidToken', sample };\n return null;\n}\n\n/**\n * resolveMask picks the mask for an entity type from a token-masks map, falling\n * back to the \"default\" entry and finally to a bare {slug}.\n */\nexport function resolveMask(masks: Record<string, string>, entityType: string): string {\n return masks[entityType] ?? masks.default ?? '{slug}';\n}\n"],
5
- "mappings": ";AAyBO,IAAM,QAAQ;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,SAAS,MAAoB;AAC3C,SAAO,QAAQ,IAAI;AACrB;AAeO,SAAS,QAAQ,MAAoB;AAC1C,SAAO,KAAK,MAAM,GAAG,EAAE,CAAC;AAC1B;AASO,SAAS,eAAe,MAAqB;AAClD,SAAO,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,WAAW;AAC7D;AAQA,IAAI,cAAqD;AAElD,SAAS,mBAAmB,QAA+C;AAChF,gBAAc;AAChB;AAKA,IAAI,sBAA6D;AAE1D,SAAS,uBAAuB,QAA+C;AACpF,wBAAsB;AACxB;AAKA,eAAsB,mBAA2C;AAC/D,SAAO,cAAc,YAAY,IAAI;AACvC;AAIO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACE,SAEO,QAEA,QACP;AACA,UAAM,OAA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;AACT;AAMO,SAAS,YAAY,OAA+B,YAA4B;AACrF,SAAO,MAAM,UAAU,KAAK,MAAM,WAAW;AAC/C;",
4
+ "sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// A tiny GraphQL-over-fetch client, in the spirit of a REST `fetchJson` helper —\n// no Apollo. Each DeviceChain functional area serves its own /graphql endpoint;\n// `area` selects which one. Requests carry the access-token Bearer when one is\n// available (see setAuthTokenGetter); login/refresh run with no token (the\n// GraphQL handler lets an absent token through with no tenant).\n\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\n\n// DeviceChain functional areas that expose a GraphQL endpoint. An \"area\" ending in\n// `/admin` is a service's instance-scoped admin API (ADR-033), served by that\n// service at a second path and authenticated with the identity token rather than a\n// tenant access token (see the `identity` request option).\n//\n// `ai-inference` has no `/admin` sibling here because it has no tenant-facing\n// surface a console would call: its data plane serves exactly one mutation, reached\n// by event-processing's service token, never by a browser. Its whole console-facing\n// surface is the operator provider list (ADR-065).\n// Declared as a const array with the type derived from it, rather than as a bare\n// union, so the set is enumerable at RUNTIME. That is what lets a test walk every\n// member and check it against the deployment catalog the Helm chart uses — a\n// union alone erases at compile time, leaving the check to a hand-kept copy of\n// this list, which is the drift this whole mechanism exists to prevent.\nexport const AREAS = [\n 'user-management',\n 'user-management/admin',\n 'user-management/settings',\n 'device-management',\n 'event-management',\n 'event-processing',\n 'device-state',\n 'command-delivery',\n 'dashboard-management',\n 'outbound-connectors',\n 'notification-management',\n 'update-management',\n 'ai-inference/admin',\n] as const;\n\nexport type Area = (typeof AREAS)[number];\n\n// Relative URL matching the cluster ingress contract: the ingress routes\n// https://<host>/api/<area>/graphql to each functional-area service and serves\n// the SPA at \"/\". In `vite dev` the same path is handled by the config proxy.\n// 'user-management/admin' resolves to /api/user-management/admin/graphql.\nexport function areaPath(area: Area): string {\n return `/api/${area}/graphql`;\n}\n\n/**\n * The deployed functional area an Area is served by — the segment before the\n * first slash, since a suffix like `/admin` or `/settings` names a PLANE of an\n * area rather than an area of its own.\n *\n * This is the join between an Area (a client-side routing convention) and the\n * area vocabulary the server reports from what the chart actually deployed, so\n * the console can tell \"never deployed here\" apart from a transport failure.\n * Note it is deliberately many-to-one: `user-management`,\n * `user-management/admin` and `user-management/settings` all key to\n * `user-management`, and the reverse direction does not exist — plenty of\n * deployed areas (event-sources, sparkplug-ingest) have no Area member.\n */\nexport function areaKey(area: Area): string {\n return area.split('/')[0];\n}\n\n// Whether an area is served on an instance-scoped lane that authenticates with the\n// IDENTITY token rather than a tenant access token (ADR-033). Those endpoints accept\n// nothing else, so the credential follows from the area and is not a per-call\n// choice: deriving it here means a new admin call cannot silently ride the tenant\n// token and 401 (or, worse, be given a tenant token that some future endpoint\n// accepts). Callers may still pass `identity` explicitly; this is the default, not\n// an override.\nexport function isIdentityArea(area: Area): boolean {\n return area.endsWith('/admin') || area.endsWith('/settings');\n}\n\n// ── Auth token injection ────────────────────────────────────────────────\n//\n// A host (e.g. the console's AuthProvider) registers a getter so the client can\n// attach a fresh access token — refreshing it first if near expiry — without the\n// SDK owning React state or storage.\n\nlet tokenGetter: (() => Promise<string | null>) | null = null;\n\nexport function setAuthTokenGetter(getter: (() => Promise<string | null>) | null) {\n tokenGetter = getter;\n}\n\n// The identity-token getter feeds the admin API (ADR-033): admin requests carry\n// the instance-scoped identity token, not the tenant access token. Registered\n// alongside setAuthTokenGetter; selected per request via the `identity` option.\nlet identityTokenGetter: (() => Promise<string | null>) | null = null;\n\nexport function setIdentityTokenGetter(getter: (() => Promise<string | null>) | null) {\n identityTokenGetter = getter;\n}\n\n/** Opt-in HTTP 401 recovery. Anonymous requests never invoke these callbacks. */\nexport interface UnauthorizedHandler {\n /**\n * Return a refreshed token for one replay, or null when recovery is unavailable or was refused\n * (onEnd then runs). Throw when the refresh failed transiently: the request fails with that\n * error and onEnd does not run, so the session is kept.\n */\n refresh: (token: string, identity: boolean) => Promise<string | null>;\n /** Recovery failed or the replay was refused. Only end the session owning this token. */\n onEnd: (error: GraphQLRequestError, token: string, identity: boolean) => void;\n}\n\nlet unauthorizedHandler: UnauthorizedHandler | null = null;\n\nexport function setUnauthorizedHandler(handler: UnauthorizedHandler | null): void {\n unauthorizedHandler = handler;\n}\n\n// resolveAuthToken returns the current access token (refreshing via the getter),\n// or null. Internal to the SDK — the ws subscribe path (subscribe.ts) reuses it\n// so subscriptions authenticate with the same token as queries.\nexport async function resolveAuthToken(): Promise<string | null> {\n return tokenGetter ? tokenGetter() : null;\n}\n\n// ── Errors ──────────────────────────────────────────────────────────────\n\nexport class GraphQLRequestError extends Error {\n constructor(\n message: string,\n /** HTTP status, or 0 for a transport-level failure. */\n public status: number,\n /** The raw `errors` array from a GraphQL response, when present. */\n public errors?: GraphQLErrorEntry[],\n ) {\n super(message);\n this.name = 'GraphQLRequestError';\n }\n}\n\n/**\n * One entry of a GraphQL response's `errors` array. `extensions` carries the server's\n * machine-readable detail when it sends any — for example `code: \"THROTTLED\"` with\n * `retryAfterSeconds` on a sign-in refused by the per-account backoff — so a caller can\n * branch on a code instead of matching the message text.\n */\nexport interface GraphQLErrorEntry {\n message: string;\n extensions?: Record<string, unknown>;\n}\n\ninterface GraphQLResponse<T> {\n data?: T;\n errors?: GraphQLErrorEntry[];\n}\n\nexport interface RequestOptions {\n /** Skip attaching the Bearer token (login / refresh run unauthenticated). */\n anonymous?: boolean;\n /**\n * Authenticate with the identity token instead of the tenant access token —\n * for the instance-scoped admin API (ADR-033). Ignored when `anonymous`.\n *\n * Rarely needed: an `/admin` or `/settings` area defaults to the identity token\n * already (see isIdentityArea). Pass it only to force the lane for an area whose\n * name does not say so.\n */\n identity?: boolean;\n}\n\n// A GraphQL document tagged with its result/variable types — what gql()/subscribe()\n// accept. A code-generated `TypedDocumentString` (client preset) satisfies it, and\n// so does a hand-authored query string cast to it: the SDK runs in documentMode\n// 'string', calling only `toString()` to get the query text, so the phantom result\n// (`TResult`) and variable (`TVariables`) generics are all that distinguish them.\n// Exported so packages/apps without codegen (dashboards, widgets, the dash app)\n// hand-author typed documents against one shared alias instead of re-inlining it.\nexport type TypedDocument<TResult, TVariables> = DocumentTypeDecoration<TResult, TVariables> & {\n toString(): string;\n};\n\n// `document` is a code-generated typed document (a `TypedDocumentString` from the\n// GraphQL Code Generator client preset). It implements\n// `DocumentTypeDecoration<TResult, TVariables>`, which carries the result and\n// variable types as phantom generics, and stringifies (via `toString()`) to the\n// raw query text the server expects. The structural `& { toString(): string }`\n// keeps this accepting a document from ANY service while still inferring both the\n// result (`TResult`) and the variables (`TVariables`).\nexport async function gql<TResult, TVariables>(\n area: Area,\n document: TypedDocument<TResult, TVariables>,\n ...[variables, options]: TVariables extends Record<string, never>\n ? [variables?: undefined, options?: RequestOptions]\n : [variables: TVariables, options?: RequestOptions]\n): Promise<TResult> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n const useIdentity = options?.identity ?? isIdentityArea(area);\n const handler = unauthorizedHandler;\n let token: string | null = null;\n\n if (!options?.anonymous) {\n const getter = useIdentity ? identityTokenGetter : tokenGetter;\n if (getter) {\n token = await getter();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n }\n\n const bodyText = JSON.stringify({ query: document.toString(), variables });\n const send = async (): Promise<Response> => {\n try {\n return await fetch(areaPath(area), {\n method: 'POST',\n headers: { ...headers },\n body: bodyText,\n });\n } catch (err) {\n throw new GraphQLRequestError(\n err instanceof Error ? err.message : 'Network request failed',\n 0,\n );\n }\n };\n\n let res = await send();\n if (res.status === 401 && token && handler && !options?.anonymous) {\n const rejectedToken = token;\n // The refresh call must be anonymous, so it cannot recursively recover itself.\n // A refresh that THROWS could not be completed right now (a network failure, a 5xx or a\n // 429): nothing was refused, so the session is kept, onEnd is not called, and this request\n // fails with that error. Only a null (a definitive refusal, or no recovery for this token)\n // or a second 401 ends the session.\n token = await handler.refresh(rejectedToken, useIdentity);\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n res = await send();\n }\n if (res.status === 401) {\n handler.onEnd(\n new GraphQLRequestError('Request failed (401)', 401),\n token ?? rejectedToken,\n useIdentity,\n );\n }\n }\n\n if (!res.ok) {\n throw new GraphQLRequestError(`Request failed (${res.status})`, res.status);\n }\n\n const body = (await res.json()) as GraphQLResponse<TResult>;\n if (body.errors && body.errors.length > 0) {\n throw new GraphQLRequestError(body.errors[0].message, res.status, body.errors);\n }\n if (body.data === undefined) {\n throw new GraphQLRequestError('Empty GraphQL response', res.status);\n }\n return body.data;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Classification of transport failures a caller has to render differently.\n//\n// Most errors are one shape to a screen (\"something went wrong\"), but a refusal\n// is not: \"you may not see this\" and \"this could not be loaded\" call for\n// different copy, and collapsing them makes a permission boundary look like an\n// outage.\n//\n// This lives beside GraphQLRequestError rather than in a host app because more\n// than one consumer needs it: the console renders a device's position panel from\n// it, and the dashboard runtime's location channel turns the same refusal into a\n// first-class snapshot state (location:read is deliberately outside the read-only\n// viewer baseline, so being refused is an ordinary state rather than a fault).\n\nimport { GraphQLRequestError } from './transport';\n\n/** True for an optimistic-concurrency refusal. Keeps the phrase fallback for older servers. */\nexport function isStaleWrite(err: unknown): boolean {\n if (err instanceof GraphQLRequestError && err.errors?.length) {\n return err.errors.some((entry) =>\n entry.extensions?.code === 'STALE_WRITE' ||\n (!entry.extensions?.code && entry.message.includes('modified by another writer')),\n );\n }\n return err instanceof Error && err.message.includes('modified by another writer');\n}\n\n// The backend's authorization gate returns core/auth's ErrForbidden, whose text\n// is \"forbidden: missing required authority\"; graphql-go surfaces a resolver\n// error verbatim as the entry's `message`, over HTTP 200. Anchoring the match at\n// the START of the message keeps it from firing on an unrelated error that\n// merely mentions the word (an entity literally named \"forbidden-zone\", say).\nconst FORBIDDEN_PREFIX = /^forbidden\\b/i;\n\n/**\n * True when the server REFUSED the request for lack of an authority, as opposed\n * to failing it. Callers use this to render a permission state rather than an\n * error state.\n */\nexport function isForbiddenError(err: unknown): boolean {\n // A subscription's refusal arrives from graphql-ws as the bare list of GraphQL errors, not\n // wrapped in a GraphQLRequestError; it is the same refusal and reads the same way.\n if (Array.isArray(err)) return err.some(isForbiddenEntry);\n if (!(err instanceof GraphQLRequestError)) return false;\n // A transport-level 403 counts even with no GraphQL body to read.\n if (err.status === 403) return true;\n // The server names the refusal by code (FORBIDDEN, with a reason such as\n // SCOPE_UNSUPPORTED for a member limited to part of the tenant); the message match\n // below stays for a server that predates the code.\n if (err.errors?.some((e) => e.extensions?.code === 'FORBIDDEN')) return true;\n const messages = err.errors?.length ? err.errors.map((e) => e.message) : [err.message];\n return messages.some((m) => FORBIDDEN_PREFIX.test(m.trim()));\n}\n\n// One entry of a GraphQL error list: refused by code, or (from a server that predates the code)\n// by the message prefix.\nfunction isForbiddenEntry(e: unknown): boolean {\n if (!e || typeof e !== 'object') return false;\n const entry = e as { message?: unknown; extensions?: { code?: unknown } };\n if (entry.extensions?.code === 'FORBIDDEN') return true;\n return typeof entry.message === 'string' && FORBIDDEN_PREFIX.test(entry.message.trim());\n}\n\n/**\n * True when the server refused the request because the caller is a member limited to part\n * of the tenant (a customer user) and the operation is not offered to such members at all\n * (`FORBIDDEN` with reason `SCOPE_UNSUPPORTED`). Distinct from an ordinary refusal: nothing\n * the member could be granted inside their scope would change the answer, so a caller\n * renders \"not available for customer users\" rather than \"you do not have access\".\n */\nexport function isScopeUnsupportedError(err: unknown): boolean {\n if (!(err instanceof GraphQLRequestError)) return false;\n return (err.errors ?? []).some(\n (e) => e.extensions?.code === 'FORBIDDEN' && e.extensions?.reason === 'SCOPE_UNSUPPORTED',\n );\n}\n\n/**\n * The machine-readable code the server put on a refusal (`extensions.code` of the first\n * error that carries one), such as `NOT_FOUND`, `CONFLICT`, `ESCALATION` or `LAST_ADMIN`;\n * null when the error carries none or is not a GraphQL response at all. Branch on this,\n * never on the message text.\n */\nexport function errorCode(err: unknown): string | null {\n if (!(err instanceof GraphQLRequestError)) return null;\n for (const e of err.errors ?? []) {\n const code = e.extensions?.code;\n if (typeof code === 'string' && code) return code;\n }\n return null;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The client half of the basemap cascade (ADR-079).\n//\n// The SERVER resolves a tenant's override over the operator's instance default and\n// hands back one effective value. This module resolves the last tier — a per-surface\n// override, set on the widget or held as a personal preference in the browser — over\n// that tenant value, and turns the result into something a renderer can use.\n//\n// It lives in the SDK rather than in either app because THREE surfaces need the\n// identical answer: the console's geofence editor, the dashboard map widget, and the\n// `/dash` viewer app, which has its own login and would otherwise be the one place\n// that quietly disagrees.\n\n/** A basemap at any tier: the tile source, and a fallback view. */\nexport interface Basemap {\n tileUrl?: string | null;\n attribution?: string | null;\n centerLat?: number | null;\n centerLon?: number | null;\n zoom?: number | null;\n}\n\n/** A resolved basemap that definitely has a tile source, so a renderer can draw it. */\nexport interface ResolvedBasemap {\n tileUrl: string;\n attribution: string | null;\n centerLat: number | null;\n centerLon: number | null;\n zoom: number | null;\n}\n\n/** Treat blank and whitespace-only strings as unset — an emptied form field means \"inherit\". */\nfunction text(v: string | null | undefined): string | null {\n if (typeof v !== 'string') return null;\n const trimmed = v.trim();\n return trimmed === '' ? null : trimmed;\n}\n\nfunction num(v: number | null | undefined): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n\n/**\n * Fold a per-surface override over the tenant's effective basemap.\n *\n * 🔴 The TILE SOURCE is atomic, exactly as it is on the server. If the override names\n * a tile URL, its attribution comes from the override too — never from the tenant. A\n * per-field fold would credit the tenant's provider for the override's tiles, which\n * is a licence violation manufactured by the merge rather than a cosmetic mismatch.\n * This is the same rule as basemap.Merge in user-management, and it has to be\n * restated here because this tier never reaches the server.\n *\n * The camera folds per field: a widget that only wants to open closer in should not\n * have to restate a provider to keep it.\n */\nexport function resolveBasemap(override: Basemap | null | undefined, tenant: Basemap | null | undefined): Basemap {\n const o = override ?? {};\n const t = tenant ?? {};\n\n // 🔴 AN INCOMPLETE OVERRIDE IS NOT AN OVERRIDE. A tile URL with no credit line is\n // refused outright by the server at the tenant and instance tiers — the two halves\n // are stored as one value or not at all — but THIS tier never reaches the server: a\n // widget's own options and the fence editor's browser-local fields are entered\n // client-side and rendered directly.\n //\n // Without this the atomic fold below did its job and still produced the defect it\n // exists to prevent: it correctly refused to lend the tenant's credit line to the\n // override's tiles, and then drew those tiles with NO credit line at all. Correct\n // about the cross-crediting, wrong about the licence.\n //\n // So an override naming tiles without their attribution is discarded whole, and the\n // surface falls back to the tenant's properly-credited basemap. Failing closed to a\n // map that is credited beats honouring a preference that cannot legally be shown.\n //\n // On an ordinary instance the fallback is a real map, because a shipped default\n // means some tier below almost always has one. On an instance whose operator\n // deliberately stored `{}` there is nothing below, and the surface falls through to\n // the bundled schematic world — which is the correct outcome for the same reason,\n // just a less pretty one.\n const overrideAttribution = text(o.attribution);\n const overrideTiles = overrideAttribution === null ? null : text(o.tileUrl);\n const tileUrl = overrideTiles ?? text(t.tileUrl);\n const attribution = overrideTiles ? overrideAttribution : text(t.attribution);\n\n // Latitude and longitude move as a pair for the same reason: half a coordinate\n // from each tier names a point neither one chose.\n const hasOverrideCentre = num(o.centerLat) !== null || num(o.centerLon) !== null;\n const centerLat = hasOverrideCentre ? num(o.centerLat) : num(t.centerLat);\n const centerLon = hasOverrideCentre ? num(o.centerLon) : num(t.centerLon);\n\n return {\n tileUrl,\n attribution,\n centerLat,\n centerLon,\n zoom: num(o.zoom) ?? num(t.zoom),\n };\n}\n\n/**\n * Narrow a folded basemap to one that can actually be rendered, or null.\n *\n * A basemap with a camera but no tile source is legitimate — an operator may set a\n * starting view before choosing a provider — but there is nothing to draw, and the\n * caller should say so rather than request tiles from an empty URL.\n */\nexport function renderableBasemap(b: Basemap | null | undefined): ResolvedBasemap | null {\n const tileUrl = text(b?.tileUrl);\n if (!tileUrl) return null;\n return {\n tileUrl,\n attribution: text(b?.attribution),\n centerLat: num(b?.centerLat),\n centerLon: num(b?.centerLon),\n zoom: num(b?.zoom),\n };\n}\n\n/**\n * The fallback view a surface opens at when it has nothing of its own to fit to.\n *\n * 🔴 A FALLBACK, never an override (ADR-079 §5). A surface with real content — an\n * existing fence's ring, a widget's markers — fits that and ignores this entirely.\n * Returns null when no tier declared a centre, so the caller keeps its own default\n * rather than being moved to 0,0.\n */\nexport function fallbackView(b: Basemap | null | undefined): { center: [number, number]; zoom: number | null } | null {\n const lat = num(b?.centerLat);\n const lon = num(b?.centerLon);\n if (lat === null || lon === null) return null;\n return { center: [lon, lat], zoom: num(b?.zoom) };\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// GraphQL subscriptions over the graphql-transport-ws protocol (ADR-037) — the\n// live half of the client wire, consumed by dashboards (the ADR-039 Hub) for\n// live telemetry. The backend serves subscriptions on the same /api/<area>/graphql\n// path via a WebSocket upgrade; a client derives the ws:// URL from the http one.\n//\n// This is the low-level SDK primitive: one lazily-created graphql-ws client per\n// area (connection reuse), and a subscribe() that binds a typed document to a\n// sink. The dashboard Hub layers subscription multiplexing on top (many widgets,\n// one connection).\n//\n// The server accepts only SUBSCRIPTION operations on this socket — queries and\n// mutations go over HTTP — and it closes the socket with 4401 when the access token\n// it authenticated with expires. subscribe() handles that close itself: when a\n// socket that had been acknowledged is closed with 4401, it re-issues the operation\n// once, which opens a new socket whose connection_init carries a freshly resolved\n// token, and reports the reconnect to the sink as connected(true) so a consumer\n// re-queries whatever it may have missed. graphql-ws treats 4401 as fatal and does\n// not retry it on its own. Any other dropped socket is retried for as long as the\n// operation is wanted, with a capped, jittered back-off (clientFor). So is a connect that\n// could not get a token because refreshing it failed transiently after the held one had\n// expired (see shouldRetry).\n\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\nimport type { GraphQLFormattedError } from 'graphql';\nimport { createClient, type Client } from 'graphql-ws';\n\nimport { isTransientRefreshError } from './session';\nimport { areaPath, resolveAuthToken, type Area } from './transport';\n\n// The graphql-transport-ws close code for an unauthorized connection. Mid-session\n// it means the token the socket authenticated with has expired.\nconst CLOSE_UNAUTHORIZED = 4401;\n\n// wsUrl builds the absolute ws(s):// URL for an area from the current origin,\n// mirroring the relative http path so dev proxy and prod ingress both work.\nfunction wsUrl(area: Area): string {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}${areaPath(area)}`;\n}\n\n// An area's shared graphql-ws client, plus what subscribe() needs to know about its\n// socket to decide whether a 4401 close is worth one re-subscribe.\ninterface AreaClient {\n client: Client;\n // The current socket has received connection_ack.\n acked: boolean;\n // The most recently closed socket had been acknowledged. A 4401 on an\n // acknowledged socket is an expiry mid-session, which a fresh token cures; a 4401\n // on one that was never acknowledged is the server refusing the token presented\n // at connect, which re-subscribing would only repeat.\n lastCloseWasAcked: boolean;\n}\n\n// The longest wait between two reconnect attempts. graphql-ws doubles its wait on each\n// attempt, so without a ceiling an outage of a few minutes would push the next attempt\n// hours away.\nexport const RETRY_CEILING_MS = 30_000;\n\n// retryDelayMs is the wait before reconnect attempt `retries` (0-based): doubling from one\n// second up to RETRY_CEILING_MS, then a random point in the upper half of that. The random\n// half spreads out every screen that lost the same server at the same moment, so they do\n// not all come back on the same tick; the fixed half keeps attempts from bunching near zero.\nexport function retryDelayMs(retries: number, random: () => number = Math.random): number {\n const ceiling = Math.min(1000 * 2 ** retries, RETRY_CEILING_MS);\n return (ceiling / 2) * (1 + random());\n}\n\n// One graphql-ws client per area — the WebSocket (and its connection_init auth)\n// is reused across every subscription to that area. connectionParams is a\n// function so the token is re-resolved on each (re)connect, surviving refresh.\nconst clients = new Map<Area, AreaClient>();\n\nfunction clientFor(area: Area): AreaClient {\n let entry = clients.get(area);\n if (!entry) {\n const client = createClient({\n url: wsUrl(area),\n connectionParams: async () => {\n const token = await resolveAuthToken();\n return token ? { Authorization: `Bearer ${token}` } : {};\n },\n // 🔴 Keep reconnecting for as long as anything is subscribed. Left to its defaults,\n // graphql-ws gives up after 5 attempts (about 40 s; in a browser, after the first one\n // that fails, see shouldRetry) and then errors every operation, and nothing reopened\n // them: a wall display that lost its network for a minute showed\n // \"Data unavailable\" until someone reloaded it. One socket per area carries every\n // operation, so each attempt is ONE connection however many widgets are waiting, and\n // graphql-ws resubscribes all of them on it once it is acknowledged.\n retryAttempts: Infinity,\n retryWait: (retries) => new Promise((resolve) => setTimeout(resolve, retryDelayMs(retries))),\n // graphql-ws retries only close events by default, and a browser reports a handshake\n // that failed (the server or the network still down) as an `error` event first, so\n // the first failed attempt would end every operation however many were allowed. A\n // socket's own error event is a network problem and is retried; an Error thrown in\n // this client is not. The closes that say the request itself is wrong (4400, 4401,\n // 4409, 4429) are fatal inside graphql-ws whatever this answers, so an expired or\n // refused token still reaches subscribe() below and the session flow, never a loop.\n //\n // 🔴 And a token that could not be had FOR NOW. The session's getAccessToken, under\n // transientRefreshErrors: 'throw', throws when the held access token has expired and the\n // refresh failed transiently (no response, a 5xx, a 429): nothing was refused and the\n // session is kept. connectionParams lets that\n // throw reach graphql-ws, which reports it here first and then closes the socket with\n // 4005; answering false made every subscription on the area error out over an outage of\n // the identity service, and nothing reopened them. It is retried like a dropped socket,\n // with the same back-off. A refused refresh is not transient: the session ends, the next\n // connect carries no token, and the server's 4401 at connect is surfaced as before.\n shouldRetry: (err) =>\n (typeof Event != 'undefined' && err instanceof Event) || hasCode(err) || isTransientRefreshError(err),\n });\n const state: AreaClient = { client, acked: false, lastCloseWasAcked: false };\n // Registered once, here, before any subscription can register its own — so on a\n // close this runs first and every sink's error handler (which graphql-ws delivers\n // later, through a rejected promise) reads the same lastCloseWasAcked. That holds\n // even after the first of them re-subscribes and a new socket starts connecting.\n client.on('connecting', () => {\n state.acked = false;\n });\n client.on('connected', () => {\n state.acked = true;\n });\n client.on('closed', () => {\n state.lastCloseWasAcked = state.acked;\n state.acked = false;\n });\n entry = state;\n clients.set(area, entry);\n }\n return entry;\n}\n\n// hasCode reports whether a graphql-ws error is a close event (anything with a close code).\nfunction hasCode(err: unknown): err is { code: unknown } {\n return typeof err === 'object' && err !== null && 'code' in err;\n}\n\n// isUnauthorizedClose reports whether a graphql-ws sink error is a 4401 close event.\nfunction isUnauthorizedClose(err: unknown): boolean {\n return hasCode(err) && err.code === CLOSE_UNAUTHORIZED;\n}\n\nexport interface SubscriptionSink<T> {\n next: (data: T) => void;\n /**\n * GraphQL errors carried by a result (for example a validation refusal sent as an\n * error-only result before `complete`). Called before `next` when a result carries both.\n */\n errors?: (errors: ReadonlyArray<GraphQLFormattedError>) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n // Connection-level signals for the shared per-area socket, distinct from the\n // per-operation next/error/complete above. `connected` fires on each successful\n // connection_ack — `wasRetry` distinguishes a reconnect (after a dropped socket,\n // or after the server closed an expired session) from the first connect; `closed`\n // fires on each socket close (graphql-ws then auto-retries a transient close). A\n // consumer that only needs data can omit both; a live-status indicator uses them\n // to tell \"connected but idle\" from \"offline\", and a consumer that must not miss\n // events re-queries on connected(true).\n connected?: (wasRetry: boolean) => void;\n closed?: () => void;\n}\n\n// subscribe binds a typed subscription document to a sink and returns an\n// unsubscribe function. The document is the same code-generated typed document\n// the query path uses, so the result type is inferred; it must be a subscription,\n// since the server refuses anything else on this socket. Result errors surface via\n// sink.errors; operation/socket failures via sink.error; normal termination via sink.complete. A\n// 4401 close of an acknowledged socket — the server ending an expired session — is\n// not surfaced: the operation is re-issued once on a new socket with a fresh token.\nexport function subscribe<TResult, TVariables>(\n area: Area,\n document: DocumentTypeDecoration<TResult, TVariables> & { toString(): string },\n variables: TVariables extends Record<string, never> ? undefined : TVariables,\n sink: SubscriptionSink<TResult>,\n): () => void {\n const entry = clientFor(area);\n const { client } = entry;\n // Set when this operation is re-issued after an expiry, so the next connection_ack\n // reaches the sink as a reconnect: graphql-ws itself reports it as a first connect,\n // because a fatal close ends its retry state.\n let reauth = false;\n // Client-level connection events are registered per subscribe() and torn down with\n // it, alongside the operation itself, so a single dispose() call releases both.\n const disposers: Array<() => void> = [];\n if (sink.connected) {\n disposers.push(\n client.on('connected', (_socket, _payload, wasRetry) => {\n const retried = wasRetry || reauth;\n reauth = false;\n sink.connected!(retried);\n }),\n );\n }\n if (sink.closed) {\n disposers.push(client.on('closed', () => sink.closed!()));\n }\n\n const payload = {\n query: document.toString(),\n variables: variables as Record<string, unknown> | undefined,\n };\n let disposed = false;\n let current: (() => void) | null = null;\n const start = (): void => {\n const previous = current;\n current = client.subscribe<TResult>(payload, {\n next: (result) => {\n if (result.errors?.length) sink.errors?.(result.errors);\n if (result.data != null) sink.next(result.data);\n },\n error: (err) => {\n if (disposed) return;\n if (isUnauthorizedClose(err) && entry.lastCloseWasAcked) {\n reauth = true;\n start();\n return;\n }\n sink.error?.(err);\n },\n complete: () => sink.complete?.(),\n });\n // Release the ended operation only once its replacement holds the client, so the\n // client's count of live operations never touches zero in between (graphql-ws\n // does not release an operation that ended in a fatal close by itself).\n previous?.();\n };\n start();\n disposers.push(() => {\n disposed = true;\n current?.();\n });\n return () => {\n for (const dispose of disposers) dispose();\n };\n}\n\n// disposeSubscriptions tears down every cached area client (their sockets). A\n// host calls this on sign-out so a stale token's socket does not linger.\nexport function disposeSubscriptions(): void {\n for (const { client } of clients.values()) {\n void client.dispose();\n }\n clients.clear();\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Client-side decode of the DeviceChain access token (ADR-008 JWT). This reads\n// the payload for display + routing only; it does NOT verify the signature —\n// every protected operation is still enforced server-side by the token's\n// authorities. Never trust these claims for authorization decisions beyond what\n// the UI shows.\n\nexport interface DecodedClaims {\n /** Tenant the subject acts within (authoritative server-side). */\n tenant: string;\n /** Human-readable subject identifier. */\n username: string;\n /** Assigned role names — display/audit only; enforcement is on authorities. */\n roles: string[];\n /** Effective capabilities (e.g. \"device:write\", or \"*\" for super-authority). */\n authorities: string[];\n /** \"access\" | \"refresh\". */\n typ: string;\n /** Expiry, epoch seconds (from the standard `exp` claim). */\n exp?: number;\n /** Issue time, epoch seconds (from the standard `iat` claim). */\n iat?: number;\n /**\n * The membership's scope, from the `scp` claim: anchors such as `customer:acme` that\n * limit the subject to part of the tenant. Empty when the subject sees the whole tenant.\n *\n * Deliberately NOT named `scope`: an OAuth access token carries its own `scope` claim (a\n * space-separated grant string), and the two mean unrelated things. Optional so a\n * hand-built claims object (a test fixture, an older caller) still type-checks; an\n * absent value means the same as an empty one.\n */\n scopeAnchors?: string[];\n}\n\n/** One anchor of a scope, split into its kind and token. */\nexport interface ScopeAnchorRef {\n /** `customer` or `group`. */\n kind: string;\n token: string;\n}\n\nfunction base64UrlDecode(segment: string): string {\n const padded = segment.replace(/-/g, '+').replace(/_/g, '/');\n const json = atob(padded);\n // Handle UTF-8 payloads.\n return decodeURIComponent(\n Array.prototype.map\n .call(json, (c: string) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n}\n\n/** Decode a JWT's payload, or null if it is malformed. */\nexport function decodeToken(token: string): DecodedClaims | null {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n try {\n const payload = JSON.parse(base64UrlDecode(parts[1]));\n return {\n tenant: payload.tenant ?? '',\n username: payload.username ?? '',\n roles: payload.roles ?? [],\n authorities: payload.authorities ?? [],\n typ: payload.typ ?? '',\n exp: payload.exp,\n iat: payload.iat,\n scopeAnchors: Array.isArray(payload.scp) ? payload.scp.filter((a: unknown) => typeof a === 'string') : [],\n };\n } catch {\n return null;\n }\n}\n\n/** True if the token is missing, malformed, or within `skewSeconds` of expiry. */\nexport function isExpired(token: string, skewSeconds = 30): boolean {\n const claims = decodeToken(token);\n if (!claims || claims.exp === undefined) return true;\n const nowSeconds = Date.now() / 1000;\n return claims.exp - skewSeconds <= nowSeconds;\n}\n\n/** True if the claims grant the authority (the super-authority \"*\" passes all). */\nexport function hasAuthority(claims: DecodedClaims | null, required: string): boolean {\n if (!claims) return false;\n return claims.authorities.some((a) => a === '*' || a === required);\n}\n\n/**\n * True when the claims limit the subject to part of the tenant (a non-empty `scp`). The\n * server enforces the scope on every request; this only lets a client stop offering what\n * the server would refuse.\n */\nexport function isScoped(claims: DecodedClaims | null): boolean {\n return (claims?.scopeAnchors?.length ?? 0) > 0;\n}\n\n/**\n * The claims' scope anchors split into kind and token (`customer:acme` → customer/acme).\n * An anchor with no `:` is dropped rather than guessed at.\n */\nexport function scopeAnchorRefs(claims: DecodedClaims | null): ScopeAnchorRef[] {\n return (claims?.scopeAnchors ?? []).flatMap((a) => {\n const i = a.indexOf(':');\n return i > 0 ? [{ kind: a.slice(0, i), token: a.slice(i + 1) }] : [];\n });\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The tenant session's access-token lifecycle, framework-free. A host owns WHERE\n// the token pair lives (React state + localStorage in the console, memory in /dash)\n// and WHAT the refresh call is; this owns WHEN to refresh and how concurrent callers\n// share one refresh:\n//\n// - getAccessToken() returns the held access token while it is comfortably valid,\n// and otherwise refreshes first.\n// - concurrent callers share ONE in-flight refresh. Refresh tokens rotate, so two\n// parallel refreshes would spend the same token twice and the second would fail.\n// - a result that arrives after the session was cleared or replaced is dropped, so a\n// slow refresh can never resurrect a dead session.\n// - a lapsed refresh token, or a DEFINITIVE refresh failure (the server answered and\n// refused: a GraphQL error such as an invalid, revoked or SSO-gated refresh token, or\n// any 4xx but 429), ends the session through onEnd and the caller gets null. The host\n// decides what \"ended\" looks like.\n// - a TRANSIENT refresh failure (no response at all, a 5xx, or a 429) NEVER ends the\n// session: the server has not refused anything, and the refresh token is still good. While\n// the access token is valid the caller is handed it. Once it has expired there is nothing\n// valid to hand over, and what the caller gets depends on `transientRefreshErrors`:\n// 'null' (the default, and the v1.6 contract of getAccessToken): null, exactly as v1.6\n// returned. v1.6 also ended the session there; it no longer does, so the next call\n// (or the auto-refresh retry below) tries again.\n// 'throw' (opt-in): the transient error is thrown, so the request fails with the outage\n// it hit rather than going out without a token and reading the server's 401 as a\n// refusal. The console and /dash opt in.\n// Only the refresh token lapsing ends a session that keeps failing transiently.\n// 🔴 #2752 made 'throw' the only behaviour. getAccessToken is a published export and a\n// v1.6 caller checks for null, so a promise that now rejected was a contract change in a\n// minor: it became the opt-in.\n// - exchange() runs a host operation that SPENDS the refresh token for its own reasons (the\n// console's step-up trades it, with a second-factor code, for an elevated pair) through the\n// same coordinator: it waits for a refresh already running, and while it runs, a refresh\n// anyone asks for (a due token, a 401, the auto-refresh timer) waits for it and takes the\n// pair it yields instead of spending the same token again. 🔴 Before it, a forced refresh\n// after a 401 and a step-up could spend one refresh token together: the server honours only\n// one, the loser's refusal ended the session, and the user was signed out after verifying.\n// - startAutoRefresh() refreshes ahead of expiry without waiting for a caller, and\n// retries a transient failure with jittered exponential backoff for as long as the\n// refresh token is valid. A display that only holds a websocket makes no request that\n// would trigger the lazy path, so without this it would sit on a token that is about\n// to expire, and a network blip at the wrong moment would end an unattended session.\n// 🔴 It used to give up when the ACCESS token expired, so an outage longer than the\n// access token's few minutes signed out a wall display whose refresh token had hours\n// left, and nobody was there to sign it back in.\n\nimport { isExpired, decodeToken } from './jwt';\nimport { GraphQLRequestError } from './transport';\n\nexport interface TokenPair {\n accessToken: string;\n refreshToken: string;\n}\n\nexport interface SessionTokensOptions {\n /** The held pair, or null when signed out. Must return the same object until it is replaced. */\n read: () => TokenPair | null;\n /** Stores a refreshed pair. */\n apply: (next: TokenPair) => void;\n /** Exchanges a refresh token for a new pair. */\n refresh: (refreshToken: string) => Promise<TokenPair>;\n /**\n * The session can no longer be sustained: the refresh token lapsed (`err` undefined), or the\n * server refused the refresh (`err` is what it threw). A transient failure never ends it. The\n * host clears its session here.\n */\n onEnd: (err?: unknown) => void;\n /**\n * Refresh this many seconds before the access token expires. Default 30. A larger value\n * gives startAutoRefresh's retries a longer window to ride out a network outage. It is\n * capped at half the token's lifetime (`exp - iat`), so a server configured with short-lived\n * tokens never hands out one that is already due, which would refresh on every call.\n */\n skewSeconds?: number;\n /**\n * What `getAccessToken` does when the access token has expired and the refresh failed\n * transiently (no response, a 5xx or a 429). Either way the session is kept and a later call\n * tries again; `onEnd` is not called.\n *\n * - `'null'` (default): resolve to null, as in v1.6.\n * - `'throw'`: reject with the refresh's error, so the request fails with the outage instead\n * of being sent without a token. `subscribe` treats that error as transient: the\n * subscription's reconnect retries it.\n */\n transientRefreshErrors?: 'null' | 'throw';\n}\n\nexport interface SessionTokens {\n /**\n * Force one shared refresh after a 401, even though the held access token has not expired.\n * Resolves to the refreshed token, or null when the session is signed out, was replaced since\n * `rejectedToken` was sent, or has ended (the refresh token lapsed or the server refused the\n * refresh). Rejects with the refresh's error when it failed transiently: the session is kept,\n * and a later call tries again. Never hands back the rejected token. It rejects whatever\n * `transientRefreshErrors` says: a null here tells `setUnauthorizedHandler` the session ended.\n *\n * Optional HERE because v1.6 had no such member, and a host that builds its own\n * `SessionTokens` must still type-check. What `createSessionTokens` returns always has it:\n * see `ManagedSessionTokens`. Without it a host has no 401 recovery, as in v1.6.\n */\n forceRefresh?: (rejectedToken?: string) => Promise<string | null>;\n /**\n * A usable access token, refreshing first when it is within the skew of expiry; null when\n * signed out or ended. When the access token has expired and the refresh failed transiently,\n * the session is kept and a later call tries again; the call resolves to null, or rejects with\n * the refresh's error under `transientRefreshErrors: 'throw'`.\n */\n getAccessToken: () => Promise<string | null>;\n /** Forget any in-flight refresh (the host cleared or replaced the session itself). */\n reset: () => void;\n /**\n * Refresh ahead of expiry on a timer, retrying a transient failure with backoff for as long\n * as the refresh token is valid. Returns a stop function.\n */\n startAutoRefresh: () => () => void;\n}\n\n/** What `createSessionTokens` returns: a `SessionTokens` whose `forceRefresh` is always present. */\nexport interface ManagedSessionTokens extends SessionTokens {\n forceRefresh: (rejectedToken?: string) => Promise<string | null>;\n /**\n * Run a host operation that spends the held refresh token and returns the pair that replaces\n * it (a step-up, say), serialized with every refresh, so the two never spend one refresh\n * token between them. It first makes sure there is a usable access token (refreshing if due)\n * and waits out any refresh already running; while `spend` runs, a refresh anyone asks for\n * waits for it and shares the pair it yields. The pair is applied like a refreshed one.\n *\n * Resolves to the new access token. Rejects with `spend`'s error when it fails (the session\n * is kept, and refreshes then go ahead as usual), and with an Error when the session is\n * signed out, has ended, or was replaced while `spend` ran (its pair is then dropped).\n *\n * While `spend` runs, the held access token is handed out without waiting as long as it has\n * not expired, because `spend`'s own request asks for one. A `forceRefresh` naming that access\n * token as rejected (a 401, which may be `spend`'s own request) rejects with a 401 error and\n * keeps the session rather than waiting on `spend`; a later 401 recovers as usual.\n */\n exchange: (spend: (refreshToken: string) => Promise<TokenPair>) => Promise<string>;\n}\n\nconst DEFAULT_SKEW_SECONDS = 30;\n// setTimeout stores its delay in a signed 32-bit int; a longer one fires immediately.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n// Auto-refresh retry backoff: 1 s doubling to 30 s, each scaled by a random 50-100 % so a\n// fleet of displays that lost the network together does not come back in lockstep.\nconst RETRY_BASE_MS = 1_000;\nconst RETRY_CAP_MS = 30_000;\n// While the access token is valid, one retry is aimed this far ahead of its expiry, not at it,\n// so a request made then still has a token. No retry is armed within RETRY_BASE_MS before that\n// aim: one that would be is moved onto it instead. After it, retries carry on at the backoff.\nconst RETRY_EXPIRY_MARGIN_MS = 1_000;\n// The shortest gap between two scheduled refreshes. A backstop: if the held token still\n// looks due right after a refresh (the device clock runs well ahead of the server's), the\n// timer must not turn into a refresh loop against the server.\nconst MIN_REFRESH_GAP_MS = 10_000;\n\n/**\n * Whether a refresh failure is worth retrying: the request never got a response (status 0),\n * or the server answered 5xx or 429 without a GraphQL error. Anything else (a GraphQL error\n * such as an invalid or revoked refresh token or SSO_REQUIRED, a 400 or 401, or an error that\n * is not a transport error at all) is the server's answer, and asking again would repeat it.\n * Exported within the package (not from index.ts): subscribe.ts reads the same predicate.\n */\nexport function isTransientRefreshError(err: unknown): boolean {\n if (!(err instanceof GraphQLRequestError)) return false;\n if (err.errors && err.errors.length > 0) return false;\n return err.status === 0 || err.status === 429 || err.status >= 500;\n}\n\ntype Outcome =\n | { kind: 'ok'; token: string }\n | { kind: 'stale' } // the session was cleared or replaced while the refresh ran\n | { kind: 'ended' }\n | { kind: 'transient'; err: unknown }\n | { kind: 'declined'; err: unknown }; // an exchange's spend failed; it applied nothing\n\nfunction expiryMs(token: string): number | undefined {\n const exp = decodeToken(token)?.exp;\n return exp === undefined ? undefined : exp * 1000;\n}\n\nexport function createSessionTokens(opts: SessionTokensOptions): ManagedSessionTokens {\n const skew = opts.skewSeconds ?? DEFAULT_SKEW_SECONDS;\n const mode = opts.transientRefreshErrors;\n // Fail closed: a misspelt mode from an untyped caller must not quietly mean the default.\n if (mode !== undefined && mode !== 'null' && mode !== 'throw') {\n throw new TypeError(`createSessionTokens: transientRefreshErrors must be 'null' or 'throw', not ${String(mode)}`);\n }\n const throwTransient = mode === 'throw';\n let inFlight: Promise<Outcome> | null = null;\n // While an exchange's spend runs: the access token held when it started, which its own\n // request is sent with. Null otherwise.\n let exchanging: string | null = null;\n let lastRefresh: { from: string; pair: TokenPair } | null = null;\n\n // The skew for one access token: the configured one, or half its lifetime if that is less.\n const skewFor = (token: string): number => {\n const c = decodeToken(token);\n if (c?.exp === undefined || c.iat === undefined) return skew;\n return Math.min(skew, Math.max(0, (c.exp - c.iat) / 2));\n };\n const due = (token: string): boolean => isExpired(token, skewFor(token));\n\n const end = (err?: unknown) => {\n inFlight = null;\n opts.onEnd(err);\n };\n\n // Spend `current`'s refresh token through `spend` (the host's refresh, or an exchange), as the\n // one in-flight use of it that every caller shares.\n const run = (\n current: TokenPair,\n spend: (refreshToken: string) => Promise<TokenPair>,\n isExchange: boolean,\n ): Promise<Outcome> => {\n // A spend that throws synchronously settles this before the assignment below, so it is\n // never left behind as the in-flight use; and a use reset() forgot never clears its successor.\n // An exchange marks `exchanging` before this runs: spend's own request asks for a token\n // synchronously, before the in-flight use is registered.\n let settled = false;\n let p: Promise<Outcome> | undefined = undefined;\n p = (async (): Promise<Outcome> => {\n try {\n const pair = await spend(current.refreshToken);\n // A promise cannot be cancelled, so guard here: if the live session is no\n // longer the one this refresh started from, drop the result.\n if (opts.read() !== current) return { kind: 'stale' };\n const next = { accessToken: pair.accessToken, refreshToken: pair.refreshToken };\n opts.apply(next);\n lastRefresh = { from: current.accessToken, pair: next };\n return { kind: 'ok', token: pair.accessToken };\n } catch (err) {\n // An exchange that failed is its caller's error, not a verdict on the session: a\n // wrong step-up code refuses the code, not the refresh token.\n if (isExchange) return { kind: 'declined', err };\n // Only end the session this refresh belonged to, not one since replaced.\n if (opts.read() !== current) return { kind: 'stale' };\n if (isTransientRefreshError(err)) return { kind: 'transient', err };\n end(err);\n return { kind: 'ended' };\n } finally {\n // Settled synchronously (p unset): nothing else can have started meanwhile.\n settled = true;\n if (p === undefined || inFlight === p) {\n inFlight = null;\n exchanging = null;\n }\n }\n })();\n if (!settled) inFlight = p;\n return p;\n };\n\n // One refresh of `current`, shared by every caller that asks while it runs. A caller that\n // finds an exchange running takes its pair; when the exchange failed it applied nothing, so\n // the held pair is refreshed as it would have been.\n const refreshShared = async (current: TokenPair): Promise<Outcome> => {\n for (;;) {\n const out = await (inFlight ?? run(current, opts.refresh, false));\n if (out.kind !== 'declined') return out;\n if (opts.read() !== current) return { kind: 'stale' };\n }\n };\n\n const getAccessToken = async (): Promise<string | null> => {\n const current = opts.read();\n if (!current) return null;\n if (isExpired(current.refreshToken, 0)) {\n end();\n return null;\n }\n if (!due(current.accessToken)) return current.accessToken;\n // An exchange is spending the refresh token, and its own request asks for an access token:\n // waiting on the exchange from inside it would never finish. The held token is still good.\n if (exchanging !== null && !isExpired(current.accessToken, 0)) return current.accessToken;\n\n const out = await refreshShared(current);\n if (out.kind === 'ok') return out.token;\n if (out.kind !== 'transient') return null;\n // A transient failure: the held token is still good if it has not actually expired.\n if (opts.read() !== current) return null;\n if (!isExpired(current.accessToken, 0)) return current.accessToken;\n // Nothing valid to hand over, but nothing was refused either: keep the session. Under\n // 'throw' the caller fails with the outage it hit (a null would send the request without a\n // token, and the server's 401 would read as a refusal); by default it gets v1.6's null.\n if (throwTransient) throw out.err;\n return null;\n };\n\n const startAutoRefresh = (): (() => void) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stopped = false;\n let failures = 0;\n\n const arm = (delay: number) => {\n timer = setTimeout(() => void fire(), Math.min(Math.max(0, delay), MAX_TIMER_MS));\n };\n\n // Arm for the next refresh of whatever pair is held now, no sooner than `floor` ms.\n const schedule = (floor = 0) => {\n if (stopped) return;\n const current = opts.read();\n const exp = current ? expiryMs(current.accessToken) : undefined;\n if (!current || exp === undefined) return; // signed out, or nothing to time against\n arm(Math.max(floor, exp - skewFor(current.accessToken) * 1000 - Date.now()));\n };\n\n const fire = async () => {\n if (stopped) return;\n const current = opts.read();\n if (!current) return;\n if (isExpired(current.refreshToken, 0)) {\n end();\n return;\n }\n // Someone else refreshed already (a request took the lazy path): time against that.\n if (!due(current.accessToken)) {\n failures = 0;\n schedule(MIN_REFRESH_GAP_MS);\n return;\n }\n const out = await refreshShared(current);\n if (stopped) return;\n if (out.kind === 'ok') {\n failures = 0;\n schedule(MIN_REFRESH_GAP_MS);\n return;\n }\n if (out.kind !== 'transient') return; // ended, or the host replaced the session\n if (opts.read() !== current) return;\n\n const backoff = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** failures) * (0.5 + Math.random() / 2);\n failures++;\n const left = (expiryMs(current.accessToken) ?? 0) - RETRY_EXPIRY_MARGIN_MS - Date.now();\n if (left > 0) {\n // A retry that would land within RETRY_BASE_MS of the aim before expiry (or past it) is\n // moved onto that aim. Otherwise a backoff that happens to land just short of the aim\n // leaves the aimed retry following it moments later: two requests back to back, against\n // a server that may have just answered 429.\n arm(left - backoff < RETRY_BASE_MS ? left : backoff);\n return;\n }\n // The access token has expired, but the refresh token may have hours left: keep trying\n // at the backoff. A retry is never armed past the refresh token's expiry; at it, fire()\n // finds the refresh token lapsed and ends the session.\n const refreshLeft = (expiryMs(current.refreshToken) ?? 0) - Date.now();\n arm(Math.min(backoff, refreshLeft));\n };\n\n schedule();\n return () => {\n stopped = true;\n if (timer !== undefined) clearTimeout(timer);\n };\n };\n\n return {\n getAccessToken,\n forceRefresh: async (rejectedToken) => {\n const current = opts.read();\n if (!current) return null;\n // A late 401 must not refresh or end a replacement session.\n if (rejectedToken !== undefined && current.accessToken !== rejectedToken) {\n // A sibling request may have finished refreshing before this 401 arrived.\n return lastRefresh?.pair === current && lastRefresh.from === rejectedToken\n ? current.accessToken : null;\n }\n if (isExpired(current.refreshToken, 0)) {\n end();\n return null;\n }\n // The access token an exchange is being sent with was rejected. This 401 may be the\n // exchange's own request, which cannot wait for the exchange it is part of; and a refresh\n // now would spend the token the exchange is spending. Fail this request and keep the\n // session: once the exchange settles, a later 401 recovers as usual.\n if (exchanging !== null && rejectedToken === exchanging) {\n throw new GraphQLRequestError('Request failed (401)', 401);\n }\n const out = await refreshShared(current);\n if (out.kind === 'ok') return out.token;\n if (out.kind !== 'transient') return null;\n if (opts.read() !== current) return null;\n // The server rejected this access token, so it is not handed back; but a transient refresh\n // failure refused nothing, so the session is kept and the caller gets the outage it hit.\n throw out.err;\n },\n exchange: async (spend) => {\n // A usable access token first: spend's own request needs one, and a refresh it would\n // otherwise trigger mid-exchange could not run.\n if (!(await getAccessToken())) throw new Error('session unavailable');\n // Then wait out a refresh already spending the token (a forced one after a 401 starts\n // whatever the access token's expiry), and take the pair it leaves.\n while (inFlight) await inFlight;\n const current = opts.read();\n if (!current) throw new Error('session unavailable');\n if (isExpired(current.refreshToken, 0)) {\n end();\n throw new Error('session unavailable');\n }\n exchanging = current.accessToken;\n const out = await run(current, spend, true);\n if (out.kind === 'ok') return out.token;\n if (out.kind === 'declined') throw out.err;\n throw new Error('session changed');\n },\n reset: () => {\n inFlight = null;\n exchanging = null;\n lastRefresh = null;\n },\n startAutoRefresh,\n };\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Token masks (ADR-042 P3): the client-side template language that mints, and\n// soft-validates, entity tokens. A mask is literal text plus typed placeholders,\n// and one mask drives three operations:\n//\n// generate fill placeholders to produce a concrete token\n// normalize kebab-case a human string into a {slug}\n// validate does a token conform to the mask's shape (soft, UI-only)\n//\n// Masks are advisory: the backend enforces only the security grammar\n// (isValidToken below mirrors rdb.ValidateToken). Style — lowercase-kebab,\n// prefixes — lives in the mask, applied here in the console, never on the wire.\n\n// The human-readable alphabet for generated ids: lowercase letters + digits minus\n// the ambiguous 0 o 1 l i, so a minted token can be read back off a label without\n// transcription errors.\nconst READABLE_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';\nconst DIGITS = '0123456789';\n\n// The security grammar the backend enforces (rdb.ValidateToken): letters (either\n// case), digits, hyphen and underscore, starting alphanumeric. Kept in sync by\n// hand — the same regex, mirrored for a pre-submit check so the user sees a bad\n// token before the server rejects it.\nconst TOKEN_GRAMMAR = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\n\n/** The maximum token length (mirrors rdb.MaxTokenLen). */\nexport const MAX_TOKEN_LEN = 128;\n\n/** isValidToken mirrors the backend security grammar for a pre-submit check. */\nexport function isValidToken(token: string): boolean {\n return token.length > 0 && token.length <= MAX_TOKEN_LEN && TOKEN_GRAMMAR.test(token);\n}\n\n/** A parsed mask segment: a literal run, or a typed placeholder. */\nexport type MaskSegment =\n | { kind: 'literal'; text: string }\n | { kind: 'placeholder'; type: 'alphanumeric' | 'numeric' | 'slug' | 'uuid' | 'unknown'; n?: number; raw: string };\n\nconst PLACEHOLDER = /\\{([a-zA-Z]+)(?:-(\\d+))?\\}/g;\nconst KNOWN = ['alphanumeric', 'numeric', 'slug', 'uuid'] as const;\n\n/** parseMask splits a mask into its literal and placeholder segments. */\nexport function parseMask(mask: string): MaskSegment[] {\n const segments: MaskSegment[] = [];\n let last = 0;\n for (const m of mask.matchAll(PLACEHOLDER)) {\n const at = m.index ?? 0;\n if (at > last) segments.push({ kind: 'literal', text: mask.slice(last, at) });\n const name = m[1].toLowerCase();\n const type = (KNOWN as readonly string[]).includes(name) ? (name as 'alphanumeric') : 'unknown';\n segments.push({ kind: 'placeholder', type, n: m[2] ? parseInt(m[2], 10) : undefined, raw: m[0] });\n last = at + m[0].length;\n }\n if (last < mask.length) segments.push({ kind: 'literal', text: mask.slice(last) });\n return segments;\n}\n\nexport interface GenerateOptions {\n /** A human string (e.g. the entity's name) that fills {slug} placeholders. */\n seed?: string;\n /** Injectable RNG in [0,1) for deterministic tests; defaults to Math.random. */\n random?: () => number;\n /** Injectable uuid for deterministic tests; defaults to crypto.randomUUID. */\n uuid?: () => string;\n}\n\nfunction randomUUID(): string {\n const g = globalThis as { crypto?: { randomUUID?: () => string } };\n if (g.crypto?.randomUUID) return g.crypto.randomUUID();\n // Fallback for environments without Web Crypto (not the console; belt & braces).\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n/**\n * generateToken fills a mask's placeholders to produce a concrete token:\n * {alphanumeric-N} → N readable chars, {numeric-N} → N digits, {uuid} → a uuid,\n * {slug} → the normalized seed (or a short readable id when no seed is given, so\n * a \"regenerate\" button always yields something). Literals pass through.\n */\nexport function generateToken(mask: string, opts: GenerateOptions = {}): string {\n const rand = opts.random ?? Math.random;\n const uuid = opts.uuid ?? randomUUID;\n // 🔴 The width is bounded before it is used. A mask may name any width the\n // regexp matches, and `Array.from({length: 1e20})` THROWS RangeError — which\n // made this function, called during render by the settings editor and by every\n // create form, a way to kill the page from a stored value. No width past\n // MAX_TOKEN_LEN can mint a legal token anyway, so an absurd one contributes\n // nothing rather than exploding. validateMask refuses such a mask outright;\n // this keeps generation safe for a mask stored before it did.\n const pick = (alphabet: string, n: number) =>\n n > MAX_TOKEN_LEN\n ? ''\n : Array.from({ length: n }, () => alphabet[Math.floor(rand() * alphabet.length)]).join('');\n\n return parseMask(mask)\n .map((seg) => {\n if (seg.kind === 'literal') return seg.text;\n switch (seg.type) {\n case 'alphanumeric':\n return pick(READABLE_ALPHABET, seg.n ?? 8);\n case 'numeric':\n return pick(DIGITS, seg.n ?? 4);\n case 'slug':\n return opts.seed ? normalizeToken(opts.seed) : pick(READABLE_ALPHABET, 6);\n case 'uuid':\n return uuid();\n default:\n return ''; // an unknown placeholder contributes nothing to a generated token\n }\n })\n .join('');\n}\n\n/**\n * normalizeToken kebab-cases a human string into a slug: lower-case, spaces and\n * underscores to hyphens, drop anything else, collapse and trim hyphens.\n * \"Ops Overview\" → \"ops-overview\".\n */\nexport function normalizeToken(input: string): string {\n return trimHyphens(\n input\n .toLowerCase()\n .trim()\n .replace(/[\\s_]+/g, '-')\n .replace(/[^a-z0-9-]+/g, '')\n .replace(/-+/g, '-'),\n );\n}\n\n/** Strips leading and trailing hyphens in linear time (no backtracking pattern). */\nfunction trimHyphens(s: string): string {\n let start = 0;\n let end = s.length;\n while (start < end && s.charCodeAt(start) === 45) start++;\n while (end > start && s.charCodeAt(end - 1) === 45) end--;\n return s.slice(start, end);\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * maskToRegExp compiles a mask into a whole-string RegExp for soft, UI-only\n * conformance checking. It is intentionally lenient (accepts either case in\n * alphanumeric/uuid segments) — the backend, not this, is the authority.\n */\nexport function maskToRegExp(mask: string): RegExp {\n const body = parseMask(mask)\n .map((seg) => {\n if (seg.kind === 'literal') return escapeRegExp(seg.text);\n switch (seg.type) {\n case 'alphanumeric':\n return `[A-Za-z0-9]{${seg.n ?? 8}}`;\n case 'numeric':\n return `[0-9]{${seg.n ?? 4}}`;\n case 'slug':\n return `[a-z0-9]+(?:-[a-z0-9]+)*`;\n case 'uuid':\n return `[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`;\n default:\n return escapeRegExp(seg.raw); // unknown placeholder must match itself literally\n }\n })\n .join('');\n return new RegExp(`^${body}$`);\n}\n\n/** conformsToMask reports whether a token matches the mask's shape (soft check). */\nexport function conformsToMask(mask: string, token: string): boolean {\n return maskToRegExp(mask).test(token);\n}\n\n/** The fixed seed sampleToken fills {slug} placeholders from. */\nconst SAMPLE_SEED = 'Sample Name';\n\n/**\n * sampleToken generates the token a mask would mint, deterministically. Same\n * generator as generateToken — a pinned RNG and uuid rather than a second\n * implementation, so a sample can never disagree with what a create form\n * actually produces.\n */\nexport function sampleToken(mask: string, seed: string = SAMPLE_SEED): string {\n return generateToken(mask, {\n seed,\n random: () => 0,\n uuid: () => '3f2b8c14-9d7e-4a51-b6c2-0e8d5a1f7b93',\n });\n}\n\n/**\n * Why a mask cannot mint usable tokens. Structured rather than a message\n * because this package is consumed by localized apps — the caller maps a reason\n * to its own wording.\n */\nexport type MaskProblem =\n | { reason: 'empty' }\n | { reason: 'unknownPlaceholder'; placeholder: string }\n | { reason: 'noPlaceholder' }\n | { reason: 'widthTooLarge'; placeholder: string; max: number }\n | { reason: 'invalidToken'; sample: string };\n\n/**\n * validateMask reports why a mask is unusable, or null when it is fine. It\n * mirrors the server (the tokenmask Go package), which is the authority and\n * refuses the same four things — every one of which fails SILENTLY otherwise:\n *\n * empty nothing to mint from\n * unknownPlaceholder contributes nothing, so \"dev-{sulg}\" mints \"dev-\"\n * noPlaceholder every entity mints the SAME token; the second create collides\n * invalidToken the minted sample is not a legal token (a space, a slash…)\n *\n * 🔴 Keep this NO STRICTER than the server. A check the server does not make\n * would refuse a mask the platform accepts, and the operator would have no way\n * to get past it.\n */\nexport function validateMask(mask: string): MaskProblem | null {\n if (mask === '') return { reason: 'empty' };\n let placeholders = 0;\n for (const seg of parseMask(mask)) {\n if (seg.kind !== 'placeholder') continue;\n if (seg.type === 'unknown') return { reason: 'unknownPlaceholder', placeholder: seg.raw };\n // 🔴 Checked BEFORE anything samples the mask. This function is called during\n // render, per keystroke — a width of 5e7 froze the tab for seconds building a\n // string nobody would ever see, and 1e20 threw RangeError and killed the\n // page. Neither reached the `invalidToken` check below, which is where a\n // reader would expect an over-long token to be caught.\n if (seg.n !== undefined && seg.n > MAX_TOKEN_LEN) {\n return { reason: 'widthTooLarge', placeholder: seg.raw, max: MAX_TOKEN_LEN };\n }\n placeholders++;\n }\n if (placeholders === 0) return { reason: 'noPlaceholder' };\n const sample = sampleToken(mask);\n if (!isValidToken(sample)) return { reason: 'invalidToken', sample };\n return null;\n}\n\n/**\n * resolveMask picks the mask for an entity type from a token-masks map, falling\n * back to the \"default\" entry and finally to a bare {slug}.\n */\nexport function resolveMask(masks: Record<string, string>, entityType: string): string {\n return masks[entityType] ?? masks.default ?? '{slug}';\n}\n"],
5
+ "mappings": ";AAyBO,IAAM,QAAQ;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,SAAS,MAAoB;AAC3C,SAAO,QAAQ,IAAI;AACrB;AAeO,SAAS,QAAQ,MAAoB;AAC1C,SAAO,KAAK,MAAM,GAAG,EAAE,CAAC;AAC1B;AASO,SAAS,eAAe,MAAqB;AAClD,SAAO,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,WAAW;AAC7D;AAQA,IAAI,cAAqD;AAElD,SAAS,mBAAmB,QAA+C;AAChF,gBAAc;AAChB;AAKA,IAAI,sBAA6D;AAE1D,SAAS,uBAAuB,QAA+C;AACpF,wBAAsB;AACxB;AAcA,IAAI,sBAAkD;AAE/C,SAAS,uBAAuB,SAA2C;AAChF,wBAAsB;AACxB;AAKA,eAAsB,mBAA2C;AAC/D,SAAO,cAAc,YAAY,IAAI;AACvC;AAIO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACE,SAEO,QAEA,QACP;AACA,UAAM,OAAO;AAJN;AAEA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAkDA,eAAsB,IACpB,MACA,aACG,CAAC,WAAW,OAAO,GAGJ;AAClB,QAAM,UAAkC,EAAE,gBAAgB,mBAAmB;AAC7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KAAK,cAAc;AAAA,IAC7E;AACA;AAAA,EACF;AACA,MAAI,iBAAiB,EAAG,QAAO,EAAE,QAAQ,gBAAgB;AACzD,QAAM,SAAS,YAAY,IAAI;AAC/B,MAAI,CAAC,aAAa,MAAM,EAAG,QAAO,EAAE,QAAQ,gBAAgB,OAAO;AACnE,SAAO;AACT;AAMO,SAAS,YAAY,OAA+B,YAA4B;AACrF,SAAO,MAAM,UAAU,KAAK,MAAM,WAAW;AAC/C;",
6
6
  "names": []
7
7
  }
package/dist/session.d.ts CHANGED
@@ -10,9 +10,9 @@ export interface SessionTokensOptions {
10
10
  /** Exchanges a refresh token for a new pair. */
11
11
  refresh: (refreshToken: string) => Promise<TokenPair>;
12
12
  /**
13
- * The session can no longer be sustained: the refresh token lapsed (`err` undefined), the
14
- * server refused the refresh (`err` is what it threw), or transient failures outlasted the
15
- * access token (`err` is the last one). The host clears its session here.
13
+ * The session can no longer be sustained: the refresh token lapsed (`err` undefined), or the
14
+ * server refused the refresh (`err` is what it threw). A transient failure never ends it. The
15
+ * host clears its session here.
16
16
  */
17
17
  onEnd: (err?: unknown) => void;
18
18
  /**
@@ -22,16 +22,74 @@ export interface SessionTokensOptions {
22
22
  * tokens never hands out one that is already due, which would refresh on every call.
23
23
  */
24
24
  skewSeconds?: number;
25
+ /**
26
+ * What `getAccessToken` does when the access token has expired and the refresh failed
27
+ * transiently (no response, a 5xx or a 429). Either way the session is kept and a later call
28
+ * tries again; `onEnd` is not called.
29
+ *
30
+ * - `'null'` (default): resolve to null, as in v1.6.
31
+ * - `'throw'`: reject with the refresh's error, so the request fails with the outage instead
32
+ * of being sent without a token. `subscribe` treats that error as transient: the
33
+ * subscription's reconnect retries it.
34
+ */
35
+ transientRefreshErrors?: 'null' | 'throw';
25
36
  }
26
37
  export interface SessionTokens {
27
- /** A usable access token, refreshing first when it is within the skew of expiry; null when signed out or ended. */
38
+ /**
39
+ * Force one shared refresh after a 401, even though the held access token has not expired.
40
+ * Resolves to the refreshed token, or null when the session is signed out, was replaced since
41
+ * `rejectedToken` was sent, or has ended (the refresh token lapsed or the server refused the
42
+ * refresh). Rejects with the refresh's error when it failed transiently: the session is kept,
43
+ * and a later call tries again. Never hands back the rejected token. It rejects whatever
44
+ * `transientRefreshErrors` says: a null here tells `setUnauthorizedHandler` the session ended.
45
+ *
46
+ * Optional HERE because v1.6 had no such member, and a host that builds its own
47
+ * `SessionTokens` must still type-check. What `createSessionTokens` returns always has it:
48
+ * see `ManagedSessionTokens`. Without it a host has no 401 recovery, as in v1.6.
49
+ */
50
+ forceRefresh?: (rejectedToken?: string) => Promise<string | null>;
51
+ /**
52
+ * A usable access token, refreshing first when it is within the skew of expiry; null when
53
+ * signed out or ended. When the access token has expired and the refresh failed transiently,
54
+ * the session is kept and a later call tries again; the call resolves to null, or rejects with
55
+ * the refresh's error under `transientRefreshErrors: 'throw'`.
56
+ */
28
57
  getAccessToken: () => Promise<string | null>;
29
58
  /** Forget any in-flight refresh (the host cleared or replaced the session itself). */
30
59
  reset: () => void;
31
60
  /**
32
- * Refresh ahead of expiry on a timer, retrying a transient failure with backoff until the
33
- * access token expires. Returns a stop function.
61
+ * Refresh ahead of expiry on a timer, retrying a transient failure with backoff for as long
62
+ * as the refresh token is valid. Returns a stop function.
34
63
  */
35
64
  startAutoRefresh: () => () => void;
36
65
  }
37
- export declare function createSessionTokens(opts: SessionTokensOptions): SessionTokens;
66
+ /** What `createSessionTokens` returns: a `SessionTokens` whose `forceRefresh` is always present. */
67
+ export interface ManagedSessionTokens extends SessionTokens {
68
+ forceRefresh: (rejectedToken?: string) => Promise<string | null>;
69
+ /**
70
+ * Run a host operation that spends the held refresh token and returns the pair that replaces
71
+ * it (a step-up, say), serialized with every refresh, so the two never spend one refresh
72
+ * token between them. It first makes sure there is a usable access token (refreshing if due)
73
+ * and waits out any refresh already running; while `spend` runs, a refresh anyone asks for
74
+ * waits for it and shares the pair it yields. The pair is applied like a refreshed one.
75
+ *
76
+ * Resolves to the new access token. Rejects with `spend`'s error when it fails (the session
77
+ * is kept, and refreshes then go ahead as usual), and with an Error when the session is
78
+ * signed out, has ended, or was replaced while `spend` ran (its pair is then dropped).
79
+ *
80
+ * While `spend` runs, the held access token is handed out without waiting as long as it has
81
+ * not expired, because `spend`'s own request asks for one. A `forceRefresh` naming that access
82
+ * token as rejected (a 401, which may be `spend`'s own request) rejects with a 401 error and
83
+ * keeps the session rather than waiting on `spend`; a later 401 recovers as usual.
84
+ */
85
+ exchange: (spend: (refreshToken: string) => Promise<TokenPair>) => Promise<string>;
86
+ }
87
+ /**
88
+ * Whether a refresh failure is worth retrying: the request never got a response (status 0),
89
+ * or the server answered 5xx or 429 without a GraphQL error. Anything else (a GraphQL error
90
+ * such as an invalid or revoked refresh token or SSO_REQUIRED, a 400 or 401, or an error that
91
+ * is not a transport error at all) is the server's answer, and asking again would repeat it.
92
+ * Exported within the package (not from index.ts): subscribe.ts reads the same predicate.
93
+ */
94
+ export declare function isTransientRefreshError(err: unknown): boolean;
95
+ export declare function createSessionTokens(opts: SessionTokensOptions): ManagedSessionTokens;
@@ -1,9 +1,15 @@
1
1
  import type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';
2
+ import type { GraphQLFormattedError } from 'graphql';
2
3
  import { type Area } from './transport';
3
4
  export declare const RETRY_CEILING_MS = 30000;
4
5
  export declare function retryDelayMs(retries: number, random?: () => number): number;
5
6
  export interface SubscriptionSink<T> {
6
7
  next: (data: T) => void;
8
+ /**
9
+ * GraphQL errors carried by a result (for example a validation refusal sent as an
10
+ * error-only result before `complete`). Called before `next` when a result carries both.
11
+ */
12
+ errors?: (errors: ReadonlyArray<GraphQLFormattedError>) => void;
7
13
  error?: (err: unknown) => void;
8
14
  complete?: () => void;
9
15
  connected?: (wasRetry: boolean) => void;
@@ -19,6 +19,18 @@ export declare function areaKey(area: Area): string;
19
19
  export declare function isIdentityArea(area: Area): boolean;
20
20
  export declare function setAuthTokenGetter(getter: (() => Promise<string | null>) | null): void;
21
21
  export declare function setIdentityTokenGetter(getter: (() => Promise<string | null>) | null): void;
22
+ /** Opt-in HTTP 401 recovery. Anonymous requests never invoke these callbacks. */
23
+ export interface UnauthorizedHandler {
24
+ /**
25
+ * Return a refreshed token for one replay, or null when recovery is unavailable or was refused
26
+ * (onEnd then runs). Throw when the refresh failed transiently: the request fails with that
27
+ * error and onEnd does not run, so the session is kept.
28
+ */
29
+ refresh: (token: string, identity: boolean) => Promise<string | null>;
30
+ /** Recovery failed or the replay was refused. Only end the session owning this token. */
31
+ onEnd: (error: GraphQLRequestError, token: string, identity: boolean) => void;
32
+ }
33
+ export declare function setUnauthorizedHandler(handler: UnauthorizedHandler | null): void;
22
34
  export declare function resolveAuthToken(): Promise<string | null>;
23
35
  export declare class GraphQLRequestError extends Error {
24
36
  /** HTTP status, or 0 for a transport-level failure. */
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@devicechain/client",
3
- "version": "1.6.0-rc.1",
3
+ "version": "1.7.0-rc.1",
4
4
  "description": "DeviceChain client SDK — two-tier auth, typed GraphQL operations, and graphql-ws subscriptions over the client wire.",
5
5
  "keywords": [
6
6
  "devicechain",
7
7
  "iot",
8
+ "iot-platform",
8
9
  "graphql",
9
10
  "sdk",
10
11
  "typescript"