@geolonia/geonicdb-sdk 0.23.2 → 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/README.md CHANGED
@@ -264,7 +264,7 @@ const entity = await db.getEntity('urn:ngsi-ld:Room:001');
264
264
  const entities = await db.getEntities({
265
265
  type: 'Room',
266
266
  limit: 10,
267
- // scopeQ: '/OpenData;/OpenData/#', // exact + descendants
267
+ // scopeQ: '(/OpenData;/OpenData/#)', // exact + descendants (AND needs parentheses, #3524)
268
268
  // georel: 'near;maxDistance==1000',
269
269
  // geometry: 'Point',
270
270
  // coordinates: '139.7,35.6',
@@ -282,6 +282,10 @@ await db.updateEntity('urn:ngsi-ld:Room:001', { temperature: { type: 'Property',
282
282
  await db.deleteEntity('urn:ngsi-ld:Room:001');
283
283
  ```
284
284
 
285
+ ## Custom data model types (#3683)
286
+
287
+ `CustomDataModelSource` and `CreateCustomDataModelFromSourceInput` in `types.ts` describe the `source` metadata returned when registering via `POST /custom-data-models` with `sourceUrl`. Custom data models are per-type validation rules; `jsonSchema` is not used for validation. No dedicated SDK client methods yet.
288
+
285
289
  ## Types / Attributes Discovery
286
290
 
287
291
  ```typescript
@@ -560,7 +564,7 @@ handle.stop();
560
564
  |--------|-----------|---------|-------------|
561
565
  | `login(email, password, options?)` | `string, string, LoginOptions?` | `Promise<LoginResponse>` | Login with email and password. Upgrades the SDK out of anonymous mode. The session is DPoP sender-constrained (RFC 9449) **automatically and transparently** — no option to set; silently falls back to Bearer when Web Crypto is unavailable. Pass `{ rememberSession: true }` to keep the user signed in across page reloads (persisted to IndexedDB) |
562
566
  | `restoreSession()` | — | `Promise<boolean>` | Rehydrate a session previously persisted via `login({ rememberSession: true })`. Returns `true` if a session was found and loaded, `false` otherwise. Call at app startup before showing the login form |
563
- | `setCredentials(opts)` | `CredentialsOptions` | `this` | Set credentials externally (e.g. from a login API response). Upgrades the SDK out of anonymous mode when `tokenType: 'Bearer'`. **Throws** when `tokenType: 'DPoP'` is passed to an anonymous-built instance — anonymous instances do not generate a DPoP key pair |
567
+ | `setCredentials(opts)` | `CredentialsOptions` | `this` | Set credentials externally (e.g. from a login API response). Upgrades the SDK out of anonymous mode when `tokenType: 'Bearer'`. **Throws** when `tokenType: 'DPoP'` is passed to an anonymous-built instance — anonymous instances do not generate a DPoP key pair. **#3595**: disconnects any active WebSocket (`OPEN` or `CONNECTING`); if a socket was active, reconnects with the new credentials (subscriptions are cleared — call `subscribe()` again if needed). Concurrent `login()` / refresh / PoW responses are discarded via a generation counter; a second overlapping `login()` invalidates the first (`AuthenticationError`) |
564
568
  | `logout()` | — | `void` | Clear all credentials and disconnect WebSocket. Reverts to anonymous mode if `anonymous: true` was set at construction |
565
569
  | `isAnonymous()` | — | `boolean` | Whether explicit anonymous mode is active. Returns the explicit mode flag — not derived from credential presence — so a refresh failure that clears `_token` does NOT silently flip this back to `true` |
566
570
 
@@ -582,7 +586,8 @@ handle.stop();
582
586
  | `type` | `string` | Entity type filter |
583
587
  | `limit` | `number` | Max results |
584
588
  | `offset` | `number` | Pagination offset |
585
- | `q` | `string` | NGSI-LD query expression |
589
+ | `q` | `string` | NGSI-LD query expression (trailing path `address[city]` per clause 4.9, #3333) |
590
+ | `jsonKeys` | `string` | Comma-separated attribute names treated as opaque JSON for `q` trailing paths (clause 4.9, #3333) |
586
591
  | `datasetId` | `string` | Multi-attribute instance filter (comma-separated; default instance is `@none`). A single match is returned as one Attribute element (ETSI GS CIM 009 clause 4.5.5.1) |
587
592
  | `options` | `string` | NGSI-LD representation options (comma-separated): `sysAttrs` (include `createdAt`/`modifiedAt`), `keyValues`, `concise`, `normalized`. Under `keyValues`, multi-attributes (instances with a `datasetId`) are returned as a `dataset` map **only when more than one instance matches**, the default instance keyed by `@none`. A single matching instance stays a bare value (ETSI GS CIM 009 clause 4.5.4 / 4.5.5.1) |
588
593
  | `local` | `boolean` | **#2278.** Limit execution to local scope (ETSI GS CIM 009 clause 5.5.13). `GET /ngsi-ld/v1/entities` requires at least one of `type` / `attrs` (with a non-system attribute) / `q` (with a non-system attribute) / a geoquery / local scope (clause 5.7.2.4). **To fetch everything without a filter, pass `local: true`** — otherwise the broker returns `400 BadRequestData` (too wide query) |
@@ -593,6 +598,7 @@ handle.stop();
593
598
  |----------|------|-------------|
594
599
  | `type` | `string` | Entity type filter |
595
600
  | `q` | `string` | NGSI-LD query expression |
601
+ | `jsonKeys` | `string` | Comma-separated attribute names treated as opaque JSON for `q` trailing paths (#3333) |
596
602
  | `local` | `boolean` | **#2278.** Limit execution to local scope (ETSI GS CIM 009 clause 5.5.13). `GET /ngsi-ld/v1/entities` requires at least one of `type` / `attrs` (with a non-system attribute) / `q` (with a non-system attribute) / a geoquery / local scope (clause 5.7.2.4). **To fetch everything without a filter, pass `local: true`** — otherwise the broker returns `400 BadRequestData` (too wide query) |
597
603
 
598
604
  ### Types / Attributes Discovery
@@ -621,7 +627,8 @@ handle.stop();
621
627
  | `id` | `string` | Entity ID |
622
628
  | `idPattern` | `string` | Entity ID pattern (regex) |
623
629
  | `attrs` | `string` | Attribute names to retrieve |
624
- | `q` | `string` | NGSI-LD query expression |
630
+ | `q` | `string` | NGSI-LD query expression (trailing path / `jsonKeys` per clause 4.9, #3333) |
631
+ | `jsonKeys` | `string` | Comma-separated attribute names treated as opaque JSON for `q` trailing paths (#3333) |
625
632
  | `timeproperty` | `string` | Time property (`observedAt`, `createdAt`, `modifiedAt`, `deletedAt`; default `observedAt`) |
626
633
  | `timeAt` | `string` | Start time (ISO 8601) |
627
634
  | `endTimeAt` | `string` | End time (ISO 8601) |
@@ -646,8 +653,8 @@ handle.stop();
646
653
 
647
654
  | Method | Parameters | Returns | Description |
648
655
  |--------|-----------|---------|-------------|
649
- | `request(method, path, body?, options?)` | `string, string, unknown, RequestOptions` | `Promise<unknown>` | Authenticated request with automatic JSON parsing. `options.headers` overrides `Content-Type` / `Accept` (header names are case-insensitive) |
650
- | `requestRaw(method, path, body?, options?)` | `string, string, unknown, RequestOptions` | `Promise<Response>` | Authenticated request returning raw `Response` (for accessing headers). Same `options` as `request()` |
656
+ | `request(method, path, body?, options?)` | `string, string, unknown, RequestOptions` | `Promise<unknown>` | Authenticated request with automatic JSON parsing. `options.headers` overrides `Content-Type` / `Accept` (header names are case-insensitive). **#3595 / #3601**: `path` must be an absolute path starting with a single `/` (e.g. `/ngsi-ld/v1/entities`); host-injecting forms like `@evil/...` or `//evil/...`, and dot-segments that escape an **absolute** baseUrl path prefix (`/../x`, `/%2e%2e/x`), throw `TypeError`. Empty/relative `baseUrl` has no absolute prefix — path-prefix escape rejection does not apply there (concatenation kept) |
657
+ | `requestRaw(method, path, body?, options?)` | `string, string, unknown, RequestOptions` | `Promise<Response>` | Authenticated request returning raw `Response` (for accessing headers). Same `options` and `path` constraints as `request()` |
651
658
 
652
659
  #### Calling `POST /mcp` (#3322)
653
660
 
package/geonicdb.cjs CHANGED
@@ -604,6 +604,47 @@ function assertCallerHeadersAllowed(headers) {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 _AuthManager = class _AuthManager {
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 WebSocketManager = class {
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 GeonicDB = class extends EventEmitter {
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 GeonicDB = class extends EventEmitter {
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