@omnibase/core-js 0.7.0 → 0.7.2

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.
@@ -0,0 +1,345 @@
1
+ // src/permissions/handler.ts
2
+ import { RelationshipApi, PermissionApi } from "@ory/client";
3
+
4
+ // src/permissions/roles.ts
5
+ var RolesHandler = class {
6
+ constructor(client) {
7
+ this.client = client;
8
+ }
9
+ /**
10
+ * Get available namespace definitions for UI
11
+ *
12
+ * Returns all namespaces and their available relations/permissions.
13
+ * Useful for building role configuration UIs.
14
+ *
15
+ * @returns List of namespace definitions
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const definitions = await omnibase.permissions.roles.getDefinitions();
20
+ *
21
+ * // Output: [{ namespace: 'Tenant', relations: ['invite_user', 'delete_tenant', ...] }]
22
+ * definitions.forEach(def => {
23
+ * console.log(`${def.namespace} supports: ${def.relations.join(', ')}`);
24
+ * });
25
+ * ```
26
+ */
27
+ async getDefinitions() {
28
+ const response = await this.client.fetch("/api/v1/roles/definitions", {
29
+ method: "GET"
30
+ });
31
+ const data = await response.json();
32
+ if (!response.ok || data.error) {
33
+ throw new Error(data.error || "Failed to fetch definitions");
34
+ }
35
+ return data.data.definitions;
36
+ }
37
+ /**
38
+ * List all roles for the current tenant
39
+ *
40
+ * Returns both system roles (defined in roles.config.json) and
41
+ * custom roles created via the API. System roles have `tenant_id = null`.
42
+ *
43
+ * @returns List of roles
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const roles = await omnibase.permissions.roles.list();
48
+ *
49
+ * const systemRoles = roles.filter(r => r.tenant_id === null);
50
+ * const customRoles = roles.filter(r => r.tenant_id !== null);
51
+ *
52
+ * console.log(`System roles: ${systemRoles.map(r => r.role_name).join(', ')}`);
53
+ * console.log(`Custom roles: ${customRoles.map(r => r.role_name).join(', ')}`);
54
+ * ```
55
+ */
56
+ async list() {
57
+ const response = await this.client.fetch("/api/v1/roles/roles", {
58
+ method: "GET"
59
+ });
60
+ const data = await response.json();
61
+ if (!response.ok || data.error) {
62
+ throw new Error(data.error || "Failed to list roles");
63
+ }
64
+ return data.data.roles;
65
+ }
66
+ /**
67
+ * Create a new custom role
68
+ *
69
+ * Creates a tenant-specific role with the specified permissions.
70
+ * Permissions use the format `namespace#relation` or `namespace:id#relation`.
71
+ *
72
+ * @param request - Role creation request
73
+ * @returns Created role
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const role = await omnibase.permissions.roles.create({
78
+ * role_name: 'billing_manager',
79
+ * permissions: [
80
+ * 'tenant#manage_billing',
81
+ * 'tenant#view_invoices',
82
+ * 'tenant#update_payment_methods'
83
+ * ]
84
+ * });
85
+ *
86
+ * console.log(`Created role: ${role.id}`);
87
+ * ```
88
+ *
89
+ * @example
90
+ * Resource-specific permissions:
91
+ * ```typescript
92
+ * const devRole = await omnibase.permissions.roles.create({
93
+ * role_name: 'project_developer',
94
+ * permissions: [
95
+ * 'project:proj_abc123#deploy',
96
+ * 'project:proj_abc123#view_logs',
97
+ * 'tenant#invite_user'
98
+ * ]
99
+ * });
100
+ * ```
101
+ */
102
+ async create(request) {
103
+ const response = await this.client.fetch("/api/v1/roles/roles", {
104
+ method: "POST",
105
+ headers: { "Content-Type": "application/json" },
106
+ body: JSON.stringify(request)
107
+ });
108
+ const data = await response.json();
109
+ if (!response.ok || data.error) {
110
+ throw new Error(data.error || "Failed to create role");
111
+ }
112
+ return data.data;
113
+ }
114
+ /**
115
+ * Update an existing role's permissions
116
+ *
117
+ * Updates the permissions for a role and automatically updates all
118
+ * Keto relationships for users assigned to this role. Old permissions
119
+ * are removed and new ones are created.
120
+ *
121
+ * @param roleId - ID of role to update
122
+ * @param request - Update request with new permissions
123
+ * @returns Updated role
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * const updatedRole = await omnibase.permissions.roles.update('role_123', {
128
+ * permissions: [
129
+ * 'tenant#manage_billing',
130
+ * 'tenant#view_invoices',
131
+ * 'tenant#manage_users' // Added new permission
132
+ * ]
133
+ * });
134
+ *
135
+ * console.log(`Updated role with ${updatedRole.permissions.length} permissions`);
136
+ * ```
137
+ */
138
+ async update(roleId, request) {
139
+ const response = await this.client.fetch(`/api/v1/roles/roles/${roleId}`, {
140
+ method: "PUT",
141
+ headers: { "Content-Type": "application/json" },
142
+ body: JSON.stringify(request)
143
+ });
144
+ const data = await response.json();
145
+ if (!response.ok || data.error) {
146
+ throw new Error(data.error || "Failed to update role");
147
+ }
148
+ return data.data;
149
+ }
150
+ /**
151
+ * Delete a role
152
+ *
153
+ * Deletes the role and automatically removes all Keto relationships
154
+ * for users assigned to this role. Cannot delete system roles.
155
+ *
156
+ * @param roleId - ID of role to delete
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * await omnibase.permissions.roles.delete('role_123');
161
+ * console.log('Role deleted successfully');
162
+ * ```
163
+ */
164
+ async delete(roleId) {
165
+ const response = await this.client.fetch(`/api/v1/roles/roles/${roleId}`, {
166
+ method: "DELETE"
167
+ });
168
+ const data = await response.json();
169
+ if (!response.ok || data.error) {
170
+ throw new Error(data.error || "Failed to delete role");
171
+ }
172
+ }
173
+ /**
174
+ * Assign a role to a user
175
+ *
176
+ * Assigns a role to a user and automatically creates all necessary
177
+ * Keto relationship tuples based on the role's permissions. The user
178
+ * immediately gains all permissions defined in the role.
179
+ *
180
+ * @param userId - ID of user to assign role to
181
+ * @param request - Assignment request with role ID
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * // Assign billing manager role to user
186
+ * await omnibase.permissions.roles.assign('user_123', {
187
+ * role_id: 'role_456'
188
+ * });
189
+ *
190
+ * // User now has all permissions from the role
191
+ * const canManageBilling = await omnibase.permissions.permissions.checkPermission(
192
+ * undefined,
193
+ * {
194
+ * namespace: 'Tenant',
195
+ * object: 'tenant_789',
196
+ * relation: 'manage_billing',
197
+ * subjectId: 'user_123'
198
+ * }
199
+ * );
200
+ * // canManageBilling.data.allowed === true
201
+ * ```
202
+ */
203
+ async assign(userId, request) {
204
+ const response = await this.client.fetch(
205
+ `/api/v1/roles/users/${userId}/roles`,
206
+ {
207
+ method: "POST",
208
+ headers: { "Content-Type": "application/json" },
209
+ body: JSON.stringify(request)
210
+ }
211
+ );
212
+ const data = await response.json();
213
+ if (!response.ok || data.error) {
214
+ throw new Error(data.error || "Failed to assign role");
215
+ }
216
+ }
217
+ };
218
+
219
+ // src/permissions/handler.ts
220
+ var PermissionsClient = class {
221
+ /**
222
+ * Ory Keto RelationshipApi for managing subject-object relationships
223
+ *
224
+ * Provides methods for creating, updating, and deleting relationships between
225
+ * subjects (users, groups) and objects (tenants, resources). This API handles
226
+ * write operations and is used to establish permission structures.
227
+ *
228
+ * Key methods:
229
+ * - `createRelationship()` - Creates a new relationship tuple
230
+ * - `deleteRelationships()` - Removes existing relationship tuples
231
+ * - `getRelationships()` - Queries existing relationships
232
+ * - `patchRelationships()` - Updates multiple relationships atomically
233
+ *
234
+ * @example
235
+ * ```typescript
236
+ * // Create a relationship
237
+ * await client.relationships.createRelationship(
238
+ * undefined,
239
+ * {
240
+ * namespace: 'Tenant',
241
+ * object: 'tenant_123',
242
+ * relation: 'members',
243
+ * subjectId: 'user_456'
244
+ * }
245
+ * );
246
+ * ```
247
+ *
248
+ * @since 1.0.0
249
+ * @group Relationships
250
+ */
251
+ relationships;
252
+ /**
253
+ * Ory Keto PermissionApi for checking permissions
254
+ *
255
+ * Provides methods for querying whether a subject has a specific permission
256
+ * on an object. This API handles read operations and is optimized for fast
257
+ * permission checks in your application logic.
258
+ *
259
+ * Key methods:
260
+ * - `checkPermission()` - Checks if a subject has permission on an object
261
+ * - `checkPermissionOrError()` - Same as above but throws error if denied
262
+ * - `expandPermissions()` - Expands relationships to show all granted permissions
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * // Check permission
267
+ * const result = await client.permissions.checkPermission(
268
+ * undefined,
269
+ * {
270
+ * namespace: 'Tenant',
271
+ * object: 'tenant_123',
272
+ * relation: 'view',
273
+ * subjectId: 'user_456'
274
+ * }
275
+ * );
276
+ *
277
+ * console.log('Has permission:', result.data.allowed);
278
+ * ```
279
+ *
280
+ * @since 1.0.0
281
+ * @group Permissions
282
+ */
283
+ permissions;
284
+ /**
285
+ * Handler for managing roles and role-based permissions
286
+ *
287
+ * Provides methods for creating custom roles, assigning permissions,
288
+ * and managing role assignments. Works alongside the Keto-based
289
+ * permissions system to provide dynamic RBAC capabilities.
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * // Create a custom role
294
+ * const role = await omnibase.permissions.roles.create({
295
+ * role_name: 'billing_manager',
296
+ * permissions: ['tenant#manage_billing', 'tenant#view_invoices']
297
+ * });
298
+ *
299
+ * // Assign role to user
300
+ * await omnibase.permissions.roles.assign('user_123', {
301
+ * role_id: role.id
302
+ * });
303
+ * ```
304
+ *
305
+ * @since 0.7.0
306
+ * @group Roles
307
+ */
308
+ roles;
309
+ /**
310
+ * Creates a new PermissionsClient instance
311
+ *
312
+ * Initializes the client with separate endpoints for read and write operations.
313
+ * The client automatically appends the appropriate Keto API paths to the base URL
314
+ * for optimal performance and security separation.
315
+ *
316
+ * @param apiBaseUrl - The base URL for your Omnibase API instance
317
+ * @param client - The main OmnibaseClient instance (for roles handler)
318
+ *
319
+ * @throws {Error} When the base URL is invalid or cannot be reached
320
+ *
321
+ * @example
322
+ * ```typescript
323
+ * const client = new PermissionsClient('https://api.example.com', omnibaseClient);
324
+ * ```
325
+ *
326
+ * @since 1.0.0
327
+ * @group Client
328
+ */
329
+ constructor(apiBaseUrl, client) {
330
+ this.relationships = new RelationshipApi(
331
+ void 0,
332
+ `${apiBaseUrl}/api/v1/permissions/write`
333
+ );
334
+ this.permissions = new PermissionApi(
335
+ void 0,
336
+ `${apiBaseUrl}/api/v1/permissions/read`
337
+ );
338
+ this.roles = new RolesHandler(client);
339
+ }
340
+ };
341
+
342
+ export {
343
+ RolesHandler,
344
+ PermissionsClient
345
+ };
@@ -70,7 +70,6 @@ var EventsClient = class {
70
70
  if (!WS) return;
71
71
  this.ws = new WS(this.url);
72
72
  this.ws.onopen = () => {
73
- console.log("\u2705 Connected to database events");
74
73
  this.reconnectDelay = 1e3;
75
74
  this.subscriptions.forEach((sub) => this.send(sub));
76
75
  };
@@ -80,17 +79,12 @@ var EventsClient = class {
80
79
  this.handleMessage(msg);
81
80
  };
82
81
  this.ws.onerror = (error) => {
83
- console.error("\u274C WebSocket error:", error);
82
+ console.error("WebSocket error:", error);
84
83
  };
85
84
  this.ws.onclose = () => {
86
85
  if (this.shouldReconnect) {
87
- console.log(
88
- `\u26A0\uFE0F Disconnected, reconnecting in ${this.reconnectDelay}ms`
89
- );
90
86
  setTimeout(() => this.connect(), this.reconnectDelay);
91
87
  this.reconnectDelay = Math.min(this.reconnectDelay * 2, 3e4);
92
- } else {
93
- console.log("Disconnected from database events");
94
88
  }
95
89
  };
96
90
  }
@@ -185,27 +179,6 @@ var EventsClient = class {
185
179
  if (listener) {
186
180
  listener(msg.data, msg);
187
181
  }
188
- } else if ("status" in msg) {
189
- if (msg.status === "subscribed") {
190
- console.log(
191
- "\u2705 Subscribed to",
192
- msg.table,
193
- msg.row_id ? `(row ${msg.row_id})` : "(all rows)"
194
- );
195
- } else if (msg.status === "unsubscribed") {
196
- console.log(
197
- "Unsubscribed from",
198
- msg.table,
199
- msg.row_id ? `(row ${msg.row_id})` : "(all rows)"
200
- );
201
- } else if (msg.status === "error") {
202
- console.error(
203
- "\u274C Subscription error:",
204
- msg.error,
205
- "for table:",
206
- msg.table
207
- );
208
- }
209
182
  }
210
183
  }
211
184
  /**
@@ -116,7 +116,7 @@ declare const createClient: <T = any>(url: string, anonKey: string, getCookie: (
116
116
  */
117
117
  interface SubscriptionOptions {
118
118
  /** Specific row ID to subscribe to (optional) */
119
- rowId?: number;
119
+ rowId?: string;
120
120
  /** Specific columns to filter updates (optional) */
121
121
  columns?: string[];
122
122
  /** Callback function triggered on data updates */
@@ -127,7 +127,7 @@ interface SubscriptionOptions {
127
127
  */
128
128
  interface Subscription {
129
129
  table: string;
130
- row_id?: number;
130
+ row_id?: string;
131
131
  columns?: string[];
132
132
  jwt: string;
133
133
  }
@@ -256,7 +256,7 @@ declare class EventsClient {
256
256
  * client.unsubscribe('users', 123);
257
257
  * ```
258
258
  */
259
- unsubscribe(table: string, rowId?: number): void;
259
+ unsubscribe(table: string, rowId?: string): void;
260
260
  /**
261
261
  * Send message to WebSocket server
262
262
  * @private
@@ -116,7 +116,7 @@ declare const createClient: <T = any>(url: string, anonKey: string, getCookie: (
116
116
  */
117
117
  interface SubscriptionOptions {
118
118
  /** Specific row ID to subscribe to (optional) */
119
- rowId?: number;
119
+ rowId?: string;
120
120
  /** Specific columns to filter updates (optional) */
121
121
  columns?: string[];
122
122
  /** Callback function triggered on data updates */
@@ -127,7 +127,7 @@ interface SubscriptionOptions {
127
127
  */
128
128
  interface Subscription {
129
129
  table: string;
130
- row_id?: number;
130
+ row_id?: string;
131
131
  columns?: string[];
132
132
  jwt: string;
133
133
  }
@@ -256,7 +256,7 @@ declare class EventsClient {
256
256
  * client.unsubscribe('users', 123);
257
257
  * ```
258
258
  */
259
- unsubscribe(table: string, rowId?: number): void;
259
+ unsubscribe(table: string, rowId?: string): void;
260
260
  /**
261
261
  * Send message to WebSocket server
262
262
  * @private
@@ -43,7 +43,6 @@ var EventsClient = class {
43
43
  if (!WS) return;
44
44
  this.ws = new WS(this.url);
45
45
  this.ws.onopen = () => {
46
- console.log("\u2705 Connected to database events");
47
46
  this.reconnectDelay = 1e3;
48
47
  this.subscriptions.forEach((sub) => this.send(sub));
49
48
  };
@@ -53,17 +52,12 @@ var EventsClient = class {
53
52
  this.handleMessage(msg);
54
53
  };
55
54
  this.ws.onerror = (error) => {
56
- console.error("\u274C WebSocket error:", error);
55
+ console.error("WebSocket error:", error);
57
56
  };
58
57
  this.ws.onclose = () => {
59
58
  if (this.shouldReconnect) {
60
- console.log(
61
- `\u26A0\uFE0F Disconnected, reconnecting in ${this.reconnectDelay}ms`
62
- );
63
59
  setTimeout(() => this.connect(), this.reconnectDelay);
64
60
  this.reconnectDelay = Math.min(this.reconnectDelay * 2, 3e4);
65
- } else {
66
- console.log("Disconnected from database events");
67
61
  }
68
62
  };
69
63
  }
@@ -158,27 +152,6 @@ var EventsClient = class {
158
152
  if (listener) {
159
153
  listener(msg.data, msg);
160
154
  }
161
- } else if ("status" in msg) {
162
- if (msg.status === "subscribed") {
163
- console.log(
164
- "\u2705 Subscribed to",
165
- msg.table,
166
- msg.row_id ? `(row ${msg.row_id})` : "(all rows)"
167
- );
168
- } else if (msg.status === "unsubscribed") {
169
- console.log(
170
- "Unsubscribed from",
171
- msg.table,
172
- msg.row_id ? `(row ${msg.row_id})` : "(all rows)"
173
- );
174
- } else if (msg.status === "error") {
175
- console.error(
176
- "\u274C Subscription error:",
177
- msg.error,
178
- "for table:",
179
- msg.table
180
- );
181
- }
182
155
  }
183
156
  }
184
157
  /**