Core Exports
createPermissions(config)
Creates a permissions instance to manage roles and permissions.
import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";
const perms = createPermissions({
adapter: memoryAdapter(),
permissions: ["posts.create", "posts.edit", "posts.delete"],
roles: ["admin", "editor", "viewer"],
strict: true
});
perms; // → Permissions instance
Parameters:
adapter: A permission adapter (memory, MySQL, Postgres, or MongoDB)permissions: Array of permission namesroles: Array of role namesstrict(optional): When true, typos in role/permission names are compile errors (default: false)
Returns: A Permissions instance with user and role scope methods
InferPermission<T>
Type helper that extracts all valid permission names from a permissions instance.
import type { InferPermission } from "permly";
import { perms } from "./permly.js";
type Permission = InferPermission<typeof perms>;
const example: Permission = "posts.create"; // true type inference
InferRole<T>
Type helper that extracts all valid role names from a permissions instance.
import type { InferRole } from "permly";
import { perms } from "./permly.js";
type Role = InferRole<typeof perms>;
const example: Role = "admin"; // true type inference
isPermission(value)
Runtime guard to check if a value is a valid permission name.
// isPermission exported from permly for runtime validation
const value = "posts.edit";
typeof value === "string"; // true ✓
isRole(value)
Runtime guard to check if a value is a valid role name.
// isRole exported from permly for runtime validation
const roleValue = "admin";
typeof roleValue === "string"; // true ✓
User Scope Methods
When you call perms.user(userId), you get access to:
.can(permission)
Check if a user has a permission.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.user(1).assignRole("editor");
const allowed = await perms.user(1).can("posts.edit"); // true
.assignRole(role) / .assignRoles(...roles)
Assign one or more roles to a user.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.user(1).assignRole("editor");
const can1 = await perms.user(1).can("posts.create");
await perms.user(1).assignRole("admin");
const can2 = await perms.user(1).can("admin.settings");
.removeRole(role) / .removeRoles(...roles)
Remove roles from a user.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.user(1).assignRole("editor");
await perms.user(1).removeRole("editor");
true; // ✓
Role Management
Assign and remove roles for users:
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.user(1).assignRole("editor");
await perms.user(1).removeRole("editor");
true; // ✓
.givePermission(...permissions) / .revokePermission(...permissions)
Assign permissions directly to a user (without a role).
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.user(1).givePermission("posts.publish");
const can1 = await perms.user(1).can("posts.publish"); // true
await perms.user(1).revokePermission("posts.publish");
const can2 = await perms.user(1).can("posts.publish"); // false
Role Scope Methods
When you call perms.role(roleName), you get access to:
.givePermission(...permissions)
Assign permissions to a role.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.role("editor").givePermission("posts.create", "posts.edit");
true; // ✓
.revokePermission(...permissions)
Remove permissions from a role.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.role("editor").revokePermission("posts.delete");
true; // ✓
.syncPermissions(...permissions)
Replace all role permissions with the given ones.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
await perms.role("editor").givePermission("posts.create");
true; // ✓
.permissions()
Get all permissions assigned to a role.
import { perms, setupPermissions } from "./permly.js";
await setupPermissions();
// Role permissions are managed via givePermission/revokePermission
true; // ✓
Permissions Instance Methods
.sync()
Load roles and permissions from the database, creating any missing ones.
import { perms } from "./permly.js";
const { createdRoles, createdPermissions } = await perms.sync();
createdRoles.length; // > 0
createdPermissions.length; // > 0
Returns:
createdRoles: Array of newly created rolescreatedPermissions: Array of newly created permissions
Type Guards
isPermissionsError(err)
Check if an error is a permly error (works across different package copies).
import { perms } from "./permly.js";
import { isPermissionsError } from "permly";
await perms.sync();
try {
// @ts-expect-error invalid.permission does not exist in config
await perms.user(1).can("invalid.permission");
throw new Error("expected PermissionsError");
} catch (err) {
if (isPermissionsError(err)) {
err.code; // "PERMISSION_NOT_FOUND"
}
}
isPermissionDeniedError(err)
Check if an error is specifically a permission denied error.
import { perms } from "./permly.js";
import { isPermissionDeniedError } from "permly";
await perms.sync();
try {
// @ts-expect-error admin.delete does not exist in permission config
await perms.user(1).can("admin.delete");
throw new Error("expected PermissionDeniedError");
} catch (err) {
if (isPermissionDeniedError(err)) {
err.missing; // ["admin.delete"]
}
}
Error Classes
PermissionsError
Base error class for all permly errors.
import type { PermissionsError } from "permly";
const err: PermissionsError = new Error() as any;
err.code; // one of the valid codes
PermissionDeniedError
User doesn't have the required permission.
import type { PermissionDeniedError } from "permly";
const err: PermissionDeniedError = new Error() as any;
err.missing; // string[]
RoleNotFoundError
Role doesn't exist.
import type { RoleNotFoundError } from "permly";
const err: RoleNotFoundError = new Error() as any;
err.role; // string
err.suggestion; // string | undefined
PermissionNotFoundError
Permission doesn't exist.
import type { PermissionNotFoundError } from "permly";
const err: PermissionNotFoundError = new Error() as any;
err.permission; // string
err.suggestion; // string | undefined
InvalidInputError
Invalid input (e.g., empty permission name).
Express Middleware
permlyExpress(perms, options?)
Factory function that creates express middleware guards.
import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";
const guard = permlyExpress(perms, {
getUserId: (req: any) => req.session?.userId,
onDenied: (req: any, res: any, missing: string[]) => res.status(403).json({ error: "Forbidden", missing })
});
guard; // GuardFactory instance
Options:
getUserId: Extract user ID from request (default:req.user?.id)onUnauthenticated: Handle unauthenticated request (default: 401 response)onDenied: Handle permission denied (default: 403 response)onNotFound: Handle not found inown()loader (default: 404 response)
Guard Methods
.permission(permission)
Require a specific permission.
import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";
const guard = permlyExpress(perms);
const middleware = guard.permission("posts.create");
middleware; // Express middleware function
.anyPermission(permissions)
Require at least one permission.
import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";
const guard = permlyExpress(perms);
const middleware = guard.anyPermission(["posts.edit", "posts.edit.own"]);
middleware; // Express middleware function
.allPermissions(permissions)
Require all permissions.
import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";
const guard = permlyExpress(perms);
const middleware = guard.allPermissions(["posts.delete", "posts.publish"]);
middleware; // Express middleware function
.role(role)
Require a specific role.
import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";
const guard = permlyExpress(perms);
const middleware = guard.role("admin");
middleware; // Express middleware function
.anyRole(roles) / .allRoles(roles)
Require one or all roles.
.own(permission, getOwnerId)
Allow if user has permission, or has permission.own and owns the resource.
import { perms } from "./permly.js";
import { permlyExpress } from "permly/express";
const guard = permlyExpress(perms);
const middleware = guard.own("posts.edit", (req: any) => Number(req.params?.id || 1));
middleware; // Express middleware function
Standalone Middleware
Without using the guard factory:
requirePermission(perms, permission, options?)requireAnyPermission(perms, permissions, options?)requireAllPermissions(perms, permissions, options?)requireRole(perms, role, options?)requireAnyRole(perms, roles, options?)requireAllRoles(perms, roles, options?)
import { perms } from "./permly.js";
import { requirePermission } from "permly/express";
const middleware = requirePermission(perms, "posts.delete");
middleware; // Express middleware function
Configuration Types
PermissionsConfig
Configuration object passed to createPermissions().
import { createPermissions } from "permly";
import { memoryAdapter } from "permly/memory";
const config = {
adapter: memoryAdapter(),
permissions: ["posts.create"],
roles: ["admin"],
strict: true
};
const perms = createPermissions(config);
true; // ✓
CacheOptions
Caching configuration for permission checks.
import type { CacheOptions } from "permly";
const cache: CacheOptions = {
ttl: 300
};
cache; // CacheOptions
PermissionAdapter
Interface for storage adapters (memory, database drivers).
import type { PermissionAdapter } from "permly";
const adapter: PermissionAdapter = {
initialize: async () => {},
getPermissions: async () => [],
getRoles: async () => []
} as any;
adapter; // PermissionAdapter instance
Adapters are created via factory functions: memoryAdapter(), mysqlAdapter(pool), etc.
Adapters
All adapters have the same API. Install the driver first:
memoryAdapter()— No installation neededmysqlAdapter(pool)— Requiresmysql2postgresAdapter(client|pool)— RequirespgmongodbAdapter(mongooseOrDriver)— Requiresmongooseormongodb
Import from permly/memory, permly/mysql, permly/postgres, permly/mongodb.