@amaster.ai/admin-sdk 1.1.72 → 1.1.74

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/index.cjs CHANGED
@@ -1,5 +1,12 @@
1
1
  'use strict';
2
2
 
3
+ var rbac = require('@amaster.ai/auth-client/rbac');
4
+ var httpClient = require('@amaster.ai/http-client');
5
+ var entityClient = require('@amaster.ai/entity-client');
6
+ var tenantManagement = require('@amaster.ai/auth-client/tenant-management');
7
+
8
+ // src/admin-sdk.ts
9
+
3
10
  // src/error.ts
4
11
  var AdminSDKError = class extends Error {
5
12
  constructor(message, statusCode, response) {
@@ -11,7 +18,7 @@ var AdminSDKError = class extends Error {
11
18
  };
12
19
 
13
20
  // src/http.ts
14
- function createHttpClient(baseURL, commonHeaders) {
21
+ function createHttpClient(baseURL, commonHeaders, resolveHeaders) {
15
22
  const normalizedBase = baseURL.replace(/\/$/, "");
16
23
  return async function request(options) {
17
24
  const { method, path, body, query } = options;
@@ -26,14 +33,18 @@ function createHttpClient(baseURL, commonHeaders) {
26
33
  const qs = params.toString();
27
34
  if (qs) url += "?" + qs;
28
35
  }
36
+ const serializedBody = body !== void 0 ? JSON.stringify(body) : void 0;
29
37
  const headers = {
30
38
  "Content-Type": "application/json",
31
- ...commonHeaders
39
+ ...commonHeaders,
40
+ ...resolveHeaders ? await resolveHeaders() : {}
32
41
  };
33
42
  const res = await fetch(url, {
34
43
  method,
44
+ ...options.redirect ? { redirect: options.redirect } : {},
45
+ ...options.credentials ? { credentials: options.credentials } : {},
35
46
  headers,
36
- body: body !== void 0 ? JSON.stringify(body) : void 0
47
+ body: serializedBody
37
48
  });
38
49
  let json;
39
50
  try {
@@ -139,501 +150,6 @@ function createAuthModule(request) {
139
150
  };
140
151
  }
141
152
 
142
- // src/modules/departments.ts
143
- function createDepartmentsModule(request) {
144
- return {
145
- /**
146
- * List all departments (flat list).
147
- *
148
- * @example
149
- * ```typescript
150
- * const depts = await admin.departments.list();
151
- * const techDept = depts.find(d => d.name === '技术部');
152
- * ```
153
- */
154
- async list() {
155
- return request({
156
- method: "GET",
157
- path: "/api/internal/org/departments"
158
- });
159
- },
160
- /**
161
- * Get a single department by ID.
162
- *
163
- * @example
164
- * ```typescript
165
- * const dept = await admin.departments.get(1);
166
- * ```
167
- */
168
- async get(id) {
169
- return request({
170
- method: "GET",
171
- path: `/api/internal/org/departments/${id}`
172
- });
173
- },
174
- /**
175
- * Create a new department.
176
- *
177
- * @example
178
- * ```typescript
179
- * const dept = await admin.departments.create({
180
- * name: '测试组',
181
- * parentId: 1,
182
- * });
183
- * ```
184
- */
185
- async create(params) {
186
- return request({
187
- method: "POST",
188
- path: "/api/internal/org/departments",
189
- body: params
190
- });
191
- },
192
- /**
193
- * Update a department.
194
- *
195
- * @example
196
- * ```typescript
197
- * await admin.departments.update(3, { name: '质量保证组' });
198
- * ```
199
- */
200
- async update(id, params) {
201
- return request({
202
- method: "PUT",
203
- path: `/api/internal/org/departments/${id}`,
204
- body: params
205
- });
206
- },
207
- /**
208
- * Delete a department.
209
- * Note: departments with sub-departments or assigned users cannot be deleted directly.
210
- *
211
- * @example
212
- * ```typescript
213
- * await admin.departments.delete(3);
214
- * ```
215
- */
216
- async delete(id) {
217
- return request({
218
- method: "DELETE",
219
- path: `/api/internal/org/departments/${id}`
220
- });
221
- },
222
- /**
223
- * List members of a department.
224
- *
225
- * @param includeChildren - Whether to include members from sub-departments. Defaults to false.
226
- *
227
- * @example
228
- * ```typescript
229
- * const members = await admin.departments.listUsers(1);
230
- * const allMembers = await admin.departments.listUsers(1, true);
231
- * ```
232
- */
233
- async listUsers(id, includeChildren = false) {
234
- return request({
235
- method: "GET",
236
- path: `/api/internal/org/departments/${id}/users`,
237
- query: { include_children: includeChildren }
238
- });
239
- },
240
- /**
241
- * Add a user to a department.
242
- *
243
- * @example
244
- * ```typescript
245
- * await admin.departments.addUser(deptId, {
246
- * userUid: user.uid,
247
- * isPrimary: true,
248
- * position: '高级工程师',
249
- * });
250
- * ```
251
- */
252
- async addUser(deptId, params) {
253
- return request({
254
- method: "POST",
255
- path: `/api/internal/org/departments/${deptId}/users`,
256
- body: params
257
- });
258
- },
259
- /**
260
- * Remove a user from a department.
261
- *
262
- * @example
263
- * ```typescript
264
- * await admin.departments.removeUser(deptId, user.uid);
265
- * ```
266
- */
267
- async removeUser(deptId, userUid) {
268
- return request({
269
- method: "DELETE",
270
- path: `/api/internal/org/departments/${deptId}/users/${userUid}`
271
- });
272
- }
273
- };
274
- }
275
-
276
- // src/modules/permissions.ts
277
- function createPermissionsModule(request) {
278
- return {
279
- /**
280
- * List all defined permissions.
281
- *
282
- * @example
283
- * ```typescript
284
- * const perms = await admin.permissions.list();
285
- * const orderRead = perms.find(p => p.resource === 'order' && p.action === 'read');
286
- * ```
287
- */
288
- async list() {
289
- return request({
290
- method: "GET",
291
- path: "/api/internal/rbac/permissions"
292
- });
293
- },
294
- /**
295
- * Create a new permission definition.
296
- *
297
- * @example
298
- * ```typescript
299
- * const perm = await admin.permissions.create({
300
- * resource: 'order',
301
- * action: 'export',
302
- * name: '导出订单',
303
- * });
304
- * ```
305
- */
306
- async create(params) {
307
- return request({
308
- method: "POST",
309
- path: "/api/internal/rbac/permissions",
310
- body: params
311
- });
312
- },
313
- /**
314
- * Update a permission definition.
315
- *
316
- * @example
317
- * ```typescript
318
- * await admin.permissions.update(10, { name: '导出报表' });
319
- * ```
320
- */
321
- async update(id, params) {
322
- return request({
323
- method: "PUT",
324
- path: `/api/internal/rbac/permissions/${id}`,
325
- body: params
326
- });
327
- },
328
- /**
329
- * Delete a permission definition.
330
- *
331
- * @example
332
- * ```typescript
333
- * await admin.permissions.delete(10);
334
- * ```
335
- */
336
- async delete(id) {
337
- return request({
338
- method: "DELETE",
339
- path: `/api/internal/rbac/permissions/${id}`
340
- });
341
- },
342
- /**
343
- * List all permissions assigned to a role.
344
- *
345
- * @example
346
- * ```typescript
347
- * const perms = await admin.permissions.listForRole(roleId);
348
- * ```
349
- */
350
- async listForRole(roleId) {
351
- return request({
352
- method: "GET",
353
- path: `/api/internal/rbac/roles/${roleId}/permissions`
354
- });
355
- },
356
- /**
357
- * Assign a permission to a role with a data scope.
358
- *
359
- * @example
360
- * ```typescript
361
- * // Department-scoped permission
362
- * await admin.permissions.assignToRole(roleId, {
363
- * permissionId: 10,
364
- * scopeType: 'dep',
365
- * });
366
- *
367
- * // Custom whitelist scope
368
- * await admin.permissions.assignToRole(roleId, {
369
- * permissionId: 20,
370
- * scopeType: 'custom',
371
- * scopeFilter: JSON.stringify({ id: [1, 2, 3] }),
372
- * });
373
- * ```
374
- */
375
- async assignToRole(roleId, params) {
376
- return request({
377
- method: "POST",
378
- path: `/api/internal/rbac/roles/${roleId}/permissions`,
379
- body: params
380
- });
381
- },
382
- /**
383
- * Remove a permission from a role.
384
- *
385
- * @example
386
- * ```typescript
387
- * await admin.permissions.removeFromRole(roleId, permId);
388
- * ```
389
- */
390
- async removeFromRole(roleId, permId) {
391
- return request({
392
- method: "DELETE",
393
- path: `/api/internal/rbac/roles/${roleId}/permissions/${permId}`
394
- });
395
- },
396
- /**
397
- * Update the data scope of a role–permission assignment.
398
- *
399
- * @example
400
- * ```typescript
401
- * await admin.permissions.updateRolePermissionScope(roleId, permId, {
402
- * scopeType: 'all',
403
- * });
404
- * ```
405
- */
406
- async updateRolePermissionScope(roleId, permId, params) {
407
- return request({
408
- method: "PUT",
409
- path: `/api/internal/rbac/roles/${roleId}/permissions/${permId}`,
410
- body: params
411
- });
412
- },
413
- /**
414
- * Assign a direct (user-level) permission exception to a user.
415
- *
416
- * This bypasses role-based assignment and gives the user a direct
417
- * data-scope override for the specified permission.
418
- *
419
- * @example
420
- * ```typescript
421
- * await admin.permissions.assignToUser('u-123456', {
422
- * permissionId: 10,
423
- * scopeType: 'dep',
424
- * });
425
- * ```
426
- */
427
- async assignToUser(uid, params) {
428
- return request({
429
- method: "POST",
430
- path: `/api/internal/rbac/users/${uid}/permissions`,
431
- body: params
432
- });
433
- },
434
- /**
435
- * Remove a direct permission exception from a user.
436
- *
437
- * @example
438
- * ```typescript
439
- * await admin.permissions.removeFromUser('u-123456', permId);
440
- * ```
441
- */
442
- async removeFromUser(uid, permId) {
443
- return request({
444
- method: "DELETE",
445
- path: `/api/internal/rbac/users/${uid}/permissions/${permId}`
446
- });
447
- },
448
- /**
449
- * List permission exceptions for a specific user.
450
- *
451
- * @example
452
- * ```typescript
453
- * const exceptions = await admin.permissions.listForUser('u-123456');
454
- * ```
455
- */
456
- async listForUser(uid) {
457
- return request({
458
- method: "GET",
459
- path: `/api/internal/rbac/users/${uid}/permissions`
460
- });
461
- },
462
- /**
463
- * Update the data scope of a user-level permission exception.
464
- *
465
- * @example
466
- * ```typescript
467
- * await admin.permissions.updateUserPermissionScope('u-123456', permId, {
468
- * scopeType: 'custom',
469
- * scopeFilter: JSON.stringify({ id: [10, 20] }),
470
- * });
471
- * ```
472
- */
473
- async updateUserPermissionScope(uid, permId, params) {
474
- return request({
475
- method: "PUT",
476
- path: `/api/internal/rbac/users/${uid}/permissions/${permId}`,
477
- body: params
478
- });
479
- }
480
- };
481
- }
482
-
483
- // src/modules/roles.ts
484
- function createRolesModule(request) {
485
- return {
486
- /**
487
- * List all roles.
488
- *
489
- * @example
490
- * ```typescript
491
- * const roles = await admin.roles.list();
492
- * const managerRole = roles.find(r => r.code === 'manager');
493
- * ```
494
- */
495
- async list() {
496
- return request({
497
- method: "GET",
498
- path: "/api/internal/rbac/roles"
499
- });
500
- },
501
- /**
502
- * Get a role by its numeric ID.
503
- *
504
- * @example
505
- * ```typescript
506
- * const role = await admin.roles.get(1);
507
- * ```
508
- */
509
- async get(id) {
510
- return request({
511
- method: "GET",
512
- path: `/api/internal/rbac/roles/${id}`
513
- });
514
- },
515
- /**
516
- * Create a new role.
517
- *
518
- * @example
519
- * ```typescript
520
- * const role = await admin.roles.create({
521
- * code: 'editor',
522
- * displayName: '编辑',
523
- * description: '负责内容编辑',
524
- * });
525
- * ```
526
- */
527
- async create(params) {
528
- return request({
529
- method: "POST",
530
- path: "/api/internal/rbac/roles",
531
- body: params
532
- });
533
- },
534
- /**
535
- * Update a role.
536
- * Note: system roles (isSystem=true) cannot be modified.
537
- *
538
- * @example
539
- * ```typescript
540
- * await admin.roles.update(3, { displayName: '高级编辑' });
541
- * ```
542
- */
543
- async update(id, params) {
544
- return request({
545
- method: "PUT",
546
- path: `/api/internal/rbac/roles/${id}`,
547
- body: params
548
- });
549
- },
550
- /**
551
- * Delete a role.
552
- * Note: system roles cannot be deleted.
553
- *
554
- * @example
555
- * ```typescript
556
- * await admin.roles.delete(3);
557
- * ```
558
- */
559
- async delete(id) {
560
- return request({
561
- method: "DELETE",
562
- path: `/api/internal/rbac/roles/${id}`
563
- });
564
- },
565
- /**
566
- * Assign a role to a user, department, team, or another role.
567
- * For users, prefer assigneeUid (string). For department/team/role, use assigneeId (number).
568
- *
569
- * @example
570
- * ```typescript
571
- * // Assign to a user (preferred: use uid)
572
- * await admin.roles.assign(roleId, { assigneeType: 'user', assigneeUid: user.uid });
573
- *
574
- * // Assign to an entire department
575
- * await admin.roles.assign(roleId, { assigneeType: 'department', assigneeId: 5 });
576
- * ```
577
- */
578
- async assign(roleId, params) {
579
- return request({
580
- method: "POST",
581
- path: `/api/internal/rbac/roles/${roleId}/assign`,
582
- body: params
583
- });
584
- },
585
- /**
586
- * Remove a role assignment.
587
- * For users, prefer assigneeUid. For department/team/role, use assigneeId.
588
- *
589
- * @example
590
- * ```typescript
591
- * await admin.roles.unassign(roleId, { assigneeType: 'user', assigneeUid: user.uid });
592
- * ```
593
- */
594
- async unassign(roleId, params) {
595
- return request({
596
- method: "POST",
597
- path: `/api/internal/rbac/roles/${roleId}/unassign`,
598
- body: params
599
- });
600
- },
601
- /**
602
- * List all assignees (users, departments, etc.) for a role.
603
- *
604
- * @example
605
- * ```typescript
606
- * const assignees = await admin.roles.listAssignees(roleId);
607
- * const users = assignees.filter(a => a.assigneeType === 'user');
608
- * ```
609
- */
610
- async listAssignees(roleId) {
611
- return request({
612
- method: "GET",
613
- path: `/api/internal/rbac/roles/${roleId}/assignees`
614
- });
615
- },
616
- /**
617
- * Get all roles assigned to a user (by UID).
618
- *
619
- * Useful in Edge Functions to check what roles a user currently holds
620
- * without making a full ACL check.
621
- *
622
- * @example
623
- * ```typescript
624
- * const roles = await admin.roles.getUserRoles('u-123456');
625
- * if (roles.some(r => r.code === 'admin')) { ... }
626
- * ```
627
- */
628
- async getUserRoles(uid) {
629
- return request({
630
- method: "GET",
631
- path: `/api/internal/rbac/users/${uid}/roles`
632
- });
633
- }
634
- };
635
- }
636
-
637
153
  // src/modules/users.ts
638
154
  function createUsersModule(request) {
639
155
  return {
@@ -730,11 +246,177 @@ function createUsersModule(request) {
730
246
  }
731
247
  };
732
248
  }
249
+ function createApplicationContext(options) {
250
+ const initial = { appId: options.appId ?? "context", env: options.env ?? "dev" };
251
+ if (!options.appId && !options.baseURL)
252
+ throw new AdminSDKError("An application domain or appId is required", 400);
253
+ let pending;
254
+ return {
255
+ initial,
256
+ resolve() {
257
+ if (options.appId && options.baseURL === void 0) return Promise.resolve(initial);
258
+ if (pending) return pending;
259
+ pending = (async () => {
260
+ const headers = { "Cache-Control": "no-cache" };
261
+ const controller = new AbortController();
262
+ const timeout = setTimeout(() => controller.abort(), 1e4);
263
+ try {
264
+ const response = await fetch(options.baseURL.replace(/\/$/, "") + "/api/auth/context", {
265
+ method: "GET",
266
+ headers,
267
+ credentials: "omit",
268
+ redirect: "error",
269
+ signal: controller.signal
270
+ });
271
+ if (!response.ok)
272
+ throw new AdminSDKError("Cannot verify application context", response.status);
273
+ const text = await response.text();
274
+ if (text.length > 16384)
275
+ throw new AdminSDKError("Cannot verify application context", 503);
276
+ const envelope = JSON.parse(text);
277
+ const value = envelope?.statusCode === 200 ? envelope.data : null;
278
+ if (value?.protocolVersion !== "1" || typeof value.applicationCode !== "string" || typeof value.environment !== "string" || typeof value.tenancyEnabled !== "boolean" || options.appId !== void 0 && value.applicationCode !== options.appId) {
279
+ throw new AdminSDKError("Cannot verify application context", 503);
280
+ }
281
+ const scope = new httpClient.RequestScopeController({
282
+ applicationCode: value.applicationCode,
283
+ environment: value.environment,
284
+ storage: null
285
+ });
286
+ if (scope.environment !== value.environment)
287
+ throw new AdminSDKError("Cannot verify application context", 503);
288
+ return { appId: scope.applicationCode, env: scope.environment };
289
+ } catch (error) {
290
+ if (error instanceof AdminSDKError) throw error;
291
+ throw new AdminSDKError("Cannot verify application context", 503);
292
+ } finally {
293
+ clearTimeout(timeout);
294
+ }
295
+ })();
296
+ pending.catch(() => {
297
+ pending = void 0;
298
+ });
299
+ return pending;
300
+ }
301
+ };
302
+ }
303
+ function deferOperations(template, resolve) {
304
+ let actual;
305
+ return Object.fromEntries(
306
+ Object.keys(template).map((name) => {
307
+ return [
308
+ name,
309
+ async (...args) => {
310
+ const captured = JSON.parse(JSON.stringify(args));
311
+ actual ?? (actual = resolve());
312
+ let module;
313
+ try {
314
+ module = await actual;
315
+ } catch {
316
+ actual = void 0;
317
+ return {
318
+ data: null,
319
+ status: 503,
320
+ error: {
321
+ status: 503,
322
+ code: "dependency_unverifiable",
323
+ message: "Cannot verify application context"
324
+ }
325
+ };
326
+ }
327
+ const operation = module[name];
328
+ return operation(...captured);
329
+ }
330
+ ];
331
+ })
332
+ );
333
+ }
334
+ function createApplicationTenantAccess(baseURL, appTenantId, serviceKey, resolve, initial) {
335
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(appTenantId)) throw new AdminSDKError("Invalid tenant identifier", 400);
336
+ if (!serviceKey || /[\r\n\0]/.test(serviceKey)) throw new AdminSDKError("An application service key is required", 401);
337
+ const applicationKey = serviceKey;
338
+ const headers = { "X-Service-Key": applicationKey };
339
+ const management = createHttpClient(baseURL, headers, async () => {
340
+ const context = await resolve();
341
+ return { "x-tenant-id": context.appId, "x-env": context.env, "x-app-tenant-id": appTenantId };
342
+ });
343
+ const changes = { sequence: 0 };
344
+ const request = async (options) => {
345
+ const write = options.method !== "GET";
346
+ if (write) changes.sequence++;
347
+ try {
348
+ return await management({ ...options, credentials: "omit", redirect: "error" });
349
+ } finally {
350
+ if (write) changes.sequence++;
351
+ }
352
+ };
353
+ function makeScope(context) {
354
+ const scope = new httpClient.RequestScopeController({ applicationCode: context.appId, environment: context.env, storage: null });
355
+ scope.setSubject({ type: "service", id: "legacy-application-administrator" });
356
+ scope.selectTenant(appTenantId);
357
+ return scope;
358
+ }
359
+ let controls;
360
+ let pending;
361
+ function connect() {
362
+ return pending ?? (pending = resolve().then((context) => {
363
+ const scope = makeScope(context);
364
+ const http = httpClient.createHttpClient({
365
+ baseURL,
366
+ requestScope: scope,
367
+ logErrors: false,
368
+ adapter: httpClient.createFetchAdapter({ onRequest: ({ init }) => {
369
+ const authenticated = new Headers(init.headers);
370
+ authenticated.delete("Authorization");
371
+ authenticated.set("X-Service-Key", applicationKey);
372
+ return { init: { ...init, headers: authenticated, credentials: "omit", redirect: "error" } };
373
+ } })
374
+ });
375
+ controls = tenantManagement.createTenancyManagement(scope, http, changes);
376
+ return http;
377
+ }));
378
+ }
379
+ const entity = {
380
+ async request(config) {
381
+ const captured = { ...config, data: config.data === void 0 ? void 0 : JSON.stringify(config.data) };
382
+ const operation = connect();
383
+ try {
384
+ return await (await operation).request(captured);
385
+ } catch (error) {
386
+ if (pending === operation) pending = void 0;
387
+ const status = error instanceof AdminSDKError ? error.statusCode : 503;
388
+ return { data: null, status, error: { status, code: "dependency_unverifiable", message: "Cannot verify application context" } };
389
+ }
390
+ }
391
+ };
392
+ const managementControls = deferOperations(tenantManagement.createTenancyManagement(makeScope(initial), entity, changes), async () => {
393
+ connect();
394
+ try {
395
+ await pending;
396
+ } catch (error) {
397
+ pending = void 0;
398
+ throw error;
399
+ }
400
+ return controls;
401
+ });
402
+ return {
403
+ ...managementControls,
404
+ auth: createAuthModule(request),
405
+ users: createUsersModule(request),
406
+ roles: rbac.createRolesModule(request),
407
+ permissions: rbac.createPermissionsModule(request),
408
+ departments: rbac.createDepartmentsModule(request),
409
+ entity: entityClient.createEntityClient(entity, { preserveIdentityStrings: true })
410
+ };
411
+ }
733
412
 
734
413
  // src/admin-sdk.ts
735
414
  var AdminSDK = class {
736
415
  constructor(options) {
737
- const { baseURL = "http://runtime:3000", appId, env = "dev", serviceKey } = options;
416
+ const { baseURL = "http://runtime:3000", serviceKey } = options;
417
+ const context = createApplicationContext(options);
418
+ const { appId, env } = context.initial;
419
+ const discover = options.baseURL !== void 0;
738
420
  const headers = {
739
421
  "x-tenant-id": appId,
740
422
  "x-env": env
@@ -743,12 +425,22 @@ var AdminSDK = class {
743
425
  headers["X-Service-Key"] = serviceKey;
744
426
  headers["X-Bypass-Auth"] = "true";
745
427
  }
746
- const request = createHttpClient(baseURL, headers);
428
+ const request = createHttpClient(
429
+ baseURL,
430
+ headers,
431
+ discover ? async () => {
432
+ const scope = await context.resolve();
433
+ return { "x-tenant-id": scope.appId, "x-env": scope.env };
434
+ } : void 0
435
+ );
436
+ this.tenancy = {
437
+ forTenant: (appTenantId) => createApplicationTenantAccess(baseURL, appTenantId, serviceKey, () => context.resolve(), context.initial)
438
+ };
747
439
  this.auth = createAuthModule(request);
748
440
  this.users = createUsersModule(request);
749
- this.roles = createRolesModule(request);
750
- this.permissions = createPermissionsModule(request);
751
- this.departments = createDepartmentsModule(request);
441
+ this.roles = rbac.createRolesModule(request);
442
+ this.permissions = rbac.createPermissionsModule(request);
443
+ this.departments = rbac.createDepartmentsModule(request);
752
444
  }
753
445
  };
754
446