@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.d.mts
CHANGED
|
@@ -467,6 +467,8 @@ interface UploadProgress {
|
|
|
467
467
|
}
|
|
468
468
|
|
|
469
469
|
type RefreshCallback = (refreshToken: string) => Promise<StoredTokens>;
|
|
470
|
+
/** #1073: renews a session that has no refresh token (API-token sign-in). */
|
|
471
|
+
type ReauthCallback = () => Promise<StoredTokens>;
|
|
470
472
|
/**
|
|
471
473
|
* Reasons the SDK reports a **server-confirmed** auth loss via `onAuthLost`.
|
|
472
474
|
* A transient refresh failure (network/transport, a 5xx, a 429 or a 408) is NOT
|
|
@@ -481,6 +483,7 @@ declare class TokenManager {
|
|
|
481
483
|
private refreshBufferSeconds;
|
|
482
484
|
private refreshLockName;
|
|
483
485
|
private refreshCallback;
|
|
486
|
+
private reauthCallback;
|
|
484
487
|
private refreshPromise;
|
|
485
488
|
private tokenRefreshedListeners;
|
|
486
489
|
private authLostListeners;
|
|
@@ -488,6 +491,13 @@ declare class TokenManager {
|
|
|
488
491
|
private pendingClear;
|
|
489
492
|
constructor(storage?: TokenStorage, refreshBufferSeconds?: number, refreshLockName?: string);
|
|
490
493
|
setRefreshCallback(callback: RefreshCallback): void;
|
|
494
|
+
/**
|
|
495
|
+
* #1073: a session without a refresh token (API-token sign-in) recovers by
|
|
496
|
+
* re-authenticating through this callback instead. `null` removes it.
|
|
497
|
+
*/
|
|
498
|
+
setReauthCallback(callback: ReauthCallback | null): void;
|
|
499
|
+
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
500
|
+
canRenew(): Promise<boolean>;
|
|
491
501
|
getAccessToken(): Promise<string | null>;
|
|
492
502
|
setTokens(tokens: StoredTokens): Promise<void>;
|
|
493
503
|
clearTokens(): Promise<void>;
|
|
@@ -552,6 +562,10 @@ declare class TokenManager {
|
|
|
552
562
|
private isTokenExpired;
|
|
553
563
|
private shouldRefresh;
|
|
554
564
|
private tryRefresh;
|
|
565
|
+
/** Deduplicate concurrent renewals; followers get null on failure, like the leader. */
|
|
566
|
+
private singleFlight;
|
|
567
|
+
/** #1073: same auth-loss classification as doRefresh, for re-authentication. */
|
|
568
|
+
private executeReauth;
|
|
555
569
|
private executeRefresh;
|
|
556
570
|
private doRefresh;
|
|
557
571
|
private safeGetTokens;
|
|
@@ -764,6 +778,13 @@ interface RealtimeConfig {
|
|
|
764
778
|
* dropping the connection.
|
|
765
779
|
*/
|
|
766
780
|
onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
|
|
781
|
+
/**
|
|
782
|
+
* Optional forced renewal of the access token, whatever its remaining
|
|
783
|
+
* lifetime. Used once after the server closed the socket although its token
|
|
784
|
+
* had not expired (the token was revoked): renewing either yields a usable
|
|
785
|
+
* token or reports the lost session to the consumer right away.
|
|
786
|
+
*/
|
|
787
|
+
refreshToken?: () => Promise<string | null>;
|
|
767
788
|
}
|
|
768
789
|
type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated' | 'evicted' | 'auth-unavailable' | 'log-reset';
|
|
769
790
|
interface StreamGapInfo {
|
|
@@ -828,6 +849,11 @@ declare class RealtimeClient {
|
|
|
828
849
|
private onOnline;
|
|
829
850
|
private disposed;
|
|
830
851
|
private rebuildRetryTimer;
|
|
852
|
+
private socketToken;
|
|
853
|
+
private socketTokenTimer;
|
|
854
|
+
private socketTokenRetries;
|
|
855
|
+
private serverClosedToken;
|
|
856
|
+
private pendingReauthReplies;
|
|
831
857
|
private connectionState;
|
|
832
858
|
private connectionStateListeners;
|
|
833
859
|
private streamSubscriptions;
|
|
@@ -964,6 +990,18 @@ declare class RealtimeClient {
|
|
|
964
990
|
* so a throwing consumer cannot cancel recovery or make subscribe reject.
|
|
965
991
|
*/
|
|
966
992
|
private keepRetrying;
|
|
993
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
994
|
+
private reauthenticateSocket;
|
|
995
|
+
private clearSocketTokenTimer;
|
|
996
|
+
/**
|
|
997
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
998
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
999
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1000
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1001
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1002
|
+
*/
|
|
1003
|
+
private scheduleSocketTokenRefresh;
|
|
1004
|
+
private refreshSocketToken;
|
|
967
1005
|
private scheduleRebuildRetry;
|
|
968
1006
|
private ensureWakeListeners;
|
|
969
1007
|
private detachWakeListeners;
|
|
@@ -1176,6 +1214,14 @@ declare class AuthModule {
|
|
|
1176
1214
|
}>;
|
|
1177
1215
|
getUserInfo(): Promise<UserInfo>;
|
|
1178
1216
|
getAuthorizationUrl(params: AuthorizationUrlParams): string;
|
|
1217
|
+
/**
|
|
1218
|
+
* #1073: sign in as a machine user with a project API token (`slr_at_…`).
|
|
1219
|
+
* The server returns a short-lived access token and no refresh token; when
|
|
1220
|
+
* it expires or is rejected, the SDK exchanges the API token again. The API
|
|
1221
|
+
* token stays in memory only and is forgotten on logout. Never use this in a
|
|
1222
|
+
* browser: an API token is a long-lived secret.
|
|
1223
|
+
*/
|
|
1224
|
+
loginWithApiToken(apiToken: string): Promise<void>;
|
|
1179
1225
|
exchangeCode(params: ExchangeCodeParams): Promise<TokenResponse>;
|
|
1180
1226
|
generatePKCE(): Promise<PKCEChallenge>;
|
|
1181
1227
|
getOpenIDConfiguration(): Promise<OpenIDConfiguration>;
|
package/dist/index.d.ts
CHANGED
|
@@ -467,6 +467,8 @@ interface UploadProgress {
|
|
|
467
467
|
}
|
|
468
468
|
|
|
469
469
|
type RefreshCallback = (refreshToken: string) => Promise<StoredTokens>;
|
|
470
|
+
/** #1073: renews a session that has no refresh token (API-token sign-in). */
|
|
471
|
+
type ReauthCallback = () => Promise<StoredTokens>;
|
|
470
472
|
/**
|
|
471
473
|
* Reasons the SDK reports a **server-confirmed** auth loss via `onAuthLost`.
|
|
472
474
|
* A transient refresh failure (network/transport, a 5xx, a 429 or a 408) is NOT
|
|
@@ -481,6 +483,7 @@ declare class TokenManager {
|
|
|
481
483
|
private refreshBufferSeconds;
|
|
482
484
|
private refreshLockName;
|
|
483
485
|
private refreshCallback;
|
|
486
|
+
private reauthCallback;
|
|
484
487
|
private refreshPromise;
|
|
485
488
|
private tokenRefreshedListeners;
|
|
486
489
|
private authLostListeners;
|
|
@@ -488,6 +491,13 @@ declare class TokenManager {
|
|
|
488
491
|
private pendingClear;
|
|
489
492
|
constructor(storage?: TokenStorage, refreshBufferSeconds?: number, refreshLockName?: string);
|
|
490
493
|
setRefreshCallback(callback: RefreshCallback): void;
|
|
494
|
+
/**
|
|
495
|
+
* #1073: a session without a refresh token (API-token sign-in) recovers by
|
|
496
|
+
* re-authenticating through this callback instead. `null` removes it.
|
|
497
|
+
*/
|
|
498
|
+
setReauthCallback(callback: ReauthCallback | null): void;
|
|
499
|
+
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
500
|
+
canRenew(): Promise<boolean>;
|
|
491
501
|
getAccessToken(): Promise<string | null>;
|
|
492
502
|
setTokens(tokens: StoredTokens): Promise<void>;
|
|
493
503
|
clearTokens(): Promise<void>;
|
|
@@ -552,6 +562,10 @@ declare class TokenManager {
|
|
|
552
562
|
private isTokenExpired;
|
|
553
563
|
private shouldRefresh;
|
|
554
564
|
private tryRefresh;
|
|
565
|
+
/** Deduplicate concurrent renewals; followers get null on failure, like the leader. */
|
|
566
|
+
private singleFlight;
|
|
567
|
+
/** #1073: same auth-loss classification as doRefresh, for re-authentication. */
|
|
568
|
+
private executeReauth;
|
|
555
569
|
private executeRefresh;
|
|
556
570
|
private doRefresh;
|
|
557
571
|
private safeGetTokens;
|
|
@@ -764,6 +778,13 @@ interface RealtimeConfig {
|
|
|
764
778
|
* dropping the connection.
|
|
765
779
|
*/
|
|
766
780
|
onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
|
|
781
|
+
/**
|
|
782
|
+
* Optional forced renewal of the access token, whatever its remaining
|
|
783
|
+
* lifetime. Used once after the server closed the socket although its token
|
|
784
|
+
* had not expired (the token was revoked): renewing either yields a usable
|
|
785
|
+
* token or reports the lost session to the consumer right away.
|
|
786
|
+
*/
|
|
787
|
+
refreshToken?: () => Promise<string | null>;
|
|
767
788
|
}
|
|
768
789
|
type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated' | 'evicted' | 'auth-unavailable' | 'log-reset';
|
|
769
790
|
interface StreamGapInfo {
|
|
@@ -828,6 +849,11 @@ declare class RealtimeClient {
|
|
|
828
849
|
private onOnline;
|
|
829
850
|
private disposed;
|
|
830
851
|
private rebuildRetryTimer;
|
|
852
|
+
private socketToken;
|
|
853
|
+
private socketTokenTimer;
|
|
854
|
+
private socketTokenRetries;
|
|
855
|
+
private serverClosedToken;
|
|
856
|
+
private pendingReauthReplies;
|
|
831
857
|
private connectionState;
|
|
832
858
|
private connectionStateListeners;
|
|
833
859
|
private streamSubscriptions;
|
|
@@ -964,6 +990,18 @@ declare class RealtimeClient {
|
|
|
964
990
|
* so a throwing consumer cannot cancel recovery or make subscribe reject.
|
|
965
991
|
*/
|
|
966
992
|
private keepRetrying;
|
|
993
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
994
|
+
private reauthenticateSocket;
|
|
995
|
+
private clearSocketTokenTimer;
|
|
996
|
+
/**
|
|
997
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
998
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
999
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1000
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1001
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1002
|
+
*/
|
|
1003
|
+
private scheduleSocketTokenRefresh;
|
|
1004
|
+
private refreshSocketToken;
|
|
967
1005
|
private scheduleRebuildRetry;
|
|
968
1006
|
private ensureWakeListeners;
|
|
969
1007
|
private detachWakeListeners;
|
|
@@ -1176,6 +1214,14 @@ declare class AuthModule {
|
|
|
1176
1214
|
}>;
|
|
1177
1215
|
getUserInfo(): Promise<UserInfo>;
|
|
1178
1216
|
getAuthorizationUrl(params: AuthorizationUrlParams): string;
|
|
1217
|
+
/**
|
|
1218
|
+
* #1073: sign in as a machine user with a project API token (`slr_at_…`).
|
|
1219
|
+
* The server returns a short-lived access token and no refresh token; when
|
|
1220
|
+
* it expires or is rejected, the SDK exchanges the API token again. The API
|
|
1221
|
+
* token stays in memory only and is forgotten on logout. Never use this in a
|
|
1222
|
+
* browser: an API token is a long-lived secret.
|
|
1223
|
+
*/
|
|
1224
|
+
loginWithApiToken(apiToken: string): Promise<void>;
|
|
1179
1225
|
exchangeCode(params: ExchangeCodeParams): Promise<TokenResponse>;
|
|
1180
1226
|
generatePKCE(): Promise<PKCEChallenge>;
|
|
1181
1227
|
getOpenIDConfiguration(): Promise<OpenIDConfiguration>;
|
package/dist/index.js
CHANGED
|
@@ -253,7 +253,7 @@ var HttpClient = class {
|
|
|
253
253
|
await this.tokenManager.notifyAuthLost("unauthorized");
|
|
254
254
|
return false;
|
|
255
255
|
}
|
|
256
|
-
const hadRefreshToken = await this.tokenManager.
|
|
256
|
+
const hadRefreshToken = await this.tokenManager.canRenew();
|
|
257
257
|
const refreshed = await this.tokenManager.forceRefresh();
|
|
258
258
|
if (refreshed) return true;
|
|
259
259
|
if (hadRefreshToken) return false;
|
|
@@ -489,6 +489,7 @@ var BrowserTokenStorage = class {
|
|
|
489
489
|
var TokenManager = class {
|
|
490
490
|
constructor(storage, refreshBufferSeconds = 60, refreshLockName = "spacelr_token_refresh") {
|
|
491
491
|
this.refreshCallback = null;
|
|
492
|
+
this.reauthCallback = null;
|
|
492
493
|
this.refreshPromise = null;
|
|
493
494
|
this.tokenRefreshedListeners = /* @__PURE__ */ new Set();
|
|
494
495
|
this.authLostListeners = /* @__PURE__ */ new Set();
|
|
@@ -508,6 +509,18 @@ var TokenManager = class {
|
|
|
508
509
|
setRefreshCallback(callback) {
|
|
509
510
|
this.refreshCallback = callback;
|
|
510
511
|
}
|
|
512
|
+
/**
|
|
513
|
+
* #1073: a session without a refresh token (API-token sign-in) recovers by
|
|
514
|
+
* re-authenticating through this callback instead. `null` removes it.
|
|
515
|
+
*/
|
|
516
|
+
setReauthCallback(callback) {
|
|
517
|
+
this.reauthCallback = callback;
|
|
518
|
+
}
|
|
519
|
+
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
520
|
+
async canRenew() {
|
|
521
|
+
if (this.reauthCallback) return true;
|
|
522
|
+
return this.hasRefreshToken();
|
|
523
|
+
}
|
|
511
524
|
async getAccessToken() {
|
|
512
525
|
const tokens = await this.storage.getTokens();
|
|
513
526
|
if (!tokens) return null;
|
|
@@ -525,10 +538,12 @@ var TokenManager = class {
|
|
|
525
538
|
if (this.pendingClear) await this.pendingClear;
|
|
526
539
|
const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
|
|
527
540
|
const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
|
|
541
|
+
this.reauthCallback = null;
|
|
528
542
|
await this.storage.setTokens(normalised);
|
|
529
543
|
this.authLostEmitted = false;
|
|
530
544
|
}
|
|
531
545
|
async clearTokens() {
|
|
546
|
+
this.reauthCallback = null;
|
|
532
547
|
await this.storage.clearTokens();
|
|
533
548
|
this.refreshPromise = null;
|
|
534
549
|
this.authLostEmitted = false;
|
|
@@ -610,6 +625,7 @@ var TokenManager = class {
|
|
|
610
625
|
async notifyAuthLost(reason) {
|
|
611
626
|
if (this.authLostEmitted) return;
|
|
612
627
|
this.authLostEmitted = true;
|
|
628
|
+
this.reauthCallback = null;
|
|
613
629
|
this.pendingClear = this.storage.clearTokens().catch(() => {
|
|
614
630
|
});
|
|
615
631
|
await this.pendingClear;
|
|
@@ -646,12 +662,15 @@ var TokenManager = class {
|
|
|
646
662
|
return Date.now() >= tokens.expiresAt * 1e3;
|
|
647
663
|
}
|
|
648
664
|
shouldRefresh(tokens) {
|
|
649
|
-
if (!tokens.expiresAt || !tokens.refreshToken) return false;
|
|
665
|
+
if (!tokens.expiresAt || !tokens.refreshToken && !this.reauthCallback) return false;
|
|
650
666
|
const bufferMs = this.refreshBufferSeconds * 1e3;
|
|
651
667
|
return Date.now() >= tokens.expiresAt * 1e3 - bufferMs;
|
|
652
668
|
}
|
|
653
669
|
async tryRefresh(tokens) {
|
|
654
|
-
if (!tokens.refreshToken
|
|
670
|
+
if (!tokens.refreshToken) {
|
|
671
|
+
return this.reauthCallback ? this.singleFlight(() => this.executeReauth()) : null;
|
|
672
|
+
}
|
|
673
|
+
if (!this.refreshCallback) return null;
|
|
655
674
|
if (this.refreshPromise) {
|
|
656
675
|
try {
|
|
657
676
|
return await this.refreshPromise;
|
|
@@ -668,6 +687,43 @@ var TokenManager = class {
|
|
|
668
687
|
this.refreshPromise = null;
|
|
669
688
|
}
|
|
670
689
|
}
|
|
690
|
+
/** Deduplicate concurrent renewals; followers get null on failure, like the leader. */
|
|
691
|
+
async singleFlight(run) {
|
|
692
|
+
if (!this.refreshPromise) {
|
|
693
|
+
this.refreshPromise = run();
|
|
694
|
+
try {
|
|
695
|
+
return await this.refreshPromise;
|
|
696
|
+
} catch {
|
|
697
|
+
return null;
|
|
698
|
+
} finally {
|
|
699
|
+
this.refreshPromise = null;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
try {
|
|
703
|
+
return await this.refreshPromise;
|
|
704
|
+
} catch {
|
|
705
|
+
return null;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/** #1073: same auth-loss classification as doRefresh, for re-authentication. */
|
|
709
|
+
async executeReauth() {
|
|
710
|
+
const callback = this.reauthCallback;
|
|
711
|
+
const superseded = () => this.reauthCallback !== callback;
|
|
712
|
+
let newTokens;
|
|
713
|
+
try {
|
|
714
|
+
newTokens = await callback();
|
|
715
|
+
} catch (error) {
|
|
716
|
+
if (superseded()) throw new Error("re-authentication superseded");
|
|
717
|
+
if (!this.isTransientTransportError(error)) {
|
|
718
|
+
await this.notifyAuthLost("refresh-failed");
|
|
719
|
+
}
|
|
720
|
+
throw error;
|
|
721
|
+
}
|
|
722
|
+
if (superseded()) throw new Error("re-authentication superseded");
|
|
723
|
+
await this.storage.setTokens(newTokens);
|
|
724
|
+
this.emitTokenRefreshed(newTokens);
|
|
725
|
+
return newTokens;
|
|
726
|
+
}
|
|
671
727
|
async executeRefresh(refreshToken) {
|
|
672
728
|
return this.withCrossTabLock(() => this.doRefresh(refreshToken));
|
|
673
729
|
}
|
|
@@ -725,6 +781,7 @@ var FileVisibility = /* @__PURE__ */ ((FileVisibility2) => {
|
|
|
725
781
|
FileVisibility2["PUBLIC"] = "public";
|
|
726
782
|
return FileVisibility2;
|
|
727
783
|
})(FileVisibility || {});
|
|
784
|
+
var API_TOKEN_GRANT = "urn:spacelr:grant-type:api-token";
|
|
728
785
|
var GrantType = /* @__PURE__ */ ((GrantType2) => {
|
|
729
786
|
GrantType2["AUTHORIZATION_CODE"] = "authorization_code";
|
|
730
787
|
GrantType2["CLIENT_CREDENTIALS"] = "client_credentials";
|
|
@@ -786,6 +843,22 @@ async function generatePKCEChallenge() {
|
|
|
786
843
|
// libs/sdk/src/core/realtime.ts
|
|
787
844
|
var import_socket = require("socket.io-client");
|
|
788
845
|
var REBUILD_RETRY_DELAY_MS = 5e3;
|
|
846
|
+
var SOCKET_TOKEN_REFRESH_LEAD_MS = 45e3;
|
|
847
|
+
var SOCKET_TOKEN_REFRESH_JITTER_MS = 15e3;
|
|
848
|
+
var SOCKET_TOKEN_REFRESH_RETRY_MS = 5e3;
|
|
849
|
+
var SOCKET_TOKEN_REFRESH_RETRY_MAX_MS = 3e4;
|
|
850
|
+
var SERVER_DISCONNECT_REBUILD_DELAY_MS = 1e3;
|
|
851
|
+
function jwtExpiryMs(token) {
|
|
852
|
+
const payload = token.split(".")[1];
|
|
853
|
+
if (!payload) return null;
|
|
854
|
+
try {
|
|
855
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
856
|
+
const exp = JSON.parse(json).exp;
|
|
857
|
+
return typeof exp === "number" ? exp * 1e3 : null;
|
|
858
|
+
} catch {
|
|
859
|
+
return null;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
789
862
|
var PERMANENT_STREAM_ACK_ERRORS = /* @__PURE__ */ new Set([
|
|
790
863
|
"not-stream-collection",
|
|
791
864
|
"Collection not found",
|
|
@@ -976,6 +1049,18 @@ var RealtimeClient = class {
|
|
|
976
1049
|
// Scheduled retry after a failed `rebuildSocket()`; cleared when it fires
|
|
977
1050
|
// or when `disconnect()` tears down.
|
|
978
1051
|
this.rebuildRetryTimer = null;
|
|
1052
|
+
// #1078 — the access token the open socket was last authenticated with, and
|
|
1053
|
+
// the timer that replaces it before it expires.
|
|
1054
|
+
this.socketToken = null;
|
|
1055
|
+
this.socketTokenTimer = null;
|
|
1056
|
+
this.socketTokenRetries = 0;
|
|
1057
|
+
// The token of a socket the server closed. If the next connect would use the
|
|
1058
|
+
// same token again, it is renewed first (once).
|
|
1059
|
+
this.serverClosedToken = null;
|
|
1060
|
+
// `reauthenticate` messages whose `authenticated` reply is still due. Such a
|
|
1061
|
+
// reply confirms a token swap on a live socket, not a new connection, so the
|
|
1062
|
+
// subscriptions must not be sent again for it.
|
|
1063
|
+
this.pendingReauthReplies = 0;
|
|
979
1064
|
this.connectionState = "disconnected";
|
|
980
1065
|
this.connectionStateListeners = /* @__PURE__ */ new Set();
|
|
981
1066
|
this.streamSubscriptions = /* @__PURE__ */ new Map();
|
|
@@ -1219,6 +1304,7 @@ var RealtimeClient = class {
|
|
|
1219
1304
|
clearTimeout(this.rebuildRetryTimer);
|
|
1220
1305
|
this.rebuildRetryTimer = null;
|
|
1221
1306
|
}
|
|
1307
|
+
this.clearSocketTokenTimer();
|
|
1222
1308
|
if (this.unsubscribeFromTokenRefreshed) {
|
|
1223
1309
|
this.unsubscribeFromTokenRefreshed();
|
|
1224
1310
|
this.unsubscribeFromTokenRefreshed = null;
|
|
@@ -1346,10 +1432,16 @@ var RealtimeClient = class {
|
|
|
1346
1432
|
this.socket = null;
|
|
1347
1433
|
previous.disconnect();
|
|
1348
1434
|
}
|
|
1349
|
-
|
|
1435
|
+
let token = await this.config.getToken();
|
|
1436
|
+
if (token && token === this.serverClosedToken) {
|
|
1437
|
+
this.serverClosedToken = null;
|
|
1438
|
+
await this.config.refreshToken?.().catch(() => null);
|
|
1439
|
+
token = await this.config.getToken();
|
|
1440
|
+
}
|
|
1350
1441
|
if (!token) {
|
|
1351
1442
|
throw new Error("No authentication token available");
|
|
1352
1443
|
}
|
|
1444
|
+
this.socketToken = token;
|
|
1353
1445
|
const wsUrl = this.config.baseUrl.replace(/\/api\/v\d+\/?$/, "");
|
|
1354
1446
|
return new Promise((resolve, reject) => {
|
|
1355
1447
|
let initialConnect = true;
|
|
@@ -1358,6 +1450,7 @@ var RealtimeClient = class {
|
|
|
1358
1450
|
auth: async (cb) => {
|
|
1359
1451
|
try {
|
|
1360
1452
|
const freshToken = await this.config.getToken();
|
|
1453
|
+
if (freshToken) this.socketToken = freshToken;
|
|
1361
1454
|
cb({ token: freshToken });
|
|
1362
1455
|
} catch {
|
|
1363
1456
|
cb({ token: null });
|
|
@@ -1387,6 +1480,7 @@ var RealtimeClient = class {
|
|
|
1387
1480
|
if (this.disposed) return;
|
|
1388
1481
|
if (this.socket !== socket) return;
|
|
1389
1482
|
this.setConnectionState("connected");
|
|
1483
|
+
this.scheduleSocketTokenRefresh();
|
|
1390
1484
|
if (initialConnect) {
|
|
1391
1485
|
initialConnect = false;
|
|
1392
1486
|
if (this.socket) {
|
|
@@ -1419,14 +1513,14 @@ var RealtimeClient = class {
|
|
|
1419
1513
|
}
|
|
1420
1514
|
if (this.config.onTokenRefreshed && !this.unsubscribeFromTokenRefreshed) {
|
|
1421
1515
|
this.unsubscribeFromTokenRefreshed = this.config.onTokenRefreshed(
|
|
1422
|
-
(accessToken) =>
|
|
1423
|
-
this.socket?.emit("reauthenticate", { token: accessToken });
|
|
1424
|
-
}
|
|
1516
|
+
(accessToken) => this.reauthenticateSocket(accessToken)
|
|
1425
1517
|
);
|
|
1426
1518
|
}
|
|
1427
1519
|
if (this.subscriptions.size > 0) this.resubscribeAll();
|
|
1428
1520
|
if (this.streamSubscriptions.size > 0) void this.resubscribeAllStreams();
|
|
1429
1521
|
resolve();
|
|
1522
|
+
} else if (this.pendingReauthReplies > 0) {
|
|
1523
|
+
this.pendingReauthReplies -= 1;
|
|
1430
1524
|
} else {
|
|
1431
1525
|
this.resubscribeAll();
|
|
1432
1526
|
void this.resubscribeAllStreams();
|
|
@@ -1506,11 +1600,17 @@ var RealtimeClient = class {
|
|
|
1506
1600
|
}
|
|
1507
1601
|
}
|
|
1508
1602
|
});
|
|
1509
|
-
socket.on("disconnect", () => {
|
|
1603
|
+
socket.on("disconnect", (reason) => {
|
|
1604
|
+
if (this.socket === socket) this.pendingReauthReplies = 0;
|
|
1510
1605
|
if (this.disposed) return;
|
|
1511
1606
|
if (initialConnect) return;
|
|
1512
1607
|
if (this.socket !== socket) return;
|
|
1513
1608
|
this.setConnectionState("reconnecting");
|
|
1609
|
+
if (reason === "io server disconnect") {
|
|
1610
|
+
this.serverClosedToken = this.socketToken;
|
|
1611
|
+
this.clearSocketTokenTimer();
|
|
1612
|
+
this.scheduleRebuildRetry(SERVER_DISCONNECT_REBUILD_DELAY_MS);
|
|
1613
|
+
}
|
|
1514
1614
|
});
|
|
1515
1615
|
});
|
|
1516
1616
|
}
|
|
@@ -1572,7 +1672,72 @@ var RealtimeClient = class {
|
|
|
1572
1672
|
} catch {
|
|
1573
1673
|
}
|
|
1574
1674
|
}
|
|
1575
|
-
|
|
1675
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
1676
|
+
reauthenticateSocket(accessToken) {
|
|
1677
|
+
if (accessToken === this.socketToken) return;
|
|
1678
|
+
if (!this.socket?.connected) return;
|
|
1679
|
+
this.socketToken = accessToken;
|
|
1680
|
+
this.pendingReauthReplies += 1;
|
|
1681
|
+
this.socket.emit("reauthenticate", { token: accessToken });
|
|
1682
|
+
this.scheduleSocketTokenRefresh();
|
|
1683
|
+
}
|
|
1684
|
+
clearSocketTokenTimer() {
|
|
1685
|
+
if (this.socketTokenTimer) {
|
|
1686
|
+
clearTimeout(this.socketTokenTimer);
|
|
1687
|
+
this.socketTokenTimer = null;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
/**
|
|
1691
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
1692
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
1693
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1694
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1695
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1696
|
+
*/
|
|
1697
|
+
scheduleSocketTokenRefresh(retryMs) {
|
|
1698
|
+
this.clearSocketTokenTimer();
|
|
1699
|
+
if (retryMs === void 0) this.socketTokenRetries = 0;
|
|
1700
|
+
if (this.disposed || !this.socketToken) return;
|
|
1701
|
+
const expiresAt = jwtExpiryMs(this.socketToken);
|
|
1702
|
+
if (expiresAt === null) return;
|
|
1703
|
+
const remaining = expiresAt - Date.now();
|
|
1704
|
+
const lead = Math.min(
|
|
1705
|
+
SOCKET_TOKEN_REFRESH_LEAD_MS + Math.random() * SOCKET_TOKEN_REFRESH_JITTER_MS,
|
|
1706
|
+
remaining / 2
|
|
1707
|
+
);
|
|
1708
|
+
const delay = retryMs ?? Math.max(1e3, remaining - lead);
|
|
1709
|
+
this.socketTokenTimer = setTimeout(() => {
|
|
1710
|
+
this.socketTokenTimer = null;
|
|
1711
|
+
void this.refreshSocketToken(expiresAt);
|
|
1712
|
+
}, delay);
|
|
1713
|
+
this.socketTokenTimer.unref?.();
|
|
1714
|
+
}
|
|
1715
|
+
async refreshSocketToken(expiresAt) {
|
|
1716
|
+
if (this.disposed || !this.socket) return;
|
|
1717
|
+
const previous = this.socketToken;
|
|
1718
|
+
let token = null;
|
|
1719
|
+
try {
|
|
1720
|
+
token = await this.config.getToken();
|
|
1721
|
+
} catch {
|
|
1722
|
+
}
|
|
1723
|
+
if (this.disposed || !this.socket) return;
|
|
1724
|
+
if (this.socketToken !== previous) return;
|
|
1725
|
+
if (token && token !== previous) {
|
|
1726
|
+
this.reauthenticateSocket(token);
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
const remaining = expiresAt - Date.now();
|
|
1730
|
+
if (remaining <= 0) return;
|
|
1731
|
+
const backoff = Math.min(
|
|
1732
|
+
SOCKET_TOKEN_REFRESH_RETRY_MS * 2 ** this.socketTokenRetries,
|
|
1733
|
+
SOCKET_TOKEN_REFRESH_RETRY_MAX_MS
|
|
1734
|
+
);
|
|
1735
|
+
this.socketTokenRetries += 1;
|
|
1736
|
+
this.scheduleSocketTokenRefresh(
|
|
1737
|
+
Math.min(backoff, Math.max(SOCKET_TOKEN_REFRESH_RETRY_MS, remaining / 2))
|
|
1738
|
+
);
|
|
1739
|
+
}
|
|
1740
|
+
scheduleRebuildRetry(delayMs = REBUILD_RETRY_DELAY_MS) {
|
|
1576
1741
|
if (this.disposed || this.rebuildRetryTimer) return;
|
|
1577
1742
|
this.rebuildRetryTimer = setTimeout(() => {
|
|
1578
1743
|
this.rebuildRetryTimer = null;
|
|
@@ -1582,7 +1747,7 @@ var RealtimeClient = class {
|
|
|
1582
1747
|
}
|
|
1583
1748
|
if (this.socket?.connected) return;
|
|
1584
1749
|
void this.rebuildSocket();
|
|
1585
|
-
},
|
|
1750
|
+
}, delayMs);
|
|
1586
1751
|
this.rebuildRetryTimer.unref?.();
|
|
1587
1752
|
}
|
|
1588
1753
|
ensureWakeListeners() {
|
|
@@ -2201,6 +2366,30 @@ var AuthModule = class _AuthModule {
|
|
|
2201
2366
|
}
|
|
2202
2367
|
return url.toString();
|
|
2203
2368
|
}
|
|
2369
|
+
/**
|
|
2370
|
+
* #1073: sign in as a machine user with a project API token (`slr_at_…`).
|
|
2371
|
+
* The server returns a short-lived access token and no refresh token; when
|
|
2372
|
+
* it expires or is rejected, the SDK exchanges the API token again. The API
|
|
2373
|
+
* token stays in memory only and is forgotten on logout. Never use this in a
|
|
2374
|
+
* browser: an API token is a long-lived secret.
|
|
2375
|
+
*/
|
|
2376
|
+
async loginWithApiToken(apiToken) {
|
|
2377
|
+
const exchange = async () => {
|
|
2378
|
+
const response = await this.http.request({
|
|
2379
|
+
method: "POST",
|
|
2380
|
+
path: this.config.tokenEndpoint ?? "/auth/token",
|
|
2381
|
+
body: { grant_type: API_TOKEN_GRANT, client_id: this.config.clientId, api_token: apiToken },
|
|
2382
|
+
skipAuthRefresh: true
|
|
2383
|
+
});
|
|
2384
|
+
return {
|
|
2385
|
+
accessToken: response.access_token,
|
|
2386
|
+
expiresAt: response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0
|
|
2387
|
+
};
|
|
2388
|
+
};
|
|
2389
|
+
const tokens = await exchange();
|
|
2390
|
+
await this.installSession(tokens);
|
|
2391
|
+
this.tokenManager.setReauthCallback(exchange);
|
|
2392
|
+
}
|
|
2204
2393
|
async exchangeCode(params) {
|
|
2205
2394
|
const body = {
|
|
2206
2395
|
grant_type: params.grantType ?? "authorization_code" /* AUTHORIZATION_CODE */,
|
|
@@ -4639,6 +4828,7 @@ function createClient(config) {
|
|
|
4639
4828
|
const realtime = new RealtimeClient({
|
|
4640
4829
|
baseUrl: config.apiUrl,
|
|
4641
4830
|
getToken: () => tokenManager.getAccessToken(),
|
|
4831
|
+
refreshToken: () => tokenManager.forceRefresh(),
|
|
4642
4832
|
onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
|
|
4643
4833
|
});
|
|
4644
4834
|
const notifications = new NotificationsModule(httpClient, {
|