Scan your whole stack
Are you using @nathapp/nestjs-account?
Find out what’s in your code.
Scan your apps free in minutes (opens in a new tab)Latest version: v1.6.0
@nathapp/nestjs-account was last scanned on 28 Nov 2026 at version 1.6.0. Risk score 0 of 100. No malicious behavior was detected.
| Version | Published | Status |
|---|---|---|
| 1.6.0 LATEST | 28 Nov 2026 | No rules fired |
| 1.5.0 | 22 Nov 2026 | No rules fired |
| 1.4.0 | 19 Nov 2026 | No rules fired |
| 1.3.3 | 18 Nov 2026 | Not shown |
| 1.3.2 | 16 Nov 2026 | Not shown |
Findings for v1.6.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.
The score describes 1.6.0; other versions have their own rules, not their own score.
The publisher’s own README, as collected from the registry.
Accounts, memberships, roles, permissions and invitations for multi-tenant NestJS
applications. Repository interfaces are ORM-agnostic; @nathapp/nestjs-account-prisma
ships the Prisma implementations.
@nathapp/nestjs-tenant.ownerId.(accountId, userId, tenantId) joins a user to an account. Roles are
granted to the membership, so a role always means "this role in this account".Tenant T1
├── Account "Smith" Alice = owner, Bob = member
└── Account "Jones" Carol = owner, Bob = admin
RolesGuard reads @Roles(...) metadata and asks your ROLES_CONTEXT_RESOLVER who the
user is and which account the route is about:
import type { ExecutionContext } from '@nestjs/common';
import type { IRolesContextResolver, RolesContext } from '@nathapp/nestjs-account';
export class RequestRolesContextResolver implements IRolesContextResolver {
resolve(context: ExecutionContext): RolesContext | null {
const req = context.switchToHttp().getRequest();
const userId = req.__session?.userId;
const tenantId = req.__tenant?.id;
if (!userId || !tenantId) return null; // 401
return { userId, tenantId, accountId: req.params?.accountId };
}
}
AccountModule.register({ rolesContextResolver: RequestRolesContextResolver });
AccountModule provides ROLES_CONTEXT_RESOLVER but does not export it: bind it again in
every module whose controllers use RolesGuard.
How the roles are found:
| Resolver returns | roleScope |
Roles used |
|---|---|---|
null |
any | none, RolesGuard answers 401 |
{ userId, tenantId, accountId } |
any | the user's membership in that account only |
{ userId, tenantId } (no accountId) |
'account' (default) |
none, 403, one warning logged |
{ userId, tenantId } (no accountId) |
'tenant' |
union of the user's roles across the tenant's accounts |
An account role only counts when the membership is ACTIVE, the account is ACTIVE and
belongs to the request tenant. Roles of a SUSPENDED or CLOSED (soft-deleted) account
never count, in either scope.
roleScopeAccountModule.register({ rolesContextResolver, roleScope: 'tenant' });
'account' (default): a role check must name the account. Use it whenever one tenant can
hold several accounts with different owners, or a member of one account could pass checks
meant for another.'tenant': a check without an account id uses the tenant-wide union. Only safe when each
tenant has exactly one account that carries these roles (for example a single staff
account per tenant).Any other value is treated as 'account'. With registerAsync, return roleScope from
useFactory.
IMembershipService.getUserRoles(userId, tenantId, accountId?) and
getUserPermissions(userId, tenantId, accountId?) take the same optional account id. Without
it they return the tenant-wide union, so pass the account whenever the question is about one.
Permissions are attached to roles. Their conditions are templated with ${userId},
${tenantId} and, for account checks, ${accountId}:
{ "action": "update", "subject": "Project", "conditions": { "accountId": "${accountId}" } }
@RequiredPermission routesBind nestjs-auth's PermissionProvider to AccountPermissionProvider. AccountModule
provides and exports it but does not bind the token, so an application's own binding is never
overridden:
import { PermissionProvider } from '@nathapp/nestjs-auth';
import { AccountPermissionProvider } from '@nathapp/nestjs-account';
@Module({
providers: [{ provide: PermissionProvider, useExisting: AccountPermissionProvider }],
exports: [PermissionProvider],
})
export class AuthzModule {}
@UseGuards(SessionGuard, PermissionAuthGuard)
@RequiredPermission(['update', 'Project']) // one [action, subject] tuple per argument
@Patch('accounts/:accountId/projects/:id')
update() { /* ... */ }
AccountPermissionProvider asks the same ROLES_CONTEXT_RESOLVER for the account and follows
the roleScope table above. The user is the request principal's id and the tenant comes from
the tenant context; resolve both from the same authenticated user your resolver uses. String
permissions are checked against the principal's authorities as before.
AuthorizationServiceconstructor(private readonly authz: AuthorizationService) {}
async rename(accountId: string, project: Project) {
await this.authz.forAccount(accountId).ensureCan('update', 'Project', project);
}
forAccount(accountId) returns an AccountAuthorization (can, ensureCan). The plain
can / ensureCan have no account and follow roleScope: under the default they grant
nothing.
AuthorizationService is a singleton. It reads the principal from a per-request context the
account module opens for every route (AuthorizationRequestContextMiddleware, on Express and
Fastify), so a provider that injects it is no longer request-scoped. Get it with
moduleRef.get(AuthorizationService); its constructor is (abilityFactory). Within one request
an ability is built once. Outside an HTTP request (a queue processor, a test without the
middleware) it throws 401 UNAUTHORIZED, as before; tests can wrap a call in
AuthorizationRequestContext.run({ user }, () => ...).
Permission sets are cached per tenant, user and account for 30 s by default:
AccountModule.register({
authzCache: { ttlMs: 30_000 }, // default; false turns the cache off
authzCacheStore: MyRedisAuthzStore, // optional IAuthorizationCacheStore (AUTHORIZATION_CACHE_STORE)
});
get(key) / set(key, permissions, ttlMs); a get that throws or
returns a non-array is treated as a miss and the permissions are loaded from the database.addMember, removeMember, updateStatus,
assignRoles, removeRoles; role delete, assignPermissions, removePermissions; account
create, update, updateStatus, softDelete; invitation accept; ownership transfer
completion; registration. Permission update and delete evict every tenant.authzCache: false where a revocation must apply at once.inviteeEmailResolver and authzCacheStore are module-definition options: under
registerAsync put them on the outer options, not in the factory result.accept(token, userId) requires one of the user's verified email addresses to equal the
invitation email (trimmed, case-insensitive). The addresses come from the
INVITEE_EMAIL_RESOLVER port:
interface IInviteeEmailResolver {
getVerifiedEmails(userId: string, tenantId: string): Promise<string[]>;
}
With @nathapp/nestjs-iam, wire its ready resolver (verified email identities of the user in
the invitation's tenant):
import { IamInviteeEmailResolver } from '@nathapp/nestjs-iam';
AccountModule.register({
inviteeEmailResolver: { useFactory: (r: IamInviteeEmailResolver) => r, inject: [IamInviteeEmailResolver] },
});
INVITATION_EMAIL_MISMATCH (403). The invitation stays pending and nothing is written. A
resolver that throws propagates its error.invitation: { requireEmailMatch: false } turns the check off (the previous behaviour).An invitation's role is checked when it is created and again when it is accepted:
ACTIVE membership in the account and either be the
account's ownerId, hold the owner role, or hold the requested role. On accept, the first
two require a transaction-held lock on the membership's account. A policy denial returns
INVITATION_ROLE_NOT_ALLOWED (403) on create; on accept the membership is created without
the role and a warning is logged.INVITATION_ROLE_NOT_FOUND), and
without the role and membership repositories the check allows, as no role can be assigned.canInviteWithRole(roleCode, invitedById, accountId, context?) for a role hierarchy;
context carries the account and roles accept already loaded.When role assignment is configured, call accept for a role-bearing invitation outside
an existing transaction. The service starts a ReadCommitted claim so that membership and role
checks see committed ownership changes. In an existing transaction it cannot guarantee that
isolation: it returns INVITATION_ROLE_NOT_ALLOWED and leaves the invitation pending.
A membership-only claim may join an ordinary txManager.run. As with every other account
write, accept evicts cached permissions and emits account.invitation.accepted when its own
write completes, which is before the caller's commit; a caller that then rolls back has
already notified local listeners. With a transactional OUTBOX_RECORDER, the claim,
membership and the accepted record (payload: { id, userId, tenantId },
metadata: { tenantId }) commit or roll back together, so use the outbox when delivery must
follow the commit.
Rejoining a removed membership: Call addMember or accept directly; no transaction
wrapper is needed. The service starts a ReadCommitted transaction for the rejoin. A
membership-only claim can still create a new membership in a caller's transaction, but
it cannot rejoin a removed member there. An unverified transaction, missing role store,
unsupported repository pair, or missed REMOVED guard results in MEMBERSHIP_ALREADY_EXISTS.
In a transactional invitation claim the refusal rolls back the claim too.
To opt in, implement rejoinIfRemoved(memberships, manager, id, patch) on the injected
membership-role repository. Verify that both stores participate in that exact manager's
transaction. Match the stored REMOVED status, set it active with the supplied metadata,
delete every prior grant from the role store, and return the updated membership. All writes,
including subsequent grants and the service's outbox record, must use the same transaction.
Return null without writes if the pair, transaction or status guard does not match. The
stock Prisma capability accepts only the stock repository classes with the same manager;
custom stores and subclasses must supply their own implementation. For direct adapter calls,
start ReadCommitted only when standalone; when joined, check isMembershipRejoinTransaction(manager)
or verify the actual isolation before writing. Never start an independent transaction to rejoin.
The legacy reactivateIfRemoved changes membership fields only; neither service uses it as
a fallback for a missing rejoin capability.
Override resolveMembershipTargetAccountId(invitation, userId) to redirect the membership.
The service validates that account and, for role-bearing claims on locking adapters, locks it
before invoking onInvitationAccepted. The write hook receives that account as
invitation.accountId and must return the invitee's membership for it. The stored invitation keeps its
original account ID.
Existing return-only overrides: If you override only onInvitationAccepted, you may still
return the invitee's membership in a different account in the invitation tenant. The service
does not lock a second account. It grants the requested role only if the inviter has an active
membership there and explicitly holds that role; neither ownerId nor the owner role is enough.
For a hook that writes to a different account, select it in resolveMembershipTargetAccountId
so its parent is locked before a membership insert can acquire a foreign-key lock. The service
cannot guarantee that lock order for writes made inside a legacy hook. If the hook called
super.onInvitationAccepted({ ...invitation, accountId: 'acc-2' }, userId), replace it with
protected resolveMembershipTargetAccountId() { return 'acc-2'; }: the default writer will
not write to an account other than the one prepared for it.
The in-memory KeyedAsyncLock holds at most 1000 keys in flight
(AccountModule.register({ keyedLockMaxKeys }) changes it). A new key at the cap is refused with
KEYED_LOCK_CAPACITY_EXCEEDED (503) and the callback does not run; a key already in flight still
queues. Use RedisKeyedLock across instances.
The owner role is the role whose code matches ownershipTransfer.ownerRoleCode (default
'owner', compared case- and space-insensitively, and by id against the role the database
resolves for that code).
ownerId may hold it. assignRoles, addMember and
registration refuse it for anyone else with OWNER_CHANGE_REQUIRES_TRANSFER (400).removeRoles refuses to take it from the current owner with the same error.ownerId.IOwnershipTransferService.Every method that acts on a record by id takes the tenant as an explicit argument. Pass the tenant of the request, or the tenant carried by the event or job you are handling:
await accounts.updateStatus(accountId, AccountStatus.SUSPENDED, tenantId);
await roles.assignPermissions(roleId, permissionIds, tenantId);
await profiles.update(accountId, { displayName }, tenantId);
await onboarding.completeStep(accountId, flowId, stepCode, tenantId, data);
The method loads the record and compares its tenant with the argument. A record of another
tenant gets the same not-found error as an unknown id, so the answer never reveals records of
other tenants. An empty, undefined or null tenant is refused before anything is read.
Find threats in your stack.
OX Radar can check high-priority threats, like critical package CVEs, against your context.
Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.
The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).
The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.