@amaster.ai/admin-sdk

中文文档
1.1.72发布于 2026/11/05MITTypeScriptESM + CJS零依赖近 30 天下载 1926

Admin SDK for Amaster platform — server-side user, role, permission and org management

原始使用文档
文档目录16 节
  1. Edge Function 快速示例(AI 参考)
  2. Installation
  3. Quick Start
  4. Environment Variables
  5. API Overview
  6. admin.auth — Permission checks (no user token required)
  7. admin.users — User CRUD
  8. admin.roles — Role management
  9. admin.permissions — Permission definitions and assignments
  10. admin.departments — Department and membership
  11. Deno / Edge Functions
  12. Identifiers: UID vs numeric ID
  13. Types (AI Reference)
  14. Error Handling
  15. License
  16. Prebind an existing user to WeCom

@amaster.ai/admin-sdk

Server-side Admin SDK for the Amaster platform. Manages users, roles, permissions, and departments via the internal API. Designed for Edge Functions (Deno) and Node.js backends — uses native fetch, no browser APIs.

Edge Function 快速示例(AI 参考)

在 AMaster edge-function 中,从 env 获取参数初始化 SDK:

import { AdminSDK } from "npm:@amaster.ai/admin-sdk";

export default async function (request: Request, env: Env): Promise<Response> {
  const admin = new AdminSDK({
    appId: env.appId,
    env: env.appEnv,
    serviceKey: env.vars["APP_SECRET"],
  });

  // 权限校验
  const { allow } = await admin.auth.checkPermission("user-uid", {
    resource: "page",
    action: "access",
  });
  if (!allow) return Response.json({ error: "Forbidden" }, { status: 403 });

  // 创建用户
  const user = await admin.users.create({
    email: "[email protected]",
    password: "Secure@123",
    displayName: "New User",
  });

  return Response.json({ user });
}

参数映射:env.appId → appId,env.appEnv → env,env.vars["APP_SECRET"] → serviceKey。baseURL 有默认值,可不传。

Installation

pnpm add @amaster.ai/admin-sdk
# or
npm install @amaster.ai/admin-sdk

Quick Start

import { AdminSDK } from "@amaster.ai/admin-sdk";

const admin = new AdminSDK({
  baseURL: process.env.RUNTIME_URL || "http://localhost:3000",
  appId: process.env.APP_ID!,
  env: process.env.ENV || "dev",
  serviceKey: process.env.SERVICE_KEY, // Required for internal API calls
});

// Check if a user can access a resource
const result = await admin.auth.checkPermission("user-uid-here", {
  resource: "page",
  action: "access",
  resourceId: "dashboard",
});
if (!result.allow) throw new Error("Forbidden");

// Functional permission and data scope are separate. For model data,
// append rowFilter to the JSONQL query before reading or mutating rows.
// `scope === "none"` is represented by an always-false rowFilter.
const runtimeRowConstraint = result.rowFilter?.filter;

// Create a user
const user = await admin.users.create({
  email: "[email protected]",
  password: "Secure@123",
  displayName: "New User",
});

// Assign a role to the user (use uid, not numeric id)
await admin.roles.assign(roleId, {
  assigneeType: "user",
  assigneeUid: user.uid,
});

Environment Variables

VariableDescriptionExample
RUNTIME_URLRuntime service base URLhttp://runtime:3000
APP_IDApplication ID (x-tenant-id)d9990247
ENVEnvironment (x-env)dev | prod
SERVICE_KEYService key for internal API auth(from Amaster console)

API Overview

admin.auth — Permission checks (no user token required)

MethodDescription
checkPermission(uid, { resource, action, resourceId? })Check if user has permission
getRules(uid)Get full ACL rules (roles + permissions) for a user
// Single permission check
const { allow, scope, resolved, rowFilter, roles, permissions } = await admin.auth.checkPermission(uid, {
  resource: "order",
  action: "read",
});

if (!allow) throw new Error("Forbidden");
// `own`, `dep`, `dep_and_sub`, `mixed`, and `none` all require the business
// data path to consume rowFilter. `none` contains an always-false condition.
const runtimeRowConstraint = rowFilter?.filter;

// Batch: fetch rules once, check locally
const rules = await admin.auth.getRules(uid);
const canExport = rules.permissions.some(
  (p) => p.resource === "report" && p.action === "export"
);

admin.users — User CRUD

MethodDescription
list(params?)List users (pagination, search)
get(uid)Get user by UID
create(params)Create user
update(uid, params)Update user
delete(uid)Delete user
const { list, total } = await admin.users.list({ query: "zhang", pageSize: 20 });
const user = await admin.users.get("abc-uid");
await admin.users.update(user.uid, { displayName: "New Name" });

admin.roles — Role management

MethodDescription
list()List all roles
get(id)Get role by ID
create(params)Create role
update(id, params)Update role
delete(id)Delete role (non-system only)
assign(roleId, params)Assign role to user/dept/team
unassign(roleId, params)Remove assignment
listAssignees(roleId)List assignees of a role
getUserRoles(uid)Get roles assigned to a user
// Prefer assigneeUid for users
await admin.roles.assign(roleId, {
  assigneeType: "user",
  assigneeUid: user.uid,
});

// For department/team/role, use assigneeId
await admin.roles.assign(roleId, {
  assigneeType: "department",
  assigneeId: 5,
});

const roles = await admin.roles.getUserRoles(user.uid);

admin.permissions — Permission definitions and assignments

MethodDescription
list()List all permissions
create(params)Create permission
update(id, params)Update permission
delete(id)Delete permission
listForRole(roleId)List permissions for a role
assignToRole(roleId, params)Assign permission to role
removeFromRole(roleId, permId)Remove permission from role
updateRolePermissionScope(...)Update role-permission scope
assignToUser(uid, params)Direct user permission (exception)
removeFromUser(uid, permId)Remove user permission
listForUser(uid)List user permission exceptions
updateUserPermissionScope(...)Update user permission scope
const perm = await admin.permissions.create({
  resource: "order",
  action: "export",
  name: "导出订单",
});

await admin.permissions.assignToRole(roleId, {
  permissionId: perm.id,
  scopeType: "dep",
});

// User-level override (bypasses role)
await admin.permissions.assignToUser(uid, {
  permissionId: perm.id,
  scopeType: "custom",
  scopeFilter: JSON.stringify({ id: [1, 2, 3] }),
});

admin.departments — Department and membership

MethodDescription
list()List all departments
get(id)Get department by ID
create(params)Create department
update(id, params)Update department
delete(id)Delete department
listUsers(id, includeChildren?)List department members
addUser(deptId, params)Add user to department (use userUid)
removeUser(deptId, userUid)Remove user from department
const dept = await admin.departments.create({ name: "技术部", parentId: 1 });
await admin.departments.addUser(dept.id, {
  userUid: user.uid,
  position: "工程师",
  isPrimary: true,
});
await admin.departments.removeUser(dept.id, user.uid);

Deno / Edge Functions

在 edge-function 中通过 npm: 导入,参数从 env 获取(见顶部「Edge Function 快速示例」)。

Identifiers: UID vs numeric ID

  • UID (string, e.g. "abc-123-def"): Primary user identifier. Use for users.get/update/delete, roles.assign (assigneeUid), departments.addUser/removeUser, auth.checkPermission, permissions.assignToUser.
  • Numeric ID (number): Database ID. Used for roles, permissions, departments, and role-assignee lookups. Prefer UID when the API supports it.

Types (AI Reference)

All types are exported from the package. Key ones:

TypeUse case
AdminSDKOptionsConstructor options
CheckPermissionParams, CheckPermissionResultauth.checkPermission
CreateUserParams, CreateUserResult, UserDetailUser CRUD
RoleAssignParams, RoleRole assignment (use assigneeUid for users)
AssignPermissionToRoleParams, AssignPermissionToUserParamsPermission assignment
AddDepartmentMemberParamsDepartment membership (use userUid)
import type { AdminSDKOptions, CreateUserParams, RoleAssignParams } from "@amaster.ai/admin-sdk";

Error Handling

import { AdminSDK, AdminSDKError } from "@amaster.ai/admin-sdk";

try {
  await admin.users.get("invalid-uid");
} catch (err) {
  if (err instanceof AdminSDKError) {
    console.error(err.status, err.message); // 404, "user not found"
  }
}

License

MIT

Prebind an existing user to WeCom

await admin.auth.bindUserOAuth(userUid, {
  provider: "wecom",
  providerUserId: "enterprise-member-userid",
});

Server-only: calls POST /api/internal/auth/users/{uid}/oauth-bindings with the environment-scoped Service Key. Edge Functions must authenticate their caller and authorize user management before calling it. Use a stable application UID, not a numeric database ID. Identical bindings are idempotent; conflicts return 409 and never move an identity. Missing/disabled users return 404. Only WeCom is supported. Use verified member IDs from the intended enterprise; this operation does not fetch WeCom contact information or prove membership. Deploy the matching Runtime endpoint before using the method.

版本与发布记录

@amaster.ai/admin-sdk 共发布 144 个版本,首次发布于 2026/02/24;过去 12 个月发布了 144 个版本。

版本发布日期距今
1.1.72latest2026/11/052 天前
1.1.712026/10/2514 天前
1.1.702026/10/081 个月前
1.1.692026/09/241 个月前
1.1.69-beta.0beta2026/09/231 个月前
1.1.682026/09/221 个月前

关于 @amaster.ai/admin-sdk 的常见问题

@amaster.ai/admin-sdk 是什么?

Admin SDK for Amaster platform — server-side user, role, permission and org management

如何安装 @amaster.ai/admin-sdk?

在项目目录运行 npm install @amaster.ai/admin-sdk,或使用 pnpm add / yarn add / bun add。

@amaster.ai/admin-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@amaster.ai/admin-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@amaster.ai/admin-sdk 可以商用吗?

@amaster.ai/admin-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@amaster.ai/admin-sdk 的下载量有多少?

根据 npm 官方下载统计,@amaster.ai/admin-sdk 在 2026/10/06 – 2026/11/04 这 30 天内被下载 1,926 次,日均约 64 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@amaster.ai/admin-sdk 还在维护吗?

最新版本 1.1.72 发布于 2026/11/05(2 天前);至今共发布 144 个版本,其中过去 12 个月发布了 144 个;首次发布于 2026/02/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。