@xcitedbs/client 0.2.8 → 0.2.9

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/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AccessCheckResult, AppAuthConfig, AppEmailConfig, AppEmailTemplates, AppUser, AppUserTokenPair, EmailTestResponse, ForgotPasswordResponse, SendVerificationResponse, BranchInfo, CommitRecord, DatabaseContext, DiffRef, DiffResult, Flags, ListIdentifierChildrenResult, ListIdentifiersResult, LockInfo, LogEntry, MergeResult, MetaValue, PlatformRegisterResult, PolicySubjectInput, UnqueryResult, UnqueryTemplate, PolicyUpdateResponse, RealtimeEvent, SecurityConfig, SecurityPolicy, StoredTriggerResponse, TriggerDefinition, StoredPolicyResponse, SubscriptionOptions, TagRecord, TextSearchQuery, TextSearchResult, OAuthProvidersResponse, ProjectInfo, PlatformRegistrationConfig, PlatformWorkspacesResponse, TokenPair, UserInfo, ApiKeyInfo, WriteDocumentOptions, CreateTestSessionOptions, XCiteDBClientOptions, XCiteQuery } from './types';
1
+ import { AccessCheckResult, AppAuthConfig, AppEmailConfig, AppEmailTemplates, AppUser, AppUserTokenPair, EmailTestResponse, ForgotPasswordResponse, SendVerificationResponse, BranchInfo, CommitRecord, DatabaseContext, DiffRef, DiffResult, Flags, ListIdentifierChildrenResult, ListIdentifiersResult, LockInfo, LogEntry, MergeResult, MetaValue, PlatformRegisterResult, PolicySubjectInput, UnqueryResult, UnqueryTemplate, PolicyUpdateResponse, RealtimeEvent, SecurityConfig, SecurityPolicy, StoredTriggerResponse, TriggerDefinition, StoredPolicyResponse, SubscriptionOptions, TagRecord, TextSearchQuery, TextSearchResult, OAuthProvidersResponse, ProjectInfo, PlatformRegistrationConfig, PlatformWorkspacesResponse, TokenPair, UserInfo, ApiKeyInfo, WriteDocumentOptions, CreateTestSessionOptions, XCiteDBClientOptions, XCiteDBJwtClaims, XCiteQuery } from './types';
2
2
  import { WebSocketSubscription } from './websocket';
3
3
  export declare class XCiteDBClient {
4
4
  private baseUrl;
@@ -22,6 +22,17 @@ export declare class XCiteDBClient {
22
22
  * then returns a client that sends `X-Test-Session` (auth-free by default).
23
23
  */
24
24
  static createTestSession(opts: CreateTestSessionOptions): Promise<XCiteDBClient>;
25
+ /**
26
+ * Canonical `project:<tenant_id>:<role>` group string. The middle segment must match the app JWT `tenant_id`
27
+ * (internal project id), not the human-readable project name.
28
+ */
29
+ static buildProjectGroup(projectId: string, role: 'admin' | 'editor' | 'viewer'): string;
30
+ private static decodeJwtPayloadJson;
31
+ /**
32
+ * Decode `appUserAccessToken`, or `accessToken` if no app token (platform JWT), without verifying the signature.
33
+ * Use for debugging ABAC (compare `tenant_id` and `groups` to `project:<…>:role` in policies).
34
+ */
35
+ getTokenClaims(): XCiteDBJwtClaims | null;
25
36
  /** Destroy this test session on the server (`DELETE /api/v1/test/sessions/current`). */
26
37
  destroyTestSession(): Promise<{
27
38
  message: string;
package/dist/client.js CHANGED
@@ -69,6 +69,81 @@ class XCiteDBClient {
69
69
  testRequireAuth: opts.testRequireAuth,
70
70
  });
71
71
  }
72
+ /**
73
+ * Canonical `project:<tenant_id>:<role>` group string. The middle segment must match the app JWT `tenant_id`
74
+ * (internal project id), not the human-readable project name.
75
+ */
76
+ static buildProjectGroup(projectId, role) {
77
+ return `project:${projectId}:${role}`;
78
+ }
79
+ static decodeJwtPayloadJson(token) {
80
+ const parts = token.split('.');
81
+ if (parts.length < 2)
82
+ return null;
83
+ try {
84
+ let b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
85
+ const pad = (4 - (b64.length % 4)) % 4;
86
+ b64 += '='.repeat(pad);
87
+ const g = globalThis;
88
+ let json = null;
89
+ if (g.Buffer) {
90
+ json = g.Buffer.from(b64, 'base64').toString('utf8');
91
+ }
92
+ else if (typeof atob === 'function') {
93
+ json = atob(b64);
94
+ }
95
+ if (json === null)
96
+ return null;
97
+ return JSON.parse(json);
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }
103
+ /**
104
+ * Decode `appUserAccessToken`, or `accessToken` if no app token (platform JWT), without verifying the signature.
105
+ * Use for debugging ABAC (compare `tenant_id` and `groups` to `project:<…>:role` in policies).
106
+ */
107
+ getTokenClaims() {
108
+ const raw = this.appUserAccessToken ?? this.accessToken;
109
+ if (!raw)
110
+ return null;
111
+ const p = XCiteDBClient.decodeJwtPayloadJson(raw);
112
+ if (!p)
113
+ return null;
114
+ let groups = [];
115
+ const g = p['groups'];
116
+ if (Array.isArray(g)) {
117
+ groups = g.filter((x) => typeof x === 'string');
118
+ }
119
+ else if (g && typeof g === 'object' && !Array.isArray(g)) {
120
+ groups = Object.keys(g);
121
+ }
122
+ else if (typeof g === 'string') {
123
+ groups = g.split(',').map((s) => s.trim()).filter(Boolean);
124
+ }
125
+ const sub = p['sub'];
126
+ const tenant_id = p['tenant_id'];
127
+ if (typeof sub !== 'string' || typeof tenant_id !== 'string')
128
+ return null;
129
+ const email = p['email'];
130
+ const type = p['type'];
131
+ const exp = p['exp'];
132
+ const iat = p['iat'];
133
+ const iss = p['iss'];
134
+ const jti = p['jti'];
135
+ return {
136
+ sub,
137
+ tenant_id,
138
+ groups,
139
+ email: typeof email === 'string' ? email : undefined,
140
+ type: typeof type === 'string' ? type : undefined,
141
+ exp: typeof exp === 'number' ? exp : undefined,
142
+ iat: typeof iat === 'number' ? iat : undefined,
143
+ iss: typeof iss === 'string' ? iss : undefined,
144
+ jti: typeof jti === 'string' ? jti : undefined,
145
+ };
146
+ }
72
147
  /** Destroy this test session on the server (`DELETE /api/v1/test/sessions/current`). */
73
148
  async destroyTestSession() {
74
149
  if (!this.testSessionToken) {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { XCiteDBClient } from './client';
2
2
  export { WebSocketSubscription } from './websocket';
3
- export type { AccessCheckResult, ApiKeyInfo, AppAuthConfig, AppEmailConfig, AppEmailSmtpConfig, AppEmailTemplateEntry, AppEmailTemplates, AppEmailWebhookConfig, AppUser, AppUserTokenPair, EmailTestResponse, ForgotPasswordResponse, SendVerificationResponse, DatabaseContext, Flags, JsonDocumentData, IdentifierChildNode, ListIdentifierChildrenResult, ListIdentifiersResult, LockInfo, OAuthProviderInfo, OAuthProvidersResponse, OwnedTenantInfo, ProjectInfo, PlatformRegistrationConfig, PlatformWorkspaceOrg, PlatformWorkspacesResponse, LogEntry, MetaValue, PlatformRegisterResult, PolicyUpdateResponse, PolicyConditions, PolicyIdentifierPattern, PolicyResources, PolicySubjectInput, PolicySubjects, RealtimeEvent, SecurityConfig, SecurityPolicy, StoredPolicyResponse, StoredTriggerResponse, SubscriptionOptions, TextSearchHit, TextSearchQuery, TextSearchResult, TriggerDefinition, TokenPair, UserInfo, WriteDocumentOptions, CreateTestSessionOptions, XCiteDBClientOptions, UnqueryResult, UnqueryTemplate, XCiteQuery, } from './types';
3
+ export type { AccessCheckResult, ApiKeyInfo, AppAuthConfig, AppEmailConfig, AppEmailSmtpConfig, AppEmailTemplateEntry, AppEmailTemplates, AppEmailWebhookConfig, AppUser, AppUserTokenPair, EmailTestResponse, ForgotPasswordResponse, SendVerificationResponse, DatabaseContext, Flags, JsonDocumentData, IdentifierChildNode, ListIdentifierChildrenResult, ListIdentifiersResult, LockInfo, OAuthProviderInfo, OAuthProvidersResponse, OwnedTenantInfo, ProjectInfo, PlatformRegistrationConfig, PlatformWorkspaceOrg, PlatformWorkspacesResponse, LogEntry, MetaValue, PlatformRegisterResult, PolicyUpdateResponse, PolicyConditions, PolicyIdentifierPattern, PolicyResources, PolicySubjectInput, PolicySubjects, RealtimeEvent, SecurityConfig, SecurityPolicy, StoredPolicyResponse, StoredTriggerResponse, SubscriptionOptions, TextSearchHit, TextSearchQuery, TextSearchResult, TriggerDefinition, TokenPair, UserInfo, WriteDocumentOptions, CreateTestSessionOptions, XCiteDBClientOptions, XCiteDBJwtClaims, UnqueryResult, UnqueryTemplate, XCiteQuery, } from './types';
4
4
  export { XCiteDBError } from './types';
package/dist/types.d.ts CHANGED
@@ -116,6 +116,21 @@ export interface ProjectInfo {
116
116
  }
117
117
  /** @deprecated Use {@link ProjectInfo}. */
118
118
  export type OwnedTenantInfo = ProjectInfo;
119
+ /**
120
+ * Payload claims from an XCiteDB-issued access JWT (decode only; no signature verification).
121
+ * Prefer {@link XCiteDBClient.getTokenClaims} to compare `tenant_id` / `groups` with ABAC policies.
122
+ */
123
+ export interface XCiteDBJwtClaims {
124
+ sub: string;
125
+ tenant_id: string;
126
+ groups: string[];
127
+ email?: string;
128
+ type?: string;
129
+ exp?: number;
130
+ iat?: number;
131
+ iss?: string;
132
+ jti?: string;
133
+ }
119
134
  export interface UserInfo {
120
135
  user_id: string;
121
136
  username: string;
package/llms-full.txt CHANGED
@@ -639,6 +639,7 @@ Policies may set **`conditions.expression`** (optional) and **`conditions.branch
639
639
  {
640
640
  "subject": {
641
641
  "id": "...",
642
+ "user_id": "...",
642
643
  "email": "...",
643
644
  "type": "app_user|developer|...",
644
645
  "role": "...",
@@ -653,7 +654,9 @@ Policies may set **`conditions.expression`** (optional) and **`conditions.branch
653
654
  }
654
655
  ```
655
656
 
656
- `subject.attr` mirrors app-user **custom attributes** from the user record. `resource.path` is the identifier split on `/` (non-empty segments only).
657
+ `subject.attr` mirrors app-user **custom attributes** from the user record. `resource.path` is the identifier split on `/` (non-empty segments only). **`subject.user_id` is the same string as `subject.id`** (app-user id); use either in expressions.
658
+
659
+ **`resources.identifiers` patterns** (`exact`, `match_start`, `match_end`): values are **canonicalized** the same way as API identifiers (leading `/` added when missing). Example: `match_start: "userdata/"` matches stored ids like `/userdata/<userId>/…`.
657
660
 
658
661
  ### Operators (predicates)
659
662
 
package/llms.txt CHANGED
@@ -24,6 +24,12 @@ These are the most common sources of confusion for developers and AI assistants:
24
24
 
25
25
  9. **Ephemeral test sessions (wet tests).** Call **`POST /api/v1/test/sessions`** with a normal API key or Bearer token to get a `session_token` (UUID). Send **`X-Test-Session: <token>`** on subsequent document/API calls to use an isolated, short-lived LMDB instead of production data. By default **developer** auth (API key / platform JWT) is bypassed, but **app-user** identity (`X-App-User-Token` or Bearer app-user JWT) is still recognized. Send **`X-Test-Auth: required`** to exercise full developer JWT/API-key auth and ABAC against the same test database. Do not send `X-Test-Session` on `/api/v1/test/*` management routes. Server limits apply (`test.session_ttl_seconds`, `test.max_sessions_per_key`, `test.max_test_db_size_bytes` in config). The test DB starts **empty** (no copy of production project config or keys).
26
26
 
27
+ ## Glossary: Project id, display name, and groups
28
+
29
+ - **Project display name** (human-readable, e.g. `invoices`): Shown in the console. The **`X-Project-Id`** header may match either this name **or** the internal project id (server convenience). Do **not** put the display name in JWT claims or in `project:<…>:role` group strings.
30
+ - **Project id / tenant_id** (internal, e.g. `t_…` or `default`): Canonical id in the app JWT **`tenant_id`** claim, in **`context.project_id`** (wire `tenant_id` in many app-auth bodies), and as the **middle segment** of **`project:<tenant_id>:admin|editor|viewer`**. Policies and app-user groups must use this value.
31
+ - **Organization `slug`** (workspace metadata): Org-level label only — not a substitute for project `tenant_id` when scoping app users or ABAC.
32
+
27
33
  ## Common Pitfalls
28
34
 
29
35
  1. **`baseUrl` must be origin-only (no `/api` or `/api/v1` path).** The SDK prepends `/api/v1/…` to every request. If `baseUrl` is `https://host/api/v1`, requests hit `/api/v1/api/v1/…` which typically returns **405 Not Allowed** from the reverse proxy. Use only the scheme + host + optional port: `https://host` or `http://localhost:8080`.
@@ -36,10 +42,49 @@ These are the most common sources of confusion for developers and AI assistants:
36
42
 
37
43
  5. **`context.project_id` (or `tenant_id`) is required for app-user self-registration.** `registerAppUser()` uses `mergeAppTenant(body)` to add `tenant_id` to the JSON body only when `context.project_id` or `context.tenant_id` is set. If both are omitted, the server cannot determine which project to register the user in. Always set `project_id` in the constructor `context` when calling `registerAppUser`, `loginAppUser`, and other public app-auth methods.
38
44
 
39
- 6. **Self-registration uses server-configured default groups.** `registerAppUser()` assigns groups from the server's `auth.app_users.default_groups` config, not from the client request. To assign specific groups, use the admin endpoint `createAppUser()` instead, or update groups after registration via `updateAppUserGroups()`.
45
+ 6. **Self-registration uses server-configured default groups.** `registerAppUser()` assigns groups from the server's `auth.app_users.default_groups` config, not from the client request. To set groups explicitly, use **`createAppUser`** with a `groups` array (e.g. `[XCiteDBClient.buildProjectGroup(projectId, 'editor')]`) or **`updateAppUserGroups`**. The server rejects `project:<x>:*` groups when `<x>` is not a known internal project id (avoids mistaking the display name for the tenant id).
40
46
 
41
47
  7. **Do not mock XciteDB in tests — use ephemeral test sessions instead.** Unlike most BaaS platforms, XciteDB has built-in support for isolated, throwaway database sessions specifically designed for wet integration tests. Mocking the client skips the actual storage, versioning, querying, and ABAC behavior, producing tests that don't catch real integration issues. Use `createTestSession()` / `test_session()` / `create_test_session()` (SDK helpers) or `POST /api/v1/test/sessions` directly to get a real, empty, isolated LMDB that is automatically scoped away from production and destroyed after the test. See "Test mode" below.
42
48
 
49
+ 8. **403 on writes with ABAC is often a JWT/group string mismatch.** Decode the app-user access token early: log **`tenant_id`**, **`groups`**, **`sub`**. The middle segment of every **`project:<x>:role`** group must equal **`tenant_id`** exactly. Document write denials may return JSON fields **`policy_id`** and **`hint`** alongside `"Forbidden"`.
50
+
51
+ 9. **`POST /api/v1/security/check` requires admin** (non-public key or app-user admin JWT). An **editor** API key gets **403** on this route — that means the *caller* cannot run the dry-run endpoint, **not** that a hypothetical subject lacks document access. Do not use this endpoint as the primary signal for “can my app user write?”.
52
+
53
+ 10. **`createAppUser` and `updateAppUserGroups` share the same gate:** admin or editor on a **secret** API key (or eligible app-user context), never a **public** key. If provisioning can create users with groups, it can patch groups later with the same credential.
54
+
55
+ 11. **Integration tests should assert token claims**, not only **`/app/auth/me`**. The profile endpoint can look fine while the JWT still carries viewer-style **`groups`**; for ABAC the token payload is authoritative. Use **`getTokenClaims()`** (JS SDK) or decode the JWT in your harness.
56
+
57
+ ## API key capability matrix (typical)
58
+
59
+ | Capability | API key `role` | Public key allowed? |
60
+ |------------|----------------|---------------------|
61
+ | Read documents (within ABAC) | viewer+ | Yes |
62
+ | Write/delete documents (within ABAC) | editor+ | No for sensitive flows; public keys are restricted |
63
+ | List/create/delete app users, **`PUT …/groups`** | admin **or** editor | No |
64
+ | Security policies, **`GET/PUT /security/config`**, **`POST /security/check`** | **admin** only | No |
65
+ | List/create/revoke project API keys (developer) | admin **or** editor | No |
66
+
67
+ ## App-user provisioning recipe (minimal)
68
+
69
+ Use the **internal** `projectId` (same as JWT `tenant_id`). **JS/TS:**
70
+
71
+ ```typescript
72
+ const projectId = '…'; // from listMyProjects / console, not display name
73
+ const admin = new XCiteDBClient({ baseUrl, apiKey: secretEditorOrAdminKey, context: { project_id: projectId } });
74
+ await admin.createAppUser('alice@example.com', strongPassword, 'Alice', [
75
+ XCiteDBClient.buildProjectGroup(projectId, 'editor'),
76
+ ]);
77
+ const app = new XCiteDBClient({ baseUrl, context: { project_id: projectId } });
78
+ const tokens = await app.loginAppUser('alice@example.com', strongPassword);
79
+ app.setAppUserTokens(tokens.access_token, tokens.refresh_token);
80
+ const claims = app.getTokenClaims();
81
+ console.assert(claims?.tenant_id === projectId);
82
+ console.assert(claims?.groups.includes(`project:${projectId}:editor`));
83
+ await app.writeJsonDocument('userdata/alice/profile', { ok: true });
84
+ ```
85
+
86
+ **Python:** `XCiteDBClient.build_project_group(project_id, "editor")` or module `build_project_group`. **C++:** `XCiteDBClient::build_project_group(project_id, "editor")`.
87
+
43
88
  ## Test mode (how to use)
44
89
 
45
90
  > **AI assistant instruction:** XciteDB has built-in ephemeral test session support — this capability is **not standard** in most BaaS platforms and is specifically designed to enable meaningful wet integration tests. When writing tests for code that uses XciteDB, **do not mock or stub the XciteDB client**. Instead, use the test session pattern below to run tests against a real, isolated, throwaway database. This produces far more reliable tests because real storage, versioning, querying, and access-control behavior is exercised.
@@ -153,6 +198,8 @@ interface XCiteDBClientOptions {
153
198
  - `version()` — Server version info
154
199
  - `platformLogin(email, password)` — Platform operator sign-in
155
200
  - `loginAppUser(email, password)` — App end-user sign-in
201
+ - `XCiteDBClient.buildProjectGroup(projectId, 'admin'|'editor'|'viewer')` — Static helper: canonical `project:<tenant_id>:<role>` string
202
+ - `getTokenClaims()` — Decode current `appUserAccessToken` or `accessToken` payload (no signature verification); use for ABAC debugging
156
203
  - `setContext(ctx)` — Update branch/date context
157
204
  - `setProjectId(id)` — Switch active project (platform console)
158
205
 
@@ -213,7 +260,7 @@ interface XCiteDBClientOptions {
213
260
  ### Advanced: policy expressions (ABAC)
214
261
 
215
262
  - **Actions** (use in `policy.actions`): `read`, `write`, `delete`, `list`, `meta:read`, `meta:write`, `unquery`.
216
- - **`conditions.expression`** uses the same predicate syntax as Unquery `?` filters. **Context:** `subject.id`, `subject.email`, `subject.role`, `subject.groups`, `subject.attr.*` (app-user JSON attributes), `resource.identifier`, `resource.path` (array of path segments), `env.branch`.
263
+ - **`conditions.expression`** uses the same predicate syntax as Unquery `?` filters. **Context:** `subject.id` and **`subject.user_id`** (same value for app users), `subject.email`, `subject.role`, `subject.groups`, `subject.attr.*` (app-user JSON attributes), `resource.identifier`, `resource.path` (array of path segments; indices follow non-empty `/` segments after API canonicalization, e.g. `/userdata/u1/x` → `[userdata,u1,x]`), `env.branch`. Policy **`match_start` / `match_end` / `exact`** strings are canonicalized like API identifiers (add leading `/` when omitted).
217
264
  - **Operators:** `=`, `!=`, `>=`, `<=`, `>`, `<`, `in`, `contains`, `starts_with`, `ends_with`, `&`, `|`, `!`, `+` (string concat), postfix `!` (exists).
218
265
  - **Examples:** `resource.path[0] = subject.attr.tenant_code` — tenant isolation; `subject.attr.level >= 5` — numeric attribute gate.
219
266
 
@@ -251,7 +298,7 @@ When calling `queryByIdentifier` or `queryDocuments`, the `flags` parameter cont
251
298
 
252
299
  ### Errors
253
300
 
254
- All API errors throw `XCiteDBError` with `.status` (HTTP code) and `.body` (parsed response). Common codes: `401` unauthenticated, `403` forbidden by policy, `404` not found, `409` conflict (lock), `422` validation, `423` project encrypted and locked, `429` rate limited.
301
+ All API errors throw `XCiteDBError` with `.status` (HTTP code) and `.body` (parsed response). Common codes: `401` unauthenticated, `403` forbidden by policy or RBAC, `404` not found, `409` conflict (lock), `422` validation, `423` project encrypted and locked, `429` rate limited. Many **ABAC** denials return `403` with `"message":"Forbidden"` plus optional **`policy_id`** and **`hint`** (check JWT `tenant_id` vs `project:` group middle segment).
255
302
 
256
303
  ## Python SDK (`xcitedb`)
257
304
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xcitedbs/client",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "XCiteDB BaaS client SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",