@geolonia/geonicdb-sdk 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/geonicdb.mjs CHANGED
@@ -563,6 +563,47 @@ function assertCallerHeadersAllowed(headers) {
563
563
  }
564
564
  }
565
565
  }
566
+ function isUnderBasePath(basePathname, resolvedPathname) {
567
+ if (basePathname === "/") {
568
+ return resolvedPathname.startsWith("/");
569
+ }
570
+ const prefix = basePathname.endsWith("/") ? basePathname.slice(0, -1) : basePathname;
571
+ return resolvedPathname === prefix || resolvedPathname.startsWith(`${prefix}/`);
572
+ }
573
+ function resolveRequestUrl(baseUrl, path) {
574
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//")) {
575
+ throw new TypeError(
576
+ 'Request path must be an absolute path starting with a single "/" (e.g. "/ngsi-ld/v1/entities"). Protocol-relative and host-injecting paths are rejected.'
577
+ );
578
+ }
579
+ if (/[\\\p{Cc}]/u.test(path)) {
580
+ throw new TypeError(
581
+ "Request path must not contain backslashes or control characters"
582
+ );
583
+ }
584
+ if (!baseUrl || !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(baseUrl)) {
585
+ return baseUrl + path;
586
+ }
587
+ let resolved;
588
+ let base;
589
+ try {
590
+ base = new URL(baseUrl);
591
+ resolved = new URL(baseUrl + path);
592
+ } catch {
593
+ throw new TypeError("Request path could not be resolved against the configured base URL");
594
+ }
595
+ if (resolved.origin !== base.origin) {
596
+ throw new TypeError(
597
+ "Request path resolves to a different origin than the configured base URL"
598
+ );
599
+ }
600
+ if (!isUnderBasePath(base.pathname, resolved.pathname)) {
601
+ throw new TypeError(
602
+ "Request path escapes the configured base URL path prefix"
603
+ );
604
+ }
605
+ return resolved.href;
606
+ }
566
607
  function mergeCallerHeaders(defaults, extraHeaders) {
567
608
  const merged = new Headers(defaults);
568
609
  const callerNames = /* @__PURE__ */ new Map();
@@ -623,6 +664,14 @@ var _AuthManager = class _AuthManager {
623
664
  /** Email captured at login, persisted for UI display. */
624
665
  __publicField(this, "_email", null);
625
666
  __publicField(this, "_tokenPromise", null);
667
+ /**
668
+ * #3595 / CodeRabbit Deep Scan `2d11c221`: bumped on every credential
669
+ * mutation (`login` / `setCredentials` / `logout`). In-flight refresh / PoW
670
+ * / login responses compare against the generation captured at start and
671
+ * discard the body when it no longer matches — otherwise a late response
672
+ * would overwrite credentials the caller just cleared or replaced.
673
+ */
674
+ __publicField(this, "_credentialGeneration", 0);
626
675
  /** Callback to emit tokenRefresh events. Set by GeonicDB class. */
627
676
  __publicField(this, "onTokenRefresh", null);
628
677
  /**
@@ -750,6 +799,9 @@ var _AuthManager = class _AuthManager {
750
799
  */
751
800
  async login(email, password, options) {
752
801
  this._log("login", email);
802
+ this._credentialGeneration++;
803
+ const generation = this._credentialGeneration;
804
+ this._tokenPromise = null;
753
805
  const wantsRemember = options?.rememberSession === true;
754
806
  const headers = {
755
807
  "Content-Type": "application/json"
@@ -784,6 +836,7 @@ var _AuthManager = class _AuthManager {
784
836
  });
785
837
  }
786
838
  const data = await res.json();
839
+ this._assertCredentialGeneration(generation, "login");
787
840
  this._anonymous = false;
788
841
  this._token = data.accessToken;
789
842
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
@@ -797,26 +850,31 @@ var _AuthManager = class _AuthManager {
797
850
  void clearDPoPSession(this._tenant);
798
851
  }
799
852
  if (this._dpopReady) await this._dpopReady;
853
+ this._assertCredentialGeneration(generation, "login");
800
854
  if (this._dpopKeyPair) {
801
855
  try {
802
856
  const bound = await this._bindDpopSession();
857
+ this._assertCredentialGeneration(generation, "login");
803
858
  if (this._rememberSession) {
804
859
  await this._persistDpopSession();
805
860
  await this._enablePersistentCache(true);
806
861
  } else {
807
862
  this._disablePersistentCache();
808
863
  }
864
+ this._assertCredentialGeneration(generation, "login");
809
865
  return bound;
810
866
  } catch (err) {
811
- this._token = null;
812
- this._tokenExpiry = 0;
813
- this._tokenType = "Bearer";
814
- this._refreshToken = null;
815
- this._tokenPromise = null;
816
- this._invalidateAuthScopedState();
817
- this._disablePersistentCache();
818
- this._rememberSession = false;
819
- this._email = null;
867
+ if (generation === this._credentialGeneration) {
868
+ this._token = null;
869
+ this._tokenExpiry = 0;
870
+ this._tokenType = "Bearer";
871
+ this._refreshToken = null;
872
+ this._tokenPromise = null;
873
+ this._invalidateAuthScopedState();
874
+ this._disablePersistentCache();
875
+ this._rememberSession = false;
876
+ this._email = null;
877
+ }
820
878
  throw err;
821
879
  }
822
880
  }
@@ -843,6 +901,7 @@ var _AuthManager = class _AuthManager {
843
901
  "Cannot bind DPoP session: no Bearer token. login() must succeed first."
844
902
  );
845
903
  }
904
+ const generation = this._credentialGeneration;
846
905
  if (this._dpopReady) await this._dpopReady;
847
906
  if (!this._dpopKeyPair) {
848
907
  throw new AuthenticationError(
@@ -852,6 +911,7 @@ var _AuthManager = class _AuthManager {
852
911
  const bindUrl = this._baseUrl + "/auth/dpop-bind";
853
912
  const accessToken = this._token;
854
913
  const data = await this._doDpopBind(bindUrl, accessToken, this._dpopNonce, 0);
914
+ this._assertCredentialGeneration(generation, "DPoP bind");
855
915
  this._token = data.accessToken;
856
916
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
857
917
  this._tokenType = "DPoP";
@@ -899,13 +959,22 @@ var _AuthManager = class _AuthManager {
899
959
  * When tokenType is 'Bearer' and refreshToken is provided, all subsequent
900
960
  * API calls and connect() bypass DPoP/PoW entirely.
901
961
  */
902
- setCredentials(opts) {
962
+ /**
963
+ * Validate credentials options without mutating state.
964
+ * #3595: GeonicDB.setCredentials calls this before disconnecting WebSocket
965
+ * so a rejected token/DPoP check does not tear down an active socket.
966
+ */
967
+ assertCredentialsAllowed(opts) {
903
968
  if (!opts || !opts.token) throw new Error("token is required");
904
969
  if (this._initialAnonymous && opts.tokenType === "DPoP") {
905
970
  throw new Error(
906
971
  "DPoP credentials cannot be set on an SDK instance constructed with `anonymous: true` (no DPoP key pair is generated for anonymous instances). Use Bearer credentials, or construct the SDK in non-anonymous mode."
907
972
  );
908
973
  }
974
+ }
975
+ setCredentials(opts) {
976
+ this.assertCredentialsAllowed(opts);
977
+ this._credentialGeneration++;
909
978
  this._anonymous = false;
910
979
  this._token = opts.token;
911
980
  this._tokenType = opts.tokenType || "Bearer";
@@ -922,6 +991,7 @@ var _AuthManager = class _AuthManager {
922
991
  }
923
992
  /** Clear all credentials. */
924
993
  logout() {
994
+ this._credentialGeneration++;
925
995
  this._token = null;
926
996
  this._tokenExpiry = 0;
927
997
  this._refreshToken = null;
@@ -1046,8 +1116,20 @@ var _AuthManager = class _AuthManager {
1046
1116
  this._tokenPromise = this._acquireTokenViaPow();
1047
1117
  return this._tokenPromise;
1048
1118
  }
1119
+ /**
1120
+ * #3595: throw when credentials mutated while an async auth exchange was
1121
+ * in flight. Leaves existing `_token` / `_refreshToken` untouched.
1122
+ */
1123
+ _assertCredentialGeneration(generation, operation) {
1124
+ if (generation !== this._credentialGeneration) {
1125
+ throw new AuthenticationError(
1126
+ `Credentials changed during ${operation}; discarding stale response`
1127
+ );
1128
+ }
1129
+ }
1049
1130
  async _refreshBearerToken() {
1050
1131
  this._log("refreshing token (type=%s)", this._tokenType);
1132
+ const generation = this._credentialGeneration;
1051
1133
  try {
1052
1134
  const isDPoP = this._tokenType === "DPoP";
1053
1135
  const refreshUrl = this._baseUrl + "/auth/refresh";
@@ -1058,12 +1140,15 @@ var _AuthManager = class _AuthManager {
1058
1140
  body
1059
1141
  });
1060
1142
  if (!res.ok) {
1061
- this._refreshToken = null;
1062
- this._token = null;
1063
- this._tokenPromise = null;
1143
+ if (generation === this._credentialGeneration) {
1144
+ this._refreshToken = null;
1145
+ this._token = null;
1146
+ this._tokenPromise = null;
1147
+ }
1064
1148
  throw new AuthenticationError("Token refresh failed: " + res.status, res.status);
1065
1149
  }
1066
1150
  const data = await res.json();
1151
+ this._assertCredentialGeneration(generation, "token refresh");
1067
1152
  this._token = data.accessToken;
1068
1153
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
1069
1154
  this._tokenType = data.tokenType ?? (isDPoP ? "DPoP" : "Bearer");
@@ -1078,7 +1163,9 @@ var _AuthManager = class _AuthManager {
1078
1163
  if (this._rememberSession) void this._persistDpopSession();
1079
1164
  return this._token;
1080
1165
  } catch (err) {
1081
- this._tokenPromise = null;
1166
+ if (generation === this._credentialGeneration) {
1167
+ this._tokenPromise = null;
1168
+ }
1082
1169
  throw err;
1083
1170
  }
1084
1171
  }
@@ -1121,6 +1208,7 @@ var _AuthManager = class _AuthManager {
1121
1208
  against a live server. Unit-mocking each fetch + crypto step would not
1122
1209
  verify the actual nonce/proof exchange. */
1123
1210
  async _acquireTokenViaPow() {
1211
+ const generation = this._credentialGeneration;
1124
1212
  try {
1125
1213
  if (this._dpopReady) await this._dpopReady;
1126
1214
  const nonceRes = await fetch(this._baseUrl + "/auth/nonce", {
@@ -1146,13 +1234,16 @@ var _AuthManager = class _AuthManager {
1146
1234
  const newNonce = res.headers.get("DPoP-Nonce");
1147
1235
  if (newNonce) this._dpopNonce = newNonce;
1148
1236
  const data = await res.json();
1237
+ this._assertCredentialGeneration(generation, "PoW token acquisition");
1149
1238
  this._token = data.access_token;
1150
1239
  this._tokenExpiry = Date.now() + (data.expires_in - 60) * 1e3;
1151
1240
  this._tokenType = data.token_type || "Bearer";
1152
1241
  this._tokenPromise = null;
1153
1242
  return this._token;
1154
1243
  } catch (err) {
1155
- this._tokenPromise = null;
1244
+ if (generation === this._credentialGeneration) {
1245
+ this._tokenPromise = null;
1246
+ }
1156
1247
  throw err;
1157
1248
  }
1158
1249
  }
@@ -1207,6 +1298,7 @@ var _AuthManager = class _AuthManager {
1207
1298
  async request(method, path, body, headers) {
1208
1299
  this._log(method, path);
1209
1300
  assertCallerHeadersAllowed(headers);
1301
+ resolveRequestUrl(this._baseUrl, path);
1210
1302
  if (!this._cache || !isCacheableMethod(method) || body !== void 0 || headers !== void 0) {
1211
1303
  const token = this.isAnonymous() ? null : await this.ensureToken();
1212
1304
  const res = await this._doAuthenticatedRequest(method, path, body, token, 0, headers);
@@ -1285,7 +1377,7 @@ var _AuthManager = class _AuthManager {
1285
1377
  );
1286
1378
  }
1287
1379
  }
1288
- const url = this._baseUrl + path;
1380
+ const url = resolveRequestUrl(this._baseUrl, path);
1289
1381
  const isDPoP = this._tokenType === "DPoP" && !!this._dpopKeyPair && token !== null;
1290
1382
  const pathname = path.split("?")[0];
1291
1383
  const isNgsiLdWrite = pathname.startsWith("/ngsi-ld/v1/") && pathname !== "/ngsi-ld/v1/jsonldContexts";
@@ -1434,6 +1526,14 @@ var WebSocketManager = class {
1434
1526
  isConnected() {
1435
1527
  return !!(this._ws && this._ws.readyState === WebSocket.OPEN);
1436
1528
  }
1529
+ /**
1530
+ * True when a socket exists in OPEN or CONNECTING.
1531
+ * #3595: `setCredentials` uses this (not `isConnected`) so a mid-handshake
1532
+ * socket is still torn down and reconnected under the new identity.
1533
+ */
1534
+ hasActiveSocket() {
1535
+ return !!(this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING));
1536
+ }
1437
1537
  /** Subscribe to entity events (can be called before or after connect). */
1438
1538
  subscribe(options) {
1439
1539
  const msg = { action: "subscribe" };
@@ -1934,9 +2034,22 @@ var GeonicDB = class extends EventEmitter {
1934
2034
  /**
1935
2035
  * Set credentials externally (e.g. from a login API response).
1936
2036
  * When tokenType is 'Bearer' with a refreshToken, DPoP/PoW is bypassed entirely.
2037
+ *
2038
+ * #3595 / CodeRabbit Deep Scan `155b7206`: always disconnects any active
2039
+ * WebSocket (OPEN or CONNECTING) first so events for the previous identity
2040
+ * cannot continue to arrive under the new credentials. If a socket was
2041
+ * active, reconnects with the newly injected token (subscriptions are
2042
+ * cleared by disconnect — call `subscribe()` again after `setCredentials`
2043
+ * if needed).
1937
2044
  */
1938
2045
  setCredentials(opts) {
2046
+ this._auth.assertCredentialsAllowed(opts);
2047
+ const wasActive = this._ws.hasActiveSocket();
2048
+ this._ws.disconnect();
1939
2049
  this._auth.setCredentials(opts);
2050
+ if (wasActive) {
2051
+ void this._ws.connect();
2052
+ }
1940
2053
  return this;
1941
2054
  }
1942
2055
  /** Clear all credentials and disconnect. */
@@ -2051,6 +2164,7 @@ var GeonicDB = class extends EventEmitter {
2051
2164
  limit: 0,
2052
2165
  type: params?.type,
2053
2166
  q: params?.q,
2167
+ jsonKeys: params?.jsonKeys,
2054
2168
  scopeQ: params?.scopeQ,
2055
2169
  // #2278: clause 5.7.2.4 の "too wide query" 免除条件 (e) local scope。
2056
2170
  local: params?.local