@spacelr/sdk 0.19.4 → 0.19.6
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/dist/index.d.mts +46 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +200 -10
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +200 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -206,7 +206,7 @@ var HttpClient = class {
|
|
|
206
206
|
await this.tokenManager.notifyAuthLost("unauthorized");
|
|
207
207
|
return false;
|
|
208
208
|
}
|
|
209
|
-
const hadRefreshToken = await this.tokenManager.
|
|
209
|
+
const hadRefreshToken = await this.tokenManager.canRenew();
|
|
210
210
|
const refreshed = await this.tokenManager.forceRefresh();
|
|
211
211
|
if (refreshed) return true;
|
|
212
212
|
if (hadRefreshToken) return false;
|
|
@@ -442,6 +442,7 @@ var BrowserTokenStorage = class {
|
|
|
442
442
|
var TokenManager = class {
|
|
443
443
|
constructor(storage, refreshBufferSeconds = 60, refreshLockName = "spacelr_token_refresh") {
|
|
444
444
|
this.refreshCallback = null;
|
|
445
|
+
this.reauthCallback = null;
|
|
445
446
|
this.refreshPromise = null;
|
|
446
447
|
this.tokenRefreshedListeners = /* @__PURE__ */ new Set();
|
|
447
448
|
this.authLostListeners = /* @__PURE__ */ new Set();
|
|
@@ -461,6 +462,18 @@ var TokenManager = class {
|
|
|
461
462
|
setRefreshCallback(callback) {
|
|
462
463
|
this.refreshCallback = callback;
|
|
463
464
|
}
|
|
465
|
+
/**
|
|
466
|
+
* #1073: a session without a refresh token (API-token sign-in) recovers by
|
|
467
|
+
* re-authenticating through this callback instead. `null` removes it.
|
|
468
|
+
*/
|
|
469
|
+
setReauthCallback(callback) {
|
|
470
|
+
this.reauthCallback = callback;
|
|
471
|
+
}
|
|
472
|
+
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
473
|
+
async canRenew() {
|
|
474
|
+
if (this.reauthCallback) return true;
|
|
475
|
+
return this.hasRefreshToken();
|
|
476
|
+
}
|
|
464
477
|
async getAccessToken() {
|
|
465
478
|
const tokens = await this.storage.getTokens();
|
|
466
479
|
if (!tokens) return null;
|
|
@@ -478,10 +491,12 @@ var TokenManager = class {
|
|
|
478
491
|
if (this.pendingClear) await this.pendingClear;
|
|
479
492
|
const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
|
|
480
493
|
const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
|
|
494
|
+
this.reauthCallback = null;
|
|
481
495
|
await this.storage.setTokens(normalised);
|
|
482
496
|
this.authLostEmitted = false;
|
|
483
497
|
}
|
|
484
498
|
async clearTokens() {
|
|
499
|
+
this.reauthCallback = null;
|
|
485
500
|
await this.storage.clearTokens();
|
|
486
501
|
this.refreshPromise = null;
|
|
487
502
|
this.authLostEmitted = false;
|
|
@@ -563,6 +578,7 @@ var TokenManager = class {
|
|
|
563
578
|
async notifyAuthLost(reason) {
|
|
564
579
|
if (this.authLostEmitted) return;
|
|
565
580
|
this.authLostEmitted = true;
|
|
581
|
+
this.reauthCallback = null;
|
|
566
582
|
this.pendingClear = this.storage.clearTokens().catch(() => {
|
|
567
583
|
});
|
|
568
584
|
await this.pendingClear;
|
|
@@ -599,12 +615,15 @@ var TokenManager = class {
|
|
|
599
615
|
return Date.now() >= tokens.expiresAt * 1e3;
|
|
600
616
|
}
|
|
601
617
|
shouldRefresh(tokens) {
|
|
602
|
-
if (!tokens.expiresAt || !tokens.refreshToken) return false;
|
|
618
|
+
if (!tokens.expiresAt || !tokens.refreshToken && !this.reauthCallback) return false;
|
|
603
619
|
const bufferMs = this.refreshBufferSeconds * 1e3;
|
|
604
620
|
return Date.now() >= tokens.expiresAt * 1e3 - bufferMs;
|
|
605
621
|
}
|
|
606
622
|
async tryRefresh(tokens) {
|
|
607
|
-
if (!tokens.refreshToken
|
|
623
|
+
if (!tokens.refreshToken) {
|
|
624
|
+
return this.reauthCallback ? this.singleFlight(() => this.executeReauth()) : null;
|
|
625
|
+
}
|
|
626
|
+
if (!this.refreshCallback) return null;
|
|
608
627
|
if (this.refreshPromise) {
|
|
609
628
|
try {
|
|
610
629
|
return await this.refreshPromise;
|
|
@@ -621,6 +640,43 @@ var TokenManager = class {
|
|
|
621
640
|
this.refreshPromise = null;
|
|
622
641
|
}
|
|
623
642
|
}
|
|
643
|
+
/** Deduplicate concurrent renewals; followers get null on failure, like the leader. */
|
|
644
|
+
async singleFlight(run) {
|
|
645
|
+
if (!this.refreshPromise) {
|
|
646
|
+
this.refreshPromise = run();
|
|
647
|
+
try {
|
|
648
|
+
return await this.refreshPromise;
|
|
649
|
+
} catch {
|
|
650
|
+
return null;
|
|
651
|
+
} finally {
|
|
652
|
+
this.refreshPromise = null;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
try {
|
|
656
|
+
return await this.refreshPromise;
|
|
657
|
+
} catch {
|
|
658
|
+
return null;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/** #1073: same auth-loss classification as doRefresh, for re-authentication. */
|
|
662
|
+
async executeReauth() {
|
|
663
|
+
const callback = this.reauthCallback;
|
|
664
|
+
const superseded = () => this.reauthCallback !== callback;
|
|
665
|
+
let newTokens;
|
|
666
|
+
try {
|
|
667
|
+
newTokens = await callback();
|
|
668
|
+
} catch (error) {
|
|
669
|
+
if (superseded()) throw new Error("re-authentication superseded");
|
|
670
|
+
if (!this.isTransientTransportError(error)) {
|
|
671
|
+
await this.notifyAuthLost("refresh-failed");
|
|
672
|
+
}
|
|
673
|
+
throw error;
|
|
674
|
+
}
|
|
675
|
+
if (superseded()) throw new Error("re-authentication superseded");
|
|
676
|
+
await this.storage.setTokens(newTokens);
|
|
677
|
+
this.emitTokenRefreshed(newTokens);
|
|
678
|
+
return newTokens;
|
|
679
|
+
}
|
|
624
680
|
async executeRefresh(refreshToken) {
|
|
625
681
|
return this.withCrossTabLock(() => this.doRefresh(refreshToken));
|
|
626
682
|
}
|
|
@@ -678,6 +734,7 @@ var FileVisibility = /* @__PURE__ */ ((FileVisibility2) => {
|
|
|
678
734
|
FileVisibility2["PUBLIC"] = "public";
|
|
679
735
|
return FileVisibility2;
|
|
680
736
|
})(FileVisibility || {});
|
|
737
|
+
var API_TOKEN_GRANT = "urn:spacelr:grant-type:api-token";
|
|
681
738
|
var GrantType = /* @__PURE__ */ ((GrantType2) => {
|
|
682
739
|
GrantType2["AUTHORIZATION_CODE"] = "authorization_code";
|
|
683
740
|
GrantType2["CLIENT_CREDENTIALS"] = "client_credentials";
|
|
@@ -739,6 +796,22 @@ async function generatePKCEChallenge() {
|
|
|
739
796
|
// libs/sdk/src/core/realtime.ts
|
|
740
797
|
import { io } from "socket.io-client";
|
|
741
798
|
var REBUILD_RETRY_DELAY_MS = 5e3;
|
|
799
|
+
var SOCKET_TOKEN_REFRESH_LEAD_MS = 45e3;
|
|
800
|
+
var SOCKET_TOKEN_REFRESH_JITTER_MS = 15e3;
|
|
801
|
+
var SOCKET_TOKEN_REFRESH_RETRY_MS = 5e3;
|
|
802
|
+
var SOCKET_TOKEN_REFRESH_RETRY_MAX_MS = 3e4;
|
|
803
|
+
var SERVER_DISCONNECT_REBUILD_DELAY_MS = 1e3;
|
|
804
|
+
function jwtExpiryMs(token) {
|
|
805
|
+
const payload = token.split(".")[1];
|
|
806
|
+
if (!payload) return null;
|
|
807
|
+
try {
|
|
808
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
809
|
+
const exp = JSON.parse(json).exp;
|
|
810
|
+
return typeof exp === "number" ? exp * 1e3 : null;
|
|
811
|
+
} catch {
|
|
812
|
+
return null;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
742
815
|
var PERMANENT_STREAM_ACK_ERRORS = /* @__PURE__ */ new Set([
|
|
743
816
|
"not-stream-collection",
|
|
744
817
|
"Collection not found",
|
|
@@ -929,6 +1002,18 @@ var RealtimeClient = class {
|
|
|
929
1002
|
// Scheduled retry after a failed `rebuildSocket()`; cleared when it fires
|
|
930
1003
|
// or when `disconnect()` tears down.
|
|
931
1004
|
this.rebuildRetryTimer = null;
|
|
1005
|
+
// #1078 — the access token the open socket was last authenticated with, and
|
|
1006
|
+
// the timer that replaces it before it expires.
|
|
1007
|
+
this.socketToken = null;
|
|
1008
|
+
this.socketTokenTimer = null;
|
|
1009
|
+
this.socketTokenRetries = 0;
|
|
1010
|
+
// The token of a socket the server closed. If the next connect would use the
|
|
1011
|
+
// same token again, it is renewed first (once).
|
|
1012
|
+
this.serverClosedToken = null;
|
|
1013
|
+
// `reauthenticate` messages whose `authenticated` reply is still due. Such a
|
|
1014
|
+
// reply confirms a token swap on a live socket, not a new connection, so the
|
|
1015
|
+
// subscriptions must not be sent again for it.
|
|
1016
|
+
this.pendingReauthReplies = 0;
|
|
932
1017
|
this.connectionState = "disconnected";
|
|
933
1018
|
this.connectionStateListeners = /* @__PURE__ */ new Set();
|
|
934
1019
|
this.streamSubscriptions = /* @__PURE__ */ new Map();
|
|
@@ -1172,6 +1257,7 @@ var RealtimeClient = class {
|
|
|
1172
1257
|
clearTimeout(this.rebuildRetryTimer);
|
|
1173
1258
|
this.rebuildRetryTimer = null;
|
|
1174
1259
|
}
|
|
1260
|
+
this.clearSocketTokenTimer();
|
|
1175
1261
|
if (this.unsubscribeFromTokenRefreshed) {
|
|
1176
1262
|
this.unsubscribeFromTokenRefreshed();
|
|
1177
1263
|
this.unsubscribeFromTokenRefreshed = null;
|
|
@@ -1299,10 +1385,16 @@ var RealtimeClient = class {
|
|
|
1299
1385
|
this.socket = null;
|
|
1300
1386
|
previous.disconnect();
|
|
1301
1387
|
}
|
|
1302
|
-
|
|
1388
|
+
let token = await this.config.getToken();
|
|
1389
|
+
if (token && token === this.serverClosedToken) {
|
|
1390
|
+
this.serverClosedToken = null;
|
|
1391
|
+
await this.config.refreshToken?.().catch(() => null);
|
|
1392
|
+
token = await this.config.getToken();
|
|
1393
|
+
}
|
|
1303
1394
|
if (!token) {
|
|
1304
1395
|
throw new Error("No authentication token available");
|
|
1305
1396
|
}
|
|
1397
|
+
this.socketToken = token;
|
|
1306
1398
|
const wsUrl = this.config.baseUrl.replace(/\/api\/v\d+\/?$/, "");
|
|
1307
1399
|
return new Promise((resolve, reject) => {
|
|
1308
1400
|
let initialConnect = true;
|
|
@@ -1311,6 +1403,7 @@ var RealtimeClient = class {
|
|
|
1311
1403
|
auth: async (cb) => {
|
|
1312
1404
|
try {
|
|
1313
1405
|
const freshToken = await this.config.getToken();
|
|
1406
|
+
if (freshToken) this.socketToken = freshToken;
|
|
1314
1407
|
cb({ token: freshToken });
|
|
1315
1408
|
} catch {
|
|
1316
1409
|
cb({ token: null });
|
|
@@ -1340,6 +1433,7 @@ var RealtimeClient = class {
|
|
|
1340
1433
|
if (this.disposed) return;
|
|
1341
1434
|
if (this.socket !== socket) return;
|
|
1342
1435
|
this.setConnectionState("connected");
|
|
1436
|
+
this.scheduleSocketTokenRefresh();
|
|
1343
1437
|
if (initialConnect) {
|
|
1344
1438
|
initialConnect = false;
|
|
1345
1439
|
if (this.socket) {
|
|
@@ -1372,14 +1466,14 @@ var RealtimeClient = class {
|
|
|
1372
1466
|
}
|
|
1373
1467
|
if (this.config.onTokenRefreshed && !this.unsubscribeFromTokenRefreshed) {
|
|
1374
1468
|
this.unsubscribeFromTokenRefreshed = this.config.onTokenRefreshed(
|
|
1375
|
-
(accessToken) =>
|
|
1376
|
-
this.socket?.emit("reauthenticate", { token: accessToken });
|
|
1377
|
-
}
|
|
1469
|
+
(accessToken) => this.reauthenticateSocket(accessToken)
|
|
1378
1470
|
);
|
|
1379
1471
|
}
|
|
1380
1472
|
if (this.subscriptions.size > 0) this.resubscribeAll();
|
|
1381
1473
|
if (this.streamSubscriptions.size > 0) void this.resubscribeAllStreams();
|
|
1382
1474
|
resolve();
|
|
1475
|
+
} else if (this.pendingReauthReplies > 0) {
|
|
1476
|
+
this.pendingReauthReplies -= 1;
|
|
1383
1477
|
} else {
|
|
1384
1478
|
this.resubscribeAll();
|
|
1385
1479
|
void this.resubscribeAllStreams();
|
|
@@ -1459,11 +1553,17 @@ var RealtimeClient = class {
|
|
|
1459
1553
|
}
|
|
1460
1554
|
}
|
|
1461
1555
|
});
|
|
1462
|
-
socket.on("disconnect", () => {
|
|
1556
|
+
socket.on("disconnect", (reason) => {
|
|
1557
|
+
if (this.socket === socket) this.pendingReauthReplies = 0;
|
|
1463
1558
|
if (this.disposed) return;
|
|
1464
1559
|
if (initialConnect) return;
|
|
1465
1560
|
if (this.socket !== socket) return;
|
|
1466
1561
|
this.setConnectionState("reconnecting");
|
|
1562
|
+
if (reason === "io server disconnect") {
|
|
1563
|
+
this.serverClosedToken = this.socketToken;
|
|
1564
|
+
this.clearSocketTokenTimer();
|
|
1565
|
+
this.scheduleRebuildRetry(SERVER_DISCONNECT_REBUILD_DELAY_MS);
|
|
1566
|
+
}
|
|
1467
1567
|
});
|
|
1468
1568
|
});
|
|
1469
1569
|
}
|
|
@@ -1525,7 +1625,72 @@ var RealtimeClient = class {
|
|
|
1525
1625
|
} catch {
|
|
1526
1626
|
}
|
|
1527
1627
|
}
|
|
1528
|
-
|
|
1628
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
1629
|
+
reauthenticateSocket(accessToken) {
|
|
1630
|
+
if (accessToken === this.socketToken) return;
|
|
1631
|
+
if (!this.socket?.connected) return;
|
|
1632
|
+
this.socketToken = accessToken;
|
|
1633
|
+
this.pendingReauthReplies += 1;
|
|
1634
|
+
this.socket.emit("reauthenticate", { token: accessToken });
|
|
1635
|
+
this.scheduleSocketTokenRefresh();
|
|
1636
|
+
}
|
|
1637
|
+
clearSocketTokenTimer() {
|
|
1638
|
+
if (this.socketTokenTimer) {
|
|
1639
|
+
clearTimeout(this.socketTokenTimer);
|
|
1640
|
+
this.socketTokenTimer = null;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
1645
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
1646
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1647
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1648
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1649
|
+
*/
|
|
1650
|
+
scheduleSocketTokenRefresh(retryMs) {
|
|
1651
|
+
this.clearSocketTokenTimer();
|
|
1652
|
+
if (retryMs === void 0) this.socketTokenRetries = 0;
|
|
1653
|
+
if (this.disposed || !this.socketToken) return;
|
|
1654
|
+
const expiresAt = jwtExpiryMs(this.socketToken);
|
|
1655
|
+
if (expiresAt === null) return;
|
|
1656
|
+
const remaining = expiresAt - Date.now();
|
|
1657
|
+
const lead = Math.min(
|
|
1658
|
+
SOCKET_TOKEN_REFRESH_LEAD_MS + Math.random() * SOCKET_TOKEN_REFRESH_JITTER_MS,
|
|
1659
|
+
remaining / 2
|
|
1660
|
+
);
|
|
1661
|
+
const delay = retryMs ?? Math.max(1e3, remaining - lead);
|
|
1662
|
+
this.socketTokenTimer = setTimeout(() => {
|
|
1663
|
+
this.socketTokenTimer = null;
|
|
1664
|
+
void this.refreshSocketToken(expiresAt);
|
|
1665
|
+
}, delay);
|
|
1666
|
+
this.socketTokenTimer.unref?.();
|
|
1667
|
+
}
|
|
1668
|
+
async refreshSocketToken(expiresAt) {
|
|
1669
|
+
if (this.disposed || !this.socket) return;
|
|
1670
|
+
const previous = this.socketToken;
|
|
1671
|
+
let token = null;
|
|
1672
|
+
try {
|
|
1673
|
+
token = await this.config.getToken();
|
|
1674
|
+
} catch {
|
|
1675
|
+
}
|
|
1676
|
+
if (this.disposed || !this.socket) return;
|
|
1677
|
+
if (this.socketToken !== previous) return;
|
|
1678
|
+
if (token && token !== previous) {
|
|
1679
|
+
this.reauthenticateSocket(token);
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
const remaining = expiresAt - Date.now();
|
|
1683
|
+
if (remaining <= 0) return;
|
|
1684
|
+
const backoff = Math.min(
|
|
1685
|
+
SOCKET_TOKEN_REFRESH_RETRY_MS * 2 ** this.socketTokenRetries,
|
|
1686
|
+
SOCKET_TOKEN_REFRESH_RETRY_MAX_MS
|
|
1687
|
+
);
|
|
1688
|
+
this.socketTokenRetries += 1;
|
|
1689
|
+
this.scheduleSocketTokenRefresh(
|
|
1690
|
+
Math.min(backoff, Math.max(SOCKET_TOKEN_REFRESH_RETRY_MS, remaining / 2))
|
|
1691
|
+
);
|
|
1692
|
+
}
|
|
1693
|
+
scheduleRebuildRetry(delayMs = REBUILD_RETRY_DELAY_MS) {
|
|
1529
1694
|
if (this.disposed || this.rebuildRetryTimer) return;
|
|
1530
1695
|
this.rebuildRetryTimer = setTimeout(() => {
|
|
1531
1696
|
this.rebuildRetryTimer = null;
|
|
@@ -1535,7 +1700,7 @@ var RealtimeClient = class {
|
|
|
1535
1700
|
}
|
|
1536
1701
|
if (this.socket?.connected) return;
|
|
1537
1702
|
void this.rebuildSocket();
|
|
1538
|
-
},
|
|
1703
|
+
}, delayMs);
|
|
1539
1704
|
this.rebuildRetryTimer.unref?.();
|
|
1540
1705
|
}
|
|
1541
1706
|
ensureWakeListeners() {
|
|
@@ -2154,6 +2319,30 @@ var AuthModule = class _AuthModule {
|
|
|
2154
2319
|
}
|
|
2155
2320
|
return url.toString();
|
|
2156
2321
|
}
|
|
2322
|
+
/**
|
|
2323
|
+
* #1073: sign in as a machine user with a project API token (`slr_at_…`).
|
|
2324
|
+
* The server returns a short-lived access token and no refresh token; when
|
|
2325
|
+
* it expires or is rejected, the SDK exchanges the API token again. The API
|
|
2326
|
+
* token stays in memory only and is forgotten on logout. Never use this in a
|
|
2327
|
+
* browser: an API token is a long-lived secret.
|
|
2328
|
+
*/
|
|
2329
|
+
async loginWithApiToken(apiToken) {
|
|
2330
|
+
const exchange = async () => {
|
|
2331
|
+
const response = await this.http.request({
|
|
2332
|
+
method: "POST",
|
|
2333
|
+
path: this.config.tokenEndpoint ?? "/auth/token",
|
|
2334
|
+
body: { grant_type: API_TOKEN_GRANT, client_id: this.config.clientId, api_token: apiToken },
|
|
2335
|
+
skipAuthRefresh: true
|
|
2336
|
+
});
|
|
2337
|
+
return {
|
|
2338
|
+
accessToken: response.access_token,
|
|
2339
|
+
expiresAt: response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0
|
|
2340
|
+
};
|
|
2341
|
+
};
|
|
2342
|
+
const tokens = await exchange();
|
|
2343
|
+
await this.installSession(tokens);
|
|
2344
|
+
this.tokenManager.setReauthCallback(exchange);
|
|
2345
|
+
}
|
|
2157
2346
|
async exchangeCode(params) {
|
|
2158
2347
|
const body = {
|
|
2159
2348
|
grant_type: params.grantType ?? "authorization_code" /* AUTHORIZATION_CODE */,
|
|
@@ -4592,6 +4781,7 @@ function createClient(config) {
|
|
|
4592
4781
|
const realtime = new RealtimeClient({
|
|
4593
4782
|
baseUrl: config.apiUrl,
|
|
4594
4783
|
getToken: () => tokenManager.getAccessToken(),
|
|
4784
|
+
refreshToken: () => tokenManager.forceRefresh(),
|
|
4595
4785
|
onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
|
|
4596
4786
|
});
|
|
4597
4787
|
const notifications = new NotificationsModule(httpClient, {
|