@spacelr/sdk 0.19.5 → 0.19.7
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 +60 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +213 -10
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +213 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -76,6 +76,8 @@ interface TokenResponse {
|
|
|
76
76
|
expires_in: number;
|
|
77
77
|
refresh_token?: string;
|
|
78
78
|
scope?: string;
|
|
79
|
+
/** #1090: expiry (ISO 8601) of the project API token; API-token sign-in only. */
|
|
80
|
+
api_token_expires_at?: string;
|
|
79
81
|
}
|
|
80
82
|
interface UserInfo {
|
|
81
83
|
sub: string;
|
|
@@ -484,6 +486,7 @@ declare class TokenManager {
|
|
|
484
486
|
private refreshLockName;
|
|
485
487
|
private refreshCallback;
|
|
486
488
|
private reauthCallback;
|
|
489
|
+
private reauthGeneration;
|
|
487
490
|
private refreshPromise;
|
|
488
491
|
private tokenRefreshedListeners;
|
|
489
492
|
private authLostListeners;
|
|
@@ -496,6 +499,13 @@ declare class TokenManager {
|
|
|
496
499
|
* re-authenticating through this callback instead. `null` removes it.
|
|
497
500
|
*/
|
|
498
501
|
setReauthCallback(callback: ReauthCallback | null): void;
|
|
502
|
+
/**
|
|
503
|
+
* #1090: changes whenever the re-authentication callback is set, replaced or
|
|
504
|
+
* dropped. Lets a caller tell whether "its" API-token session is still the
|
|
505
|
+
* current one without keeping a reference to the callback (whose closure
|
|
506
|
+
* holds the API token).
|
|
507
|
+
*/
|
|
508
|
+
getReauthGeneration(): number;
|
|
499
509
|
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
500
510
|
canRenew(): Promise<boolean>;
|
|
501
511
|
getAccessToken(): Promise<string | null>;
|
|
@@ -778,6 +788,13 @@ interface RealtimeConfig {
|
|
|
778
788
|
* dropping the connection.
|
|
779
789
|
*/
|
|
780
790
|
onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
|
|
791
|
+
/**
|
|
792
|
+
* Optional forced renewal of the access token, whatever its remaining
|
|
793
|
+
* lifetime. Used once after the server closed the socket although its token
|
|
794
|
+
* had not expired (the token was revoked): renewing either yields a usable
|
|
795
|
+
* token or reports the lost session to the consumer right away.
|
|
796
|
+
*/
|
|
797
|
+
refreshToken?: () => Promise<string | null>;
|
|
781
798
|
}
|
|
782
799
|
type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated' | 'evicted' | 'auth-unavailable' | 'log-reset';
|
|
783
800
|
interface StreamGapInfo {
|
|
@@ -842,6 +859,11 @@ declare class RealtimeClient {
|
|
|
842
859
|
private onOnline;
|
|
843
860
|
private disposed;
|
|
844
861
|
private rebuildRetryTimer;
|
|
862
|
+
private socketToken;
|
|
863
|
+
private socketTokenTimer;
|
|
864
|
+
private socketTokenRetries;
|
|
865
|
+
private serverClosedToken;
|
|
866
|
+
private pendingReauthReplies;
|
|
845
867
|
private connectionState;
|
|
846
868
|
private connectionStateListeners;
|
|
847
869
|
private streamSubscriptions;
|
|
@@ -978,6 +1000,18 @@ declare class RealtimeClient {
|
|
|
978
1000
|
* so a throwing consumer cannot cancel recovery or make subscribe reject.
|
|
979
1001
|
*/
|
|
980
1002
|
private keepRetrying;
|
|
1003
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
1004
|
+
private reauthenticateSocket;
|
|
1005
|
+
private clearSocketTokenTimer;
|
|
1006
|
+
/**
|
|
1007
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
1008
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
1009
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1010
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1011
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1012
|
+
*/
|
|
1013
|
+
private scheduleSocketTokenRefresh;
|
|
1014
|
+
private refreshSocketToken;
|
|
981
1015
|
private scheduleRebuildRetry;
|
|
982
1016
|
private ensureWakeListeners;
|
|
983
1017
|
private detachWakeListeners;
|
|
@@ -1107,6 +1141,9 @@ declare class AuthModule {
|
|
|
1107
1141
|
private lastEmittedState;
|
|
1108
1142
|
private beforeLogout?;
|
|
1109
1143
|
private afterSignIn?;
|
|
1144
|
+
private apiTokenExpiresAt;
|
|
1145
|
+
private apiTokenGeneration;
|
|
1146
|
+
private apiTokenExpiryListeners;
|
|
1110
1147
|
constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig,
|
|
1111
1148
|
/**
|
|
1112
1149
|
* Wired by `createClient`. `beforeLogout` runs while the session is still
|
|
@@ -1166,6 +1203,29 @@ declare class AuthModule {
|
|
|
1166
1203
|
* the previous user before it is re-registered for the new one.
|
|
1167
1204
|
*/
|
|
1168
1205
|
private installSession;
|
|
1206
|
+
/** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
|
|
1207
|
+
private setApiTokenExpiry;
|
|
1208
|
+
private apiTokenSessionLive;
|
|
1209
|
+
private notifyApiTokenExpiry;
|
|
1210
|
+
/**
|
|
1211
|
+
* #1090: expiry of the project API token behind the current machine-user
|
|
1212
|
+
* session, or null when it is unknown (no API-token session, a token without
|
|
1213
|
+
* an expiry, or a server that does not report it yet).
|
|
1214
|
+
*/
|
|
1215
|
+
getApiTokenExpiry(): Date | null;
|
|
1216
|
+
/**
|
|
1217
|
+
* #1090: be told when the project API token of this session expires within
|
|
1218
|
+
* `withinDays` (default 14), so a new token can be issued before the agent is
|
|
1219
|
+
* signed out. Checked at sign-in, on every re-exchange (at least every 15
|
|
1220
|
+
* minutes while the session is in use) and when the listener is added; a
|
|
1221
|
+
* listener hears about the same token at most once a day. Returns an
|
|
1222
|
+
* unsubscribe function.
|
|
1223
|
+
*/
|
|
1224
|
+
onApiTokenExpiring(listener: (info: {
|
|
1225
|
+
expiresAt: Date;
|
|
1226
|
+
}) => void | Promise<void>, options?: {
|
|
1227
|
+
withinDays?: number;
|
|
1228
|
+
}): () => void;
|
|
1169
1229
|
private emitState;
|
|
1170
1230
|
login(params: LoginParams): Promise<LoginResponse>;
|
|
1171
1231
|
register(params: RegisterParams): Promise<RegisterResponse>;
|
package/dist/index.d.ts
CHANGED
|
@@ -76,6 +76,8 @@ interface TokenResponse {
|
|
|
76
76
|
expires_in: number;
|
|
77
77
|
refresh_token?: string;
|
|
78
78
|
scope?: string;
|
|
79
|
+
/** #1090: expiry (ISO 8601) of the project API token; API-token sign-in only. */
|
|
80
|
+
api_token_expires_at?: string;
|
|
79
81
|
}
|
|
80
82
|
interface UserInfo {
|
|
81
83
|
sub: string;
|
|
@@ -484,6 +486,7 @@ declare class TokenManager {
|
|
|
484
486
|
private refreshLockName;
|
|
485
487
|
private refreshCallback;
|
|
486
488
|
private reauthCallback;
|
|
489
|
+
private reauthGeneration;
|
|
487
490
|
private refreshPromise;
|
|
488
491
|
private tokenRefreshedListeners;
|
|
489
492
|
private authLostListeners;
|
|
@@ -496,6 +499,13 @@ declare class TokenManager {
|
|
|
496
499
|
* re-authenticating through this callback instead. `null` removes it.
|
|
497
500
|
*/
|
|
498
501
|
setReauthCallback(callback: ReauthCallback | null): void;
|
|
502
|
+
/**
|
|
503
|
+
* #1090: changes whenever the re-authentication callback is set, replaced or
|
|
504
|
+
* dropped. Lets a caller tell whether "its" API-token session is still the
|
|
505
|
+
* current one without keeping a reference to the callback (whose closure
|
|
506
|
+
* holds the API token).
|
|
507
|
+
*/
|
|
508
|
+
getReauthGeneration(): number;
|
|
499
509
|
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
500
510
|
canRenew(): Promise<boolean>;
|
|
501
511
|
getAccessToken(): Promise<string | null>;
|
|
@@ -778,6 +788,13 @@ interface RealtimeConfig {
|
|
|
778
788
|
* dropping the connection.
|
|
779
789
|
*/
|
|
780
790
|
onTokenRefreshed?: (listener: (accessToken: string) => void) => () => void;
|
|
791
|
+
/**
|
|
792
|
+
* Optional forced renewal of the access token, whatever its remaining
|
|
793
|
+
* lifetime. Used once after the server closed the socket although its token
|
|
794
|
+
* had not expired (the token was revoked): renewing either yields a usable
|
|
795
|
+
* token or reports the lost session to the consumer right away.
|
|
796
|
+
*/
|
|
797
|
+
refreshToken?: () => Promise<string | null>;
|
|
781
798
|
}
|
|
782
799
|
type GapReason = 'outside-retention-window' | 'redis-unavailable' | 'replay-error' | 'replay-truncated' | 'evicted' | 'auth-unavailable' | 'log-reset';
|
|
783
800
|
interface StreamGapInfo {
|
|
@@ -842,6 +859,11 @@ declare class RealtimeClient {
|
|
|
842
859
|
private onOnline;
|
|
843
860
|
private disposed;
|
|
844
861
|
private rebuildRetryTimer;
|
|
862
|
+
private socketToken;
|
|
863
|
+
private socketTokenTimer;
|
|
864
|
+
private socketTokenRetries;
|
|
865
|
+
private serverClosedToken;
|
|
866
|
+
private pendingReauthReplies;
|
|
845
867
|
private connectionState;
|
|
846
868
|
private connectionStateListeners;
|
|
847
869
|
private streamSubscriptions;
|
|
@@ -978,6 +1000,18 @@ declare class RealtimeClient {
|
|
|
978
1000
|
* so a throwing consumer cannot cancel recovery or make subscribe reject.
|
|
979
1001
|
*/
|
|
980
1002
|
private keepRetrying;
|
|
1003
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
1004
|
+
private reauthenticateSocket;
|
|
1005
|
+
private clearSocketTokenTimer;
|
|
1006
|
+
/**
|
|
1007
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
1008
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
1009
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1010
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1011
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1012
|
+
*/
|
|
1013
|
+
private scheduleSocketTokenRefresh;
|
|
1014
|
+
private refreshSocketToken;
|
|
981
1015
|
private scheduleRebuildRetry;
|
|
982
1016
|
private ensureWakeListeners;
|
|
983
1017
|
private detachWakeListeners;
|
|
@@ -1107,6 +1141,9 @@ declare class AuthModule {
|
|
|
1107
1141
|
private lastEmittedState;
|
|
1108
1142
|
private beforeLogout?;
|
|
1109
1143
|
private afterSignIn?;
|
|
1144
|
+
private apiTokenExpiresAt;
|
|
1145
|
+
private apiTokenGeneration;
|
|
1146
|
+
private apiTokenExpiryListeners;
|
|
1110
1147
|
constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig,
|
|
1111
1148
|
/**
|
|
1112
1149
|
* Wired by `createClient`. `beforeLogout` runs while the session is still
|
|
@@ -1166,6 +1203,29 @@ declare class AuthModule {
|
|
|
1166
1203
|
* the previous user before it is re-registered for the new one.
|
|
1167
1204
|
*/
|
|
1168
1205
|
private installSession;
|
|
1206
|
+
/** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
|
|
1207
|
+
private setApiTokenExpiry;
|
|
1208
|
+
private apiTokenSessionLive;
|
|
1209
|
+
private notifyApiTokenExpiry;
|
|
1210
|
+
/**
|
|
1211
|
+
* #1090: expiry of the project API token behind the current machine-user
|
|
1212
|
+
* session, or null when it is unknown (no API-token session, a token without
|
|
1213
|
+
* an expiry, or a server that does not report it yet).
|
|
1214
|
+
*/
|
|
1215
|
+
getApiTokenExpiry(): Date | null;
|
|
1216
|
+
/**
|
|
1217
|
+
* #1090: be told when the project API token of this session expires within
|
|
1218
|
+
* `withinDays` (default 14), so a new token can be issued before the agent is
|
|
1219
|
+
* signed out. Checked at sign-in, on every re-exchange (at least every 15
|
|
1220
|
+
* minutes while the session is in use) and when the listener is added; a
|
|
1221
|
+
* listener hears about the same token at most once a day. Returns an
|
|
1222
|
+
* unsubscribe function.
|
|
1223
|
+
*/
|
|
1224
|
+
onApiTokenExpiring(listener: (info: {
|
|
1225
|
+
expiresAt: Date;
|
|
1226
|
+
}) => void | Promise<void>, options?: {
|
|
1227
|
+
withinDays?: number;
|
|
1228
|
+
}): () => void;
|
|
1169
1229
|
private emitState;
|
|
1170
1230
|
login(params: LoginParams): Promise<LoginResponse>;
|
|
1171
1231
|
register(params: RegisterParams): Promise<RegisterResponse>;
|
package/dist/index.js
CHANGED
|
@@ -490,6 +490,7 @@ var TokenManager = class {
|
|
|
490
490
|
constructor(storage, refreshBufferSeconds = 60, refreshLockName = "spacelr_token_refresh") {
|
|
491
491
|
this.refreshCallback = null;
|
|
492
492
|
this.reauthCallback = null;
|
|
493
|
+
this.reauthGeneration = 0;
|
|
493
494
|
this.refreshPromise = null;
|
|
494
495
|
this.tokenRefreshedListeners = /* @__PURE__ */ new Set();
|
|
495
496
|
this.authLostListeners = /* @__PURE__ */ new Set();
|
|
@@ -515,6 +516,16 @@ var TokenManager = class {
|
|
|
515
516
|
*/
|
|
516
517
|
setReauthCallback(callback) {
|
|
517
518
|
this.reauthCallback = callback;
|
|
519
|
+
this.reauthGeneration += 1;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* #1090: changes whenever the re-authentication callback is set, replaced or
|
|
523
|
+
* dropped. Lets a caller tell whether "its" API-token session is still the
|
|
524
|
+
* current one without keeping a reference to the callback (whose closure
|
|
525
|
+
* holds the API token).
|
|
526
|
+
*/
|
|
527
|
+
getReauthGeneration() {
|
|
528
|
+
return this.reauthGeneration;
|
|
518
529
|
}
|
|
519
530
|
/** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
|
|
520
531
|
async canRenew() {
|
|
@@ -539,11 +550,13 @@ var TokenManager = class {
|
|
|
539
550
|
const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
|
|
540
551
|
const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
|
|
541
552
|
this.reauthCallback = null;
|
|
553
|
+
this.reauthGeneration += 1;
|
|
542
554
|
await this.storage.setTokens(normalised);
|
|
543
555
|
this.authLostEmitted = false;
|
|
544
556
|
}
|
|
545
557
|
async clearTokens() {
|
|
546
558
|
this.reauthCallback = null;
|
|
559
|
+
this.reauthGeneration += 1;
|
|
547
560
|
await this.storage.clearTokens();
|
|
548
561
|
this.refreshPromise = null;
|
|
549
562
|
this.authLostEmitted = false;
|
|
@@ -626,6 +639,7 @@ var TokenManager = class {
|
|
|
626
639
|
if (this.authLostEmitted) return;
|
|
627
640
|
this.authLostEmitted = true;
|
|
628
641
|
this.reauthCallback = null;
|
|
642
|
+
this.reauthGeneration += 1;
|
|
629
643
|
this.pendingClear = this.storage.clearTokens().catch(() => {
|
|
630
644
|
});
|
|
631
645
|
await this.pendingClear;
|
|
@@ -843,6 +857,22 @@ async function generatePKCEChallenge() {
|
|
|
843
857
|
// libs/sdk/src/core/realtime.ts
|
|
844
858
|
var import_socket = require("socket.io-client");
|
|
845
859
|
var REBUILD_RETRY_DELAY_MS = 5e3;
|
|
860
|
+
var SOCKET_TOKEN_REFRESH_LEAD_MS = 45e3;
|
|
861
|
+
var SOCKET_TOKEN_REFRESH_JITTER_MS = 15e3;
|
|
862
|
+
var SOCKET_TOKEN_REFRESH_RETRY_MS = 5e3;
|
|
863
|
+
var SOCKET_TOKEN_REFRESH_RETRY_MAX_MS = 3e4;
|
|
864
|
+
var SERVER_DISCONNECT_REBUILD_DELAY_MS = 1e3;
|
|
865
|
+
function jwtExpiryMs(token) {
|
|
866
|
+
const payload = token.split(".")[1];
|
|
867
|
+
if (!payload) return null;
|
|
868
|
+
try {
|
|
869
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
870
|
+
const exp = JSON.parse(json).exp;
|
|
871
|
+
return typeof exp === "number" ? exp * 1e3 : null;
|
|
872
|
+
} catch {
|
|
873
|
+
return null;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
846
876
|
var PERMANENT_STREAM_ACK_ERRORS = /* @__PURE__ */ new Set([
|
|
847
877
|
"not-stream-collection",
|
|
848
878
|
"Collection not found",
|
|
@@ -1033,6 +1063,18 @@ var RealtimeClient = class {
|
|
|
1033
1063
|
// Scheduled retry after a failed `rebuildSocket()`; cleared when it fires
|
|
1034
1064
|
// or when `disconnect()` tears down.
|
|
1035
1065
|
this.rebuildRetryTimer = null;
|
|
1066
|
+
// #1078 — the access token the open socket was last authenticated with, and
|
|
1067
|
+
// the timer that replaces it before it expires.
|
|
1068
|
+
this.socketToken = null;
|
|
1069
|
+
this.socketTokenTimer = null;
|
|
1070
|
+
this.socketTokenRetries = 0;
|
|
1071
|
+
// The token of a socket the server closed. If the next connect would use the
|
|
1072
|
+
// same token again, it is renewed first (once).
|
|
1073
|
+
this.serverClosedToken = null;
|
|
1074
|
+
// `reauthenticate` messages whose `authenticated` reply is still due. Such a
|
|
1075
|
+
// reply confirms a token swap on a live socket, not a new connection, so the
|
|
1076
|
+
// subscriptions must not be sent again for it.
|
|
1077
|
+
this.pendingReauthReplies = 0;
|
|
1036
1078
|
this.connectionState = "disconnected";
|
|
1037
1079
|
this.connectionStateListeners = /* @__PURE__ */ new Set();
|
|
1038
1080
|
this.streamSubscriptions = /* @__PURE__ */ new Map();
|
|
@@ -1276,6 +1318,7 @@ var RealtimeClient = class {
|
|
|
1276
1318
|
clearTimeout(this.rebuildRetryTimer);
|
|
1277
1319
|
this.rebuildRetryTimer = null;
|
|
1278
1320
|
}
|
|
1321
|
+
this.clearSocketTokenTimer();
|
|
1279
1322
|
if (this.unsubscribeFromTokenRefreshed) {
|
|
1280
1323
|
this.unsubscribeFromTokenRefreshed();
|
|
1281
1324
|
this.unsubscribeFromTokenRefreshed = null;
|
|
@@ -1403,10 +1446,16 @@ var RealtimeClient = class {
|
|
|
1403
1446
|
this.socket = null;
|
|
1404
1447
|
previous.disconnect();
|
|
1405
1448
|
}
|
|
1406
|
-
|
|
1449
|
+
let token = await this.config.getToken();
|
|
1450
|
+
if (token && token === this.serverClosedToken) {
|
|
1451
|
+
this.serverClosedToken = null;
|
|
1452
|
+
await this.config.refreshToken?.().catch(() => null);
|
|
1453
|
+
token = await this.config.getToken();
|
|
1454
|
+
}
|
|
1407
1455
|
if (!token) {
|
|
1408
1456
|
throw new Error("No authentication token available");
|
|
1409
1457
|
}
|
|
1458
|
+
this.socketToken = token;
|
|
1410
1459
|
const wsUrl = this.config.baseUrl.replace(/\/api\/v\d+\/?$/, "");
|
|
1411
1460
|
return new Promise((resolve, reject) => {
|
|
1412
1461
|
let initialConnect = true;
|
|
@@ -1415,6 +1464,7 @@ var RealtimeClient = class {
|
|
|
1415
1464
|
auth: async (cb) => {
|
|
1416
1465
|
try {
|
|
1417
1466
|
const freshToken = await this.config.getToken();
|
|
1467
|
+
if (freshToken) this.socketToken = freshToken;
|
|
1418
1468
|
cb({ token: freshToken });
|
|
1419
1469
|
} catch {
|
|
1420
1470
|
cb({ token: null });
|
|
@@ -1444,6 +1494,7 @@ var RealtimeClient = class {
|
|
|
1444
1494
|
if (this.disposed) return;
|
|
1445
1495
|
if (this.socket !== socket) return;
|
|
1446
1496
|
this.setConnectionState("connected");
|
|
1497
|
+
this.scheduleSocketTokenRefresh();
|
|
1447
1498
|
if (initialConnect) {
|
|
1448
1499
|
initialConnect = false;
|
|
1449
1500
|
if (this.socket) {
|
|
@@ -1476,14 +1527,14 @@ var RealtimeClient = class {
|
|
|
1476
1527
|
}
|
|
1477
1528
|
if (this.config.onTokenRefreshed && !this.unsubscribeFromTokenRefreshed) {
|
|
1478
1529
|
this.unsubscribeFromTokenRefreshed = this.config.onTokenRefreshed(
|
|
1479
|
-
(accessToken) =>
|
|
1480
|
-
this.socket?.emit("reauthenticate", { token: accessToken });
|
|
1481
|
-
}
|
|
1530
|
+
(accessToken) => this.reauthenticateSocket(accessToken)
|
|
1482
1531
|
);
|
|
1483
1532
|
}
|
|
1484
1533
|
if (this.subscriptions.size > 0) this.resubscribeAll();
|
|
1485
1534
|
if (this.streamSubscriptions.size > 0) void this.resubscribeAllStreams();
|
|
1486
1535
|
resolve();
|
|
1536
|
+
} else if (this.pendingReauthReplies > 0) {
|
|
1537
|
+
this.pendingReauthReplies -= 1;
|
|
1487
1538
|
} else {
|
|
1488
1539
|
this.resubscribeAll();
|
|
1489
1540
|
void this.resubscribeAllStreams();
|
|
@@ -1563,11 +1614,17 @@ var RealtimeClient = class {
|
|
|
1563
1614
|
}
|
|
1564
1615
|
}
|
|
1565
1616
|
});
|
|
1566
|
-
socket.on("disconnect", () => {
|
|
1617
|
+
socket.on("disconnect", (reason) => {
|
|
1618
|
+
if (this.socket === socket) this.pendingReauthReplies = 0;
|
|
1567
1619
|
if (this.disposed) return;
|
|
1568
1620
|
if (initialConnect) return;
|
|
1569
1621
|
if (this.socket !== socket) return;
|
|
1570
1622
|
this.setConnectionState("reconnecting");
|
|
1623
|
+
if (reason === "io server disconnect") {
|
|
1624
|
+
this.serverClosedToken = this.socketToken;
|
|
1625
|
+
this.clearSocketTokenTimer();
|
|
1626
|
+
this.scheduleRebuildRetry(SERVER_DISCONNECT_REBUILD_DELAY_MS);
|
|
1627
|
+
}
|
|
1571
1628
|
});
|
|
1572
1629
|
});
|
|
1573
1630
|
}
|
|
@@ -1629,7 +1686,72 @@ var RealtimeClient = class {
|
|
|
1629
1686
|
} catch {
|
|
1630
1687
|
}
|
|
1631
1688
|
}
|
|
1632
|
-
|
|
1689
|
+
/** #1078: send a new access token to the open socket, once per token. */
|
|
1690
|
+
reauthenticateSocket(accessToken) {
|
|
1691
|
+
if (accessToken === this.socketToken) return;
|
|
1692
|
+
if (!this.socket?.connected) return;
|
|
1693
|
+
this.socketToken = accessToken;
|
|
1694
|
+
this.pendingReauthReplies += 1;
|
|
1695
|
+
this.socket.emit("reauthenticate", { token: accessToken });
|
|
1696
|
+
this.scheduleSocketTokenRefresh();
|
|
1697
|
+
}
|
|
1698
|
+
clearSocketTokenTimer() {
|
|
1699
|
+
if (this.socketTokenTimer) {
|
|
1700
|
+
clearTimeout(this.socketTokenTimer);
|
|
1701
|
+
this.socketTokenTimer = null;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* #1078: keep the open socket's token fresh. A subscriber that only listens
|
|
1706
|
+
* makes no requests, so nothing else would refresh its token before the
|
|
1707
|
+
* gateway closes the socket at expiry. Shortly before expiry this asks the
|
|
1708
|
+
* token manager for a token (which refreshes it) and re-authenticates the
|
|
1709
|
+
* socket with the result. Tokens without a readable `exp` are left alone.
|
|
1710
|
+
*/
|
|
1711
|
+
scheduleSocketTokenRefresh(retryMs) {
|
|
1712
|
+
this.clearSocketTokenTimer();
|
|
1713
|
+
if (retryMs === void 0) this.socketTokenRetries = 0;
|
|
1714
|
+
if (this.disposed || !this.socketToken) return;
|
|
1715
|
+
const expiresAt = jwtExpiryMs(this.socketToken);
|
|
1716
|
+
if (expiresAt === null) return;
|
|
1717
|
+
const remaining = expiresAt - Date.now();
|
|
1718
|
+
const lead = Math.min(
|
|
1719
|
+
SOCKET_TOKEN_REFRESH_LEAD_MS + Math.random() * SOCKET_TOKEN_REFRESH_JITTER_MS,
|
|
1720
|
+
remaining / 2
|
|
1721
|
+
);
|
|
1722
|
+
const delay = retryMs ?? Math.max(1e3, remaining - lead);
|
|
1723
|
+
this.socketTokenTimer = setTimeout(() => {
|
|
1724
|
+
this.socketTokenTimer = null;
|
|
1725
|
+
void this.refreshSocketToken(expiresAt);
|
|
1726
|
+
}, delay);
|
|
1727
|
+
this.socketTokenTimer.unref?.();
|
|
1728
|
+
}
|
|
1729
|
+
async refreshSocketToken(expiresAt) {
|
|
1730
|
+
if (this.disposed || !this.socket) return;
|
|
1731
|
+
const previous = this.socketToken;
|
|
1732
|
+
let token = null;
|
|
1733
|
+
try {
|
|
1734
|
+
token = await this.config.getToken();
|
|
1735
|
+
} catch {
|
|
1736
|
+
}
|
|
1737
|
+
if (this.disposed || !this.socket) return;
|
|
1738
|
+
if (this.socketToken !== previous) return;
|
|
1739
|
+
if (token && token !== previous) {
|
|
1740
|
+
this.reauthenticateSocket(token);
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
const remaining = expiresAt - Date.now();
|
|
1744
|
+
if (remaining <= 0) return;
|
|
1745
|
+
const backoff = Math.min(
|
|
1746
|
+
SOCKET_TOKEN_REFRESH_RETRY_MS * 2 ** this.socketTokenRetries,
|
|
1747
|
+
SOCKET_TOKEN_REFRESH_RETRY_MAX_MS
|
|
1748
|
+
);
|
|
1749
|
+
this.socketTokenRetries += 1;
|
|
1750
|
+
this.scheduleSocketTokenRefresh(
|
|
1751
|
+
Math.min(backoff, Math.max(SOCKET_TOKEN_REFRESH_RETRY_MS, remaining / 2))
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
scheduleRebuildRetry(delayMs = REBUILD_RETRY_DELAY_MS) {
|
|
1633
1755
|
if (this.disposed || this.rebuildRetryTimer) return;
|
|
1634
1756
|
this.rebuildRetryTimer = setTimeout(() => {
|
|
1635
1757
|
this.rebuildRetryTimer = null;
|
|
@@ -1639,7 +1761,7 @@ var RealtimeClient = class {
|
|
|
1639
1761
|
}
|
|
1640
1762
|
if (this.socket?.connected) return;
|
|
1641
1763
|
void this.rebuildSocket();
|
|
1642
|
-
},
|
|
1764
|
+
}, delayMs);
|
|
1643
1765
|
this.rebuildRetryTimer.unref?.();
|
|
1644
1766
|
}
|
|
1645
1767
|
ensureWakeListeners() {
|
|
@@ -2039,10 +2161,22 @@ function mapProfile(u) {
|
|
|
2039
2161
|
roles: u.roles ?? []
|
|
2040
2162
|
};
|
|
2041
2163
|
}
|
|
2164
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
2165
|
+
var API_TOKEN_EXPIRY_DEFAULT_DAYS = 14;
|
|
2166
|
+
var API_TOKEN_EXPIRY_REMINDER_MS = DAY_MS;
|
|
2042
2167
|
var AuthModule = class _AuthModule {
|
|
2043
2168
|
constructor(http, tokenManager, config, hooks = {}) {
|
|
2044
2169
|
this.stateListeners = /* @__PURE__ */ new Set();
|
|
2045
2170
|
this.lastEmittedState = null;
|
|
2171
|
+
// #1090: expiry of the API token behind the current machine-user session, as
|
|
2172
|
+
// last reported by the token endpoint, and who wants to hear about it.
|
|
2173
|
+
this.apiTokenExpiresAt = null;
|
|
2174
|
+
// The token manager's re-auth generation of the API-token sign-in this
|
|
2175
|
+
// expiry belongs to. The expiry counts only while that generation is current:
|
|
2176
|
+
// any other sign-in, setTokens, clearTokens or auth loss moves it on. A number
|
|
2177
|
+
// on purpose, not the exchange callback, whose closure holds the API token.
|
|
2178
|
+
this.apiTokenGeneration = null;
|
|
2179
|
+
this.apiTokenExpiryListeners = /* @__PURE__ */ new Set();
|
|
2046
2180
|
this.http = http;
|
|
2047
2181
|
this.tokenManager = tokenManager;
|
|
2048
2182
|
this.config = config;
|
|
@@ -2057,9 +2191,10 @@ var AuthModule = class _AuthModule {
|
|
|
2057
2191
|
expiresAt
|
|
2058
2192
|
};
|
|
2059
2193
|
});
|
|
2060
|
-
this.unsubscribeAuthLost = this.tokenManager.onAuthLost(
|
|
2061
|
-
|
|
2062
|
-
|
|
2194
|
+
this.unsubscribeAuthLost = this.tokenManager.onAuthLost(() => {
|
|
2195
|
+
this.setApiTokenExpiry(void 0);
|
|
2196
|
+
this.emitState("unauthenticated");
|
|
2197
|
+
});
|
|
2063
2198
|
}
|
|
2064
2199
|
/**
|
|
2065
2200
|
* Returns true if a non-expired access token is currently in storage.
|
|
@@ -2120,6 +2255,7 @@ var AuthModule = class _AuthModule {
|
|
|
2120
2255
|
this.unsubscribeAuthLost = () => {
|
|
2121
2256
|
};
|
|
2122
2257
|
this.stateListeners.clear();
|
|
2258
|
+
this.apiTokenExpiryListeners.clear();
|
|
2123
2259
|
this.lastEmittedState = null;
|
|
2124
2260
|
this.beforeLogout = void 0;
|
|
2125
2261
|
this.afterSignIn = void 0;
|
|
@@ -2135,8 +2271,64 @@ var AuthModule = class _AuthModule {
|
|
|
2135
2271
|
await this.beforeLogout().catch(() => void 0);
|
|
2136
2272
|
}
|
|
2137
2273
|
await this.tokenManager.setTokens(tokens);
|
|
2274
|
+
this.setApiTokenExpiry(void 0);
|
|
2138
2275
|
this.emitState("authenticated");
|
|
2139
2276
|
}
|
|
2277
|
+
/** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
|
|
2278
|
+
setApiTokenExpiry(expiresAt) {
|
|
2279
|
+
const parsed = expiresAt ? new Date(expiresAt) : null;
|
|
2280
|
+
const next = parsed && !Number.isNaN(parsed.getTime()) ? parsed : null;
|
|
2281
|
+
if (next?.getTime() !== this.apiTokenExpiresAt?.getTime()) {
|
|
2282
|
+
for (const entry of this.apiTokenExpiryListeners) entry.lastNotifiedAt = 0;
|
|
2283
|
+
}
|
|
2284
|
+
this.apiTokenExpiresAt = next;
|
|
2285
|
+
for (const entry of this.apiTokenExpiryListeners) this.notifyApiTokenExpiry(entry);
|
|
2286
|
+
}
|
|
2287
|
+
apiTokenSessionLive() {
|
|
2288
|
+
return this.apiTokenGeneration !== null && this.apiTokenGeneration === this.tokenManager.getReauthGeneration();
|
|
2289
|
+
}
|
|
2290
|
+
notifyApiTokenExpiry(entry) {
|
|
2291
|
+
const expiresAt = this.apiTokenExpiresAt;
|
|
2292
|
+
if (!expiresAt || !this.apiTokenSessionLive()) return;
|
|
2293
|
+
const now = Date.now();
|
|
2294
|
+
if (expiresAt.getTime() - now > entry.withinMs) return;
|
|
2295
|
+
if (now - entry.lastNotifiedAt < API_TOKEN_EXPIRY_REMINDER_MS) return;
|
|
2296
|
+
entry.lastNotifiedAt = now;
|
|
2297
|
+
try {
|
|
2298
|
+
void Promise.resolve(entry.listener({ expiresAt: new Date(expiresAt) })).catch(() => void 0);
|
|
2299
|
+
} catch {
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* #1090: expiry of the project API token behind the current machine-user
|
|
2304
|
+
* session, or null when it is unknown (no API-token session, a token without
|
|
2305
|
+
* an expiry, or a server that does not report it yet).
|
|
2306
|
+
*/
|
|
2307
|
+
getApiTokenExpiry() {
|
|
2308
|
+
return this.apiTokenExpiresAt && this.apiTokenSessionLive() ? new Date(this.apiTokenExpiresAt) : null;
|
|
2309
|
+
}
|
|
2310
|
+
/**
|
|
2311
|
+
* #1090: be told when the project API token of this session expires within
|
|
2312
|
+
* `withinDays` (default 14), so a new token can be issued before the agent is
|
|
2313
|
+
* signed out. Checked at sign-in, on every re-exchange (at least every 15
|
|
2314
|
+
* minutes while the session is in use) and when the listener is added; a
|
|
2315
|
+
* listener hears about the same token at most once a day. Returns an
|
|
2316
|
+
* unsubscribe function.
|
|
2317
|
+
*/
|
|
2318
|
+
onApiTokenExpiring(listener, options = {}) {
|
|
2319
|
+
const requested = options.withinDays;
|
|
2320
|
+
const withinDays = typeof requested === "number" && Number.isFinite(requested) && requested >= 0 ? requested : API_TOKEN_EXPIRY_DEFAULT_DAYS;
|
|
2321
|
+
const entry = {
|
|
2322
|
+
listener,
|
|
2323
|
+
withinMs: withinDays * DAY_MS,
|
|
2324
|
+
lastNotifiedAt: 0
|
|
2325
|
+
};
|
|
2326
|
+
this.apiTokenExpiryListeners.add(entry);
|
|
2327
|
+
this.notifyApiTokenExpiry(entry);
|
|
2328
|
+
return () => {
|
|
2329
|
+
this.apiTokenExpiryListeners.delete(entry);
|
|
2330
|
+
};
|
|
2331
|
+
}
|
|
2140
2332
|
emitState(state) {
|
|
2141
2333
|
if (state === "authenticated") {
|
|
2142
2334
|
this.afterSignIn?.().catch(() => void 0);
|
|
@@ -2204,6 +2396,7 @@ var AuthModule = class _AuthModule {
|
|
|
2204
2396
|
} catch {
|
|
2205
2397
|
}
|
|
2206
2398
|
await this.tokenManager.clearTokens();
|
|
2399
|
+
this.setApiTokenExpiry(void 0);
|
|
2207
2400
|
this.emitState("unauthenticated");
|
|
2208
2401
|
}
|
|
2209
2402
|
/**
|
|
@@ -2266,6 +2459,8 @@ var AuthModule = class _AuthModule {
|
|
|
2266
2459
|
* browser: an API token is a long-lived secret.
|
|
2267
2460
|
*/
|
|
2268
2461
|
async loginWithApiToken(apiToken) {
|
|
2462
|
+
let reportedExpiry;
|
|
2463
|
+
let generation = null;
|
|
2269
2464
|
const exchange = async () => {
|
|
2270
2465
|
const response = await this.http.request({
|
|
2271
2466
|
method: "POST",
|
|
@@ -2273,6 +2468,10 @@ var AuthModule = class _AuthModule {
|
|
|
2273
2468
|
body: { grant_type: API_TOKEN_GRANT, client_id: this.config.clientId, api_token: apiToken },
|
|
2274
2469
|
skipAuthRefresh: true
|
|
2275
2470
|
});
|
|
2471
|
+
reportedExpiry = response.api_token_expires_at;
|
|
2472
|
+
if (generation !== null && generation === this.tokenManager.getReauthGeneration()) {
|
|
2473
|
+
this.setApiTokenExpiry(reportedExpiry ?? this.apiTokenExpiresAt?.toISOString());
|
|
2474
|
+
}
|
|
2276
2475
|
return {
|
|
2277
2476
|
accessToken: response.access_token,
|
|
2278
2477
|
expiresAt: response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0
|
|
@@ -2281,6 +2480,9 @@ var AuthModule = class _AuthModule {
|
|
|
2281
2480
|
const tokens = await exchange();
|
|
2282
2481
|
await this.installSession(tokens);
|
|
2283
2482
|
this.tokenManager.setReauthCallback(exchange);
|
|
2483
|
+
generation = this.tokenManager.getReauthGeneration();
|
|
2484
|
+
this.apiTokenGeneration = generation;
|
|
2485
|
+
this.setApiTokenExpiry(reportedExpiry);
|
|
2284
2486
|
}
|
|
2285
2487
|
async exchangeCode(params) {
|
|
2286
2488
|
const body = {
|
|
@@ -4720,6 +4922,7 @@ function createClient(config) {
|
|
|
4720
4922
|
const realtime = new RealtimeClient({
|
|
4721
4923
|
baseUrl: config.apiUrl,
|
|
4722
4924
|
getToken: () => tokenManager.getAccessToken(),
|
|
4925
|
+
refreshToken: () => tokenManager.forceRefresh(),
|
|
4723
4926
|
onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
|
|
4724
4927
|
});
|
|
4725
4928
|
const notifications = new NotificationsModule(httpClient, {
|