@horussw/auth-core
v0.2.0
Published
Core contracts and engines for multi-tenant AuthN/AuthZ.
Readme
@horussw/auth-core
Framework-independent, multi-tenant authorization with exact permissions and attribute policies. Node >=20.
npm install @horussw/auth-coreimport { AuthorizationEngine, AttributePolicyEngine } from '@horussw/auth-core';
const engine = new AuthorizationEngine({
permissionProvider: {
async loadPermissions({ principal, tenantId }) {
// Look up active tenant membership and resolve role/direct grants in your database.
const permissions = await membershipRepository.permissions(principal.subjectId, tenantId);
return { subjectId: principal.subjectId, tenantId, roles: [], permissions };
},
},
resourceAttributeProvider: {
async getAttributes(type, id, { tenantId }) {
if (type !== 'invoice') return null;
// Return null if absent; returned attributes must include the actual tenantId.
return invoiceRepository.attributesByTenantAndId(tenantId, id);
},
},
policyEngine: new AttributePolicyEngine({
policies: {
draft: ({ resourceAttributes }) => resourceAttributes?.status === 'draft',
},
}),
});
const decision = await engine.authorize({
principal,
tenantId: principal.tenantId,
action: 'approve',
resourceType: 'invoice',
resourceId: '42',
policies: ['draft'],
});
if (!decision.allow) throw new Error('Forbidden');Every required permission must be present; absent requiredPermissions, the key is resourceType:action. Wildcards and role hierarchies are not inferred. All named policies must return exactly true; unknown policies deny. BasicPolicyEngine supports owner and sameTenant and rejects named policies.
Migration from 0.1
- The provider is authoritative; principal/JWT permissions are no longer merged.
- Tenant is required by default; subject and tenant must match the snapshot. Identified resources require trusted attributes with a matching tenant. Missing resources never fall back to supplied attributes.
- Resource providers receive a third argument
{ principal, tenantId, action }. Query storage by tenant and ID. - Cache keys are JSON tuples. Default TTL is 60s, capped at 300s, also bounded by
expiresAt. Zero avoids caching. Date objects must survive cache serialization. - After committed permission changes, call
engine.invalidatePermissions(subjectId, tenantId). Shared deployments require shared deletion; in-flight requests are not cancelled. Disable permission caching when immediate revocation is required. - In-memory caching is bounded to 10,000 entries by default. Audit sink failures deny; redact sensitive principal claims in your sink.
The application must filter lists and response fields, validate writable fields, and protect mutable ABAC decisions with transactions/version checks. Custom PolicyEngine implementations are trusted code responsible for their permission semantics. The engine retains snapshot and resource tenant invariants.
