@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.d.ts CHANGED
@@ -107,6 +107,11 @@ export interface GetEntitiesParams {
107
107
  offset?: number;
108
108
  /** NGSI-LD query expression */
109
109
  q?: string;
110
+ /**
111
+ * #3333: clause 4.9 `jsonKeys` — CSV of attribute names whose values are treated as
112
+ * opaque JSON (not expanded as JSON-LD) when evaluating `q` trailing paths.
113
+ */
114
+ jsonKeys?: string;
110
115
  /** NGSI-LD scope query expression (`/foo`, `/foo/#`, `/foo/+`, `;` で OR) */
111
116
  scopeQ?: string;
112
117
  /** Geo-relation: `near`, `within`, `contains`, `intersects`, `disjoint`, `equals` */
@@ -167,6 +172,8 @@ export interface CountEntitiesParams {
167
172
  type?: string;
168
173
  /** NGSI-LD query expression */
169
174
  q?: string;
175
+ /** #3333: clause 4.9 `jsonKeys` (CSV) for opaque JSON attributes in `q` trailing paths */
176
+ jsonKeys?: string;
170
177
  /** NGSI-LD scope query expression (#1132) */
171
178
  scopeQ?: string;
172
179
  /**
@@ -327,6 +334,8 @@ export interface GetTemporalEntitiesParams {
327
334
  attrs?: string;
328
335
  /** NGSI-LD query expression */
329
336
  q?: string;
337
+ /** #3333: clause 4.9 `jsonKeys` (CSV) for opaque JSON attributes in `q` trailing paths */
338
+ jsonKeys?: string;
330
339
  /** Time property to use (observedAt, createdAt, modifiedAt) */
331
340
  timeproperty?: string;
332
341
  /** Start time (ISO 8601) */
@@ -769,6 +778,13 @@ export declare class GeonicDB extends EventEmitter {
769
778
  /**
770
779
  * Set credentials externally (e.g. from a login API response).
771
780
  * When tokenType is 'Bearer' with a refreshToken, DPoP/PoW is bypassed entirely.
781
+ *
782
+ * #3595 / CodeRabbit Deep Scan `155b7206`: always disconnects any active
783
+ * WebSocket (OPEN or CONNECTING) first so events for the previous identity
784
+ * cannot continue to arrive under the new credentials. If a socket was
785
+ * active, reconnects with the newly injected token (subscriptions are
786
+ * cleared by disconnect — call `subscribe()` again after `setCredentials`
787
+ * if needed).
772
788
  */
773
789
  setCredentials(opts: CredentialsOptions): this;
774
790
  /** Clear all credentials and disconnect. */
package/geonicdb.iife.js CHANGED
@@ -604,6 +604,47 @@ var GeonicDBModule = (() => {
604
604
  }
605
605
  }
606
606
  }
607
+ function isUnderBasePath(basePathname, resolvedPathname) {
608
+ if (basePathname === "/") {
609
+ return resolvedPathname.startsWith("/");
610
+ }
611
+ const prefix = basePathname.endsWith("/") ? basePathname.slice(0, -1) : basePathname;
612
+ return resolvedPathname === prefix || resolvedPathname.startsWith(`${prefix}/`);
613
+ }
614
+ function resolveRequestUrl(baseUrl, path) {
615
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//")) {
616
+ throw new TypeError(
617
+ '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.'
618
+ );
619
+ }
620
+ if (/[\\\p{Cc}]/u.test(path)) {
621
+ throw new TypeError(
622
+ "Request path must not contain backslashes or control characters"
623
+ );
624
+ }
625
+ if (!baseUrl || !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(baseUrl)) {
626
+ return baseUrl + path;
627
+ }
628
+ let resolved;
629
+ let base;
630
+ try {
631
+ base = new URL(baseUrl);
632
+ resolved = new URL(baseUrl + path);
633
+ } catch {
634
+ throw new TypeError("Request path could not be resolved against the configured base URL");
635
+ }
636
+ if (resolved.origin !== base.origin) {
637
+ throw new TypeError(
638
+ "Request path resolves to a different origin than the configured base URL"
639
+ );
640
+ }
641
+ if (!isUnderBasePath(base.pathname, resolved.pathname)) {
642
+ throw new TypeError(
643
+ "Request path escapes the configured base URL path prefix"
644
+ );
645
+ }
646
+ return resolved.href;
647
+ }
607
648
  function mergeCallerHeaders(defaults, extraHeaders) {
608
649
  const merged = new Headers(defaults);
609
650
  const callerNames = /* @__PURE__ */ new Map();
@@ -664,6 +705,14 @@ var GeonicDBModule = (() => {
664
705
  /** Email captured at login, persisted for UI display. */
665
706
  __publicField(this, "_email", null);
666
707
  __publicField(this, "_tokenPromise", null);
708
+ /**
709
+ * #3595 / CodeRabbit Deep Scan `2d11c221`: bumped on every credential
710
+ * mutation (`login` / `setCredentials` / `logout`). In-flight refresh / PoW
711
+ * / login responses compare against the generation captured at start and
712
+ * discard the body when it no longer matches — otherwise a late response
713
+ * would overwrite credentials the caller just cleared or replaced.
714
+ */
715
+ __publicField(this, "_credentialGeneration", 0);
667
716
  /** Callback to emit tokenRefresh events. Set by GeonicDB class. */
668
717
  __publicField(this, "onTokenRefresh", null);
669
718
  /**
@@ -791,6 +840,9 @@ var GeonicDBModule = (() => {
791
840
  */
792
841
  async login(email, password, options) {
793
842
  this._log("login", email);
843
+ this._credentialGeneration++;
844
+ const generation = this._credentialGeneration;
845
+ this._tokenPromise = null;
794
846
  const wantsRemember = options?.rememberSession === true;
795
847
  const headers = {
796
848
  "Content-Type": "application/json"
@@ -825,6 +877,7 @@ var GeonicDBModule = (() => {
825
877
  });
826
878
  }
827
879
  const data = await res.json();
880
+ this._assertCredentialGeneration(generation, "login");
828
881
  this._anonymous = false;
829
882
  this._token = data.accessToken;
830
883
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
@@ -838,26 +891,31 @@ var GeonicDBModule = (() => {
838
891
  void clearDPoPSession(this._tenant);
839
892
  }
840
893
  if (this._dpopReady) await this._dpopReady;
894
+ this._assertCredentialGeneration(generation, "login");
841
895
  if (this._dpopKeyPair) {
842
896
  try {
843
897
  const bound = await this._bindDpopSession();
898
+ this._assertCredentialGeneration(generation, "login");
844
899
  if (this._rememberSession) {
845
900
  await this._persistDpopSession();
846
901
  await this._enablePersistentCache(true);
847
902
  } else {
848
903
  this._disablePersistentCache();
849
904
  }
905
+ this._assertCredentialGeneration(generation, "login");
850
906
  return bound;
851
907
  } catch (err) {
852
- this._token = null;
853
- this._tokenExpiry = 0;
854
- this._tokenType = "Bearer";
855
- this._refreshToken = null;
856
- this._tokenPromise = null;
857
- this._invalidateAuthScopedState();
858
- this._disablePersistentCache();
859
- this._rememberSession = false;
860
- this._email = null;
908
+ if (generation === this._credentialGeneration) {
909
+ this._token = null;
910
+ this._tokenExpiry = 0;
911
+ this._tokenType = "Bearer";
912
+ this._refreshToken = null;
913
+ this._tokenPromise = null;
914
+ this._invalidateAuthScopedState();
915
+ this._disablePersistentCache();
916
+ this._rememberSession = false;
917
+ this._email = null;
918
+ }
861
919
  throw err;
862
920
  }
863
921
  }
@@ -884,6 +942,7 @@ var GeonicDBModule = (() => {
884
942
  "Cannot bind DPoP session: no Bearer token. login() must succeed first."
885
943
  );
886
944
  }
945
+ const generation = this._credentialGeneration;
887
946
  if (this._dpopReady) await this._dpopReady;
888
947
  if (!this._dpopKeyPair) {
889
948
  throw new AuthenticationError(
@@ -893,6 +952,7 @@ var GeonicDBModule = (() => {
893
952
  const bindUrl = this._baseUrl + "/auth/dpop-bind";
894
953
  const accessToken = this._token;
895
954
  const data = await this._doDpopBind(bindUrl, accessToken, this._dpopNonce, 0);
955
+ this._assertCredentialGeneration(generation, "DPoP bind");
896
956
  this._token = data.accessToken;
897
957
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
898
958
  this._tokenType = "DPoP";
@@ -940,13 +1000,22 @@ var GeonicDBModule = (() => {
940
1000
  * When tokenType is 'Bearer' and refreshToken is provided, all subsequent
941
1001
  * API calls and connect() bypass DPoP/PoW entirely.
942
1002
  */
943
- setCredentials(opts) {
1003
+ /**
1004
+ * Validate credentials options without mutating state.
1005
+ * #3595: GeonicDB.setCredentials calls this before disconnecting WebSocket
1006
+ * so a rejected token/DPoP check does not tear down an active socket.
1007
+ */
1008
+ assertCredentialsAllowed(opts) {
944
1009
  if (!opts || !opts.token) throw new Error("token is required");
945
1010
  if (this._initialAnonymous && opts.tokenType === "DPoP") {
946
1011
  throw new Error(
947
1012
  "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."
948
1013
  );
949
1014
  }
1015
+ }
1016
+ setCredentials(opts) {
1017
+ this.assertCredentialsAllowed(opts);
1018
+ this._credentialGeneration++;
950
1019
  this._anonymous = false;
951
1020
  this._token = opts.token;
952
1021
  this._tokenType = opts.tokenType || "Bearer";
@@ -963,6 +1032,7 @@ var GeonicDBModule = (() => {
963
1032
  }
964
1033
  /** Clear all credentials. */
965
1034
  logout() {
1035
+ this._credentialGeneration++;
966
1036
  this._token = null;
967
1037
  this._tokenExpiry = 0;
968
1038
  this._refreshToken = null;
@@ -1087,8 +1157,20 @@ var GeonicDBModule = (() => {
1087
1157
  this._tokenPromise = this._acquireTokenViaPow();
1088
1158
  return this._tokenPromise;
1089
1159
  }
1160
+ /**
1161
+ * #3595: throw when credentials mutated while an async auth exchange was
1162
+ * in flight. Leaves existing `_token` / `_refreshToken` untouched.
1163
+ */
1164
+ _assertCredentialGeneration(generation, operation) {
1165
+ if (generation !== this._credentialGeneration) {
1166
+ throw new AuthenticationError(
1167
+ `Credentials changed during ${operation}; discarding stale response`
1168
+ );
1169
+ }
1170
+ }
1090
1171
  async _refreshBearerToken() {
1091
1172
  this._log("refreshing token (type=%s)", this._tokenType);
1173
+ const generation = this._credentialGeneration;
1092
1174
  try {
1093
1175
  const isDPoP = this._tokenType === "DPoP";
1094
1176
  const refreshUrl = this._baseUrl + "/auth/refresh";
@@ -1099,12 +1181,15 @@ var GeonicDBModule = (() => {
1099
1181
  body
1100
1182
  });
1101
1183
  if (!res.ok) {
1102
- this._refreshToken = null;
1103
- this._token = null;
1104
- this._tokenPromise = null;
1184
+ if (generation === this._credentialGeneration) {
1185
+ this._refreshToken = null;
1186
+ this._token = null;
1187
+ this._tokenPromise = null;
1188
+ }
1105
1189
  throw new AuthenticationError("Token refresh failed: " + res.status, res.status);
1106
1190
  }
1107
1191
  const data = await res.json();
1192
+ this._assertCredentialGeneration(generation, "token refresh");
1108
1193
  this._token = data.accessToken;
1109
1194
  this._tokenExpiry = Date.now() + (data.expiresIn - 60) * 1e3;
1110
1195
  this._tokenType = data.tokenType ?? (isDPoP ? "DPoP" : "Bearer");
@@ -1119,7 +1204,9 @@ var GeonicDBModule = (() => {
1119
1204
  if (this._rememberSession) void this._persistDpopSession();
1120
1205
  return this._token;
1121
1206
  } catch (err) {
1122
- this._tokenPromise = null;
1207
+ if (generation === this._credentialGeneration) {
1208
+ this._tokenPromise = null;
1209
+ }
1123
1210
  throw err;
1124
1211
  }
1125
1212
  }
@@ -1162,6 +1249,7 @@ var GeonicDBModule = (() => {
1162
1249
  against a live server. Unit-mocking each fetch + crypto step would not
1163
1250
  verify the actual nonce/proof exchange. */
1164
1251
  async _acquireTokenViaPow() {
1252
+ const generation = this._credentialGeneration;
1165
1253
  try {
1166
1254
  if (this._dpopReady) await this._dpopReady;
1167
1255
  const nonceRes = await fetch(this._baseUrl + "/auth/nonce", {
@@ -1187,13 +1275,16 @@ var GeonicDBModule = (() => {
1187
1275
  const newNonce = res.headers.get("DPoP-Nonce");
1188
1276
  if (newNonce) this._dpopNonce = newNonce;
1189
1277
  const data = await res.json();
1278
+ this._assertCredentialGeneration(generation, "PoW token acquisition");
1190
1279
  this._token = data.access_token;
1191
1280
  this._tokenExpiry = Date.now() + (data.expires_in - 60) * 1e3;
1192
1281
  this._tokenType = data.token_type || "Bearer";
1193
1282
  this._tokenPromise = null;
1194
1283
  return this._token;
1195
1284
  } catch (err) {
1196
- this._tokenPromise = null;
1285
+ if (generation === this._credentialGeneration) {
1286
+ this._tokenPromise = null;
1287
+ }
1197
1288
  throw err;
1198
1289
  }
1199
1290
  }
@@ -1248,6 +1339,7 @@ var GeonicDBModule = (() => {
1248
1339
  async request(method, path, body, headers) {
1249
1340
  this._log(method, path);
1250
1341
  assertCallerHeadersAllowed(headers);
1342
+ resolveRequestUrl(this._baseUrl, path);
1251
1343
  if (!this._cache || !isCacheableMethod(method) || body !== void 0 || headers !== void 0) {
1252
1344
  const token = this.isAnonymous() ? null : await this.ensureToken();
1253
1345
  const res = await this._doAuthenticatedRequest(method, path, body, token, 0, headers);
@@ -1326,7 +1418,7 @@ var GeonicDBModule = (() => {
1326
1418
  );
1327
1419
  }
1328
1420
  }
1329
- const url = this._baseUrl + path;
1421
+ const url = resolveRequestUrl(this._baseUrl, path);
1330
1422
  const isDPoP = this._tokenType === "DPoP" && !!this._dpopKeyPair && token !== null;
1331
1423
  const pathname = path.split("?")[0];
1332
1424
  const isNgsiLdWrite = pathname.startsWith("/ngsi-ld/v1/") && pathname !== "/ngsi-ld/v1/jsonldContexts";
@@ -1475,6 +1567,14 @@ var GeonicDBModule = (() => {
1475
1567
  isConnected() {
1476
1568
  return !!(this._ws && this._ws.readyState === WebSocket.OPEN);
1477
1569
  }
1570
+ /**
1571
+ * True when a socket exists in OPEN or CONNECTING.
1572
+ * #3595: `setCredentials` uses this (not `isConnected`) so a mid-handshake
1573
+ * socket is still torn down and reconnected under the new identity.
1574
+ */
1575
+ hasActiveSocket() {
1576
+ return !!(this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING));
1577
+ }
1478
1578
  /** Subscribe to entity events (can be called before or after connect). */
1479
1579
  subscribe(options) {
1480
1580
  const msg = { action: "subscribe" };
@@ -1975,9 +2075,22 @@ var GeonicDBModule = (() => {
1975
2075
  /**
1976
2076
  * Set credentials externally (e.g. from a login API response).
1977
2077
  * When tokenType is 'Bearer' with a refreshToken, DPoP/PoW is bypassed entirely.
2078
+ *
2079
+ * #3595 / CodeRabbit Deep Scan `155b7206`: always disconnects any active
2080
+ * WebSocket (OPEN or CONNECTING) first so events for the previous identity
2081
+ * cannot continue to arrive under the new credentials. If a socket was
2082
+ * active, reconnects with the newly injected token (subscriptions are
2083
+ * cleared by disconnect — call `subscribe()` again after `setCredentials`
2084
+ * if needed).
1978
2085
  */
1979
2086
  setCredentials(opts) {
2087
+ this._auth.assertCredentialsAllowed(opts);
2088
+ const wasActive = this._ws.hasActiveSocket();
2089
+ this._ws.disconnect();
1980
2090
  this._auth.setCredentials(opts);
2091
+ if (wasActive) {
2092
+ void this._ws.connect();
2093
+ }
1981
2094
  return this;
1982
2095
  }
1983
2096
  /** Clear all credentials and disconnect. */
@@ -2092,6 +2205,7 @@ var GeonicDBModule = (() => {
2092
2205
  limit: 0,
2093
2206
  type: params?.type,
2094
2207
  q: params?.q,
2208
+ jsonKeys: params?.jsonKeys,
2095
2209
  scopeQ: params?.scopeQ,
2096
2210
  // #2278: clause 5.7.2.4 の "too wide query" 免除条件 (e) local scope。
2097
2211
  local: params?.local