npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ballistix.digital/identity-connector

v0.6.0

Published

NestJS module that signs a user in with an OIDC access token and provisions users at one or more identity providers, behind provider-agnostic contracts.

Readme

@ballistix.digital/identity-connector

A NestJS module that signs a user in with an OIDC access token and provisions users at one or more identity providers, behind provider-agnostic contracts. The app does not know which provider is behind it, and one app can use more than one at the same time. The providers are Zitadel, Entra and Auth0, each behind an entry of its own.

This file is the consumer guide and the public contract. The pages that describe how the package is built live in the Ballistix wiki.

Install

npm install @ballistix.digital/identity-connector @ballistix.digital/exception-mapper @ballistix.digital/exception-types class-validator class-transformer

The providers verify tokens, and the Zitadel provider signs its service user's assertion, with jose. Install it when the application imports ./zitadel, ./entra or ./auth0:

npm install jose@^6

Zitadel's bulk import hashes a password with bcryptjs, which it loads only when called. Install it when the application calls provisionMany() on a Zitadel connection:

npm install bcryptjs@^3

jose ships ES modules only. Node 24 loads it from CommonJS by itself, but Jest's CommonJS runtime does not: a Jest setup that loads a provider entry transforms jose to CommonJS (transformIgnorePatterns: ['/node_modules/(?!jose/)']). Give jose a transformer of its own that only rewrites the import syntax and keeps class fields as they are (useDefineForClassFields: true): jose's error classes break under the [[Set]] semantics Ballistix packages compile with, and ts-jest keeps one configuration per Jest project, so a second ts-jest entry does not help. This repository's test/module/common/esModule.transformer.js is such a transformer.

A browser build that reads the ./types entry alone installs the package by itself:

npm install @ballistix.digital/identity-connector

The package needs Node 24 or later and has no dependencies of its own. Every peer dependency is optional, so npm installs none of them for you: install in the application what the entries it imports need.

Entries

| Entry | Holds | | --- | --- | | . | The module, the runtime, the contracts, and identityConnectorException and identityConnectorExceptionTypeOf | | ./zitadel | The Zitadel provider | | ./entra | The Entra provider | | ./auth0 | The Auth0 provider | | ./testing | The test doubles and the store contract | | ./types | The exception type enum, with no framework import |

Signing in

An app writes three classes and registers them. Each one extends a class of the package, which holds the logic.

  1. Register ExceptionModule and the app's provider classes, one per identity provider connection:

    @Module({
      imports: [
        ExceptionModule.forRoot(),
        IdentityConnectorModule.forRoot({ identityProviders: [ComplianceZitadel] }),
      ],
    })
    export class AppModule {}

    The module builds each provider once, with what its constructor injects, so a global ConfigModule or a module in imports must provide it; every guard and identity management then shares that instance. Two providers with the same name stop the app at boot, since a store keeps an identity under its provider's name, and so do two providers that list the same issuer: a token names only its issuer, so with the same audience each would accept the other's tokens. A missing ExceptionModule stops it too: without its filter, every refusal would reach the client as a 500.

  2. Write the user store over the app's own table. It implements UserStore, and the library never touches the table itself:

    @Injectable()
    export class UserStoreService extends UserStore<User> {
      findByIdentityId(identityId, provider, transaction) { /* find by the column of that provider, on the transaction when given */ }
      async linkByEmail(identity) { /* one match by email, conditional link */ }
      async create(identity) { /* only with createOnSignIn: return the user the identity already has, or insert one */ }
      async sync(user, identity) { /* write roles, email, names; return the value for request.user */ }
      toProfile(user, provider) { /* throw identityConnectorException(NO_EMAIL) when the user has none */ }
      link(user, identityId, provider, transaction) { /* conditional: no other identity, no other user, by primary key */ }
    }
  3. Extend the guard, pass it the providers whose tokens it accepts, and put it on the controllers. request.user is what sync() returned:

    @Injectable()
    export class AuthGuard extends IdentityAuthGuard<User> {
      constructor(runtime: IdentityRuntime, store: UserStoreService, zitadel: ComplianceZitadel) {
        super(runtime, store, [zitadel]);
      }
    }
    
    @UseGuards(AuthGuard)

A guard accepts the tokens of the providers it passes to super(), at least one, injected by the class it registered in IdentityConnectorModule.forRoot(); a guard for employee routes passes only the Entra provider. A token goes to the one among them that lists its issuer, before anything is verified, and a token of another registered provider is refused as PROVIDER_NOT_ACCEPTED. A guard without providers, or with a provider the module does not register, stops the app at boot. A provider the app registers only when it is configured is injected with @Optional() and passed only when it is set:

constructor(runtime: IdentityRuntime, store: UserStoreService, entra: ComplianceEntra, @Optional() zitadel?: ComplianceZitadel) {
  super(runtime, store, zitadel ? [entra, zitadel] : [entra]);
}

Provisioning users

Provisioning gives one of the app's users an identity at the identity provider, for example when the app invites a customer: the identity provider's identity with the user's email, or a new one, linked to the user through the store's link(). The app then sends its own mail with a link where the user sets up how they sign in, such as a password.

Extend IdentityManagement once per place the app manages identities, such as customers and employees. It injects the store and the provider class, and passes the management options of that place: their shape is the provider's, for Zitadel the organization new users land in.

@Injectable()
export class CustomerIdentityManagement extends IdentityManagement<User, ComplianceZitadel> {
  constructor(runtime: IdentityRuntime, store: UserStoreService, zitadel: ComplianceZitadel, config: ConfigService) {
    super(runtime, store, zitadel, {
      organizationId: config.get('ZITADEL_CUSTOMERS_ORG_ID'),
      federatedOrganizationIds: [config.get('ZITADEL_VDL_ORG_ID')],
    });
  }
}

Inject it where the domain needs it:

if (!(await this.customers.isFederated(user))) {
  await this.customers.provision(user, transaction);
  // queue the app's own mail
}

// in the mail job, at send time, so the link is never stored
const link = await this.customers.createAccountSetupLink(user, { returnUrl });
  • isFederated(user) is true when the user's email signs in elsewhere, for example employees whose domain belongs to an organization that signs in through Entra. Call it before provision(): provision() does not check it, and would give such a user an identity of its own.
  • provision(user, transaction?) does nothing for a user already linked to the provider. Otherwise it finds the identity by email or creates one, and links it with link(user, identityId, provider, transaction). The store's link() decides: it refuses a user that has another identity of the provider, and an identity another user has. When it refuses, provision() reads the owner with findByIdentityId(identityId, provider, transaction) to throw IDENTITY_ALREADY_LINKED or LINK_REFUSED. The transaction reaches both unchanged, so the store runs them on the connection the transaction holds: with a pool of one connection, a read outside it would wait forever. The guard calls findByIdentityId without a transaction. provision() returns nothing and throws on failure. When it fails after the identity was created, the next call finds that identity by email and links it, rather than creating a second one.
  • provisionMany(users, { transaction?, dryRun?, identityIdOf? }) is provision() for a page of users, such as a migration of existing users needs. It asks the provider for every email at once with findByEmails(), creates the missing identities at once with createMany(), then links each user as provision() does. It returns one result per user, in the order given, and a failure fails only its own user; it throws only when the whole call fails, such as NOT_CONFIGURED or an unreachable search. Check isFederated() first, as for provision(). Pass a page of users per call, such as a hundred. When the provider holds several identities with one email, the user is linked to the first the provider answers. identityIdOf(user) names the id a created identity gets, such as the user's own id, for a provider that lets the caller choose it, as Zitadel's import does; without it, or with another provider, the provider picks the id.
  • createAccountSetupLink(user, { returnUrl }) asks the provider for a link where the identity sets up how it signs in, such as a password.
const results = await this.customers.provisionMany(page, { dryRun });
for (const result of results) {
  if (result.outcome === ProvisionOutcomeEnum.FAILED) {
    log(result.user.id, identityConnectorExceptionTypeOf(result.error) ?? result.error.message);
  }
}

| Outcome | Meaning | | --- | --- | | ALREADY_PROVISIONED | The user had an identity at the provider; nothing changed | | PROVISIONED | The user is linked to the identity with its email, which the provider had or created | | WOULD_LINK, WOULD_CREATE | dryRun: what a real run would do. A dry run creates, links and forgets nothing | | FAILED | The user got no identity. error is what provision() would have thrown |

Two users with one email get one identity: the first links it, and the second fails with IDENTITY_ALREADY_LINKED, as two provision() calls in a row would. A dry run reports the same, and also IDENTITY_ALREADY_LINKED for an identity another user already holds.

A provider without bulk calls answers findByEmails() and createMany() with one findByEmail() or create() per user, so provisionMany() works with every provider; Zitadel overrides both.

A sign-in refused just before the user is provisioned is not remembered after provision() links the identity, so the user signs in at once. That holds when the guard and the identity management inject the same store instance: the guard remembers sign-ins per store instance, so two store classes are two caches, even over one table, and so is one class registered in two modules. Register the store once, as a singleton: a request-scoped store gets a new cache on every request, which remembers nothing and does not run parallel first sign-ins of one identity one at a time. Calling provision() again for a user already linked clears the refusal as well.

Each method reads the email and the identity id through the store's toProfile(user, provider), so the app never handles an identity id. Two identity managements may inject one provider class, each with its own management options. An identity management whose provider class is not registered in IdentityConnectorModule.forRoot() stops the app at boot.

What the methods throw; Exceptions lists every type with its code and field:

| Type | Status | Exception | When | | --- | --- | --- | --- | | NO_EMAIL | 409 | PreconditionFailedException | toProfile() found no email on the user | | IDENTITY_ALREADY_LINKED | 409 | PreconditionFailedException | provision(): the store's link() refused, and another user owns the identity with the user's email | | LINK_REFUSED | 409 | PreconditionFailedException | provision(): the store's link() refused for another reason, such as a user with another identity of the provider | | USER_NOT_PROVISIONED | 409 | PreconditionFailedException | createAccountSetupLink(): the user has no identity at this provider | | NOT_CONFIGURED | 503 | GenericErrorException | The provider holds no management credentials. Catch it to skip provisioning, for example on a local machine | | NOT_SUPPORTED | 501 | GenericErrorException | The provider cannot perform the call | | PROVIDER_UNREACHABLE | 503 | GenericErrorException | The provider could not be reached |

A refusal of the provider that retrying does not fix, such as a rejected key, is a plain Error with the provider's answer; the provider's section says which.

Exceptions

The library has no exception class of its own. It throws the exceptions of @ballistix.digital/exception-types, so the app's exception filter and its frontends see the same classes and envelopes as for any other error. Each type of IdentityConnectorExceptionTypeEnum reaches the client as:

| Type | Status | Code | Exception | Where the type sits | Thrown by | | --- | --- | --- | --- | --- | --- | | NO_TOKEN | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard: no Bearer token | | UNKNOWN_ISSUER | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard: no registered provider lists the token's issuer | | PROVIDER_NOT_ACCEPTED | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard: the provider that lists the token's issuer is registered, but not one the guard accepts | | INVALID_TOKEN | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard and the providers: the token is not valid | | USER_NOT_LINKED | 403 | ACCESS_DENIED | AccessDeniedException | errors[0].message | The guard: no user for the identity | | NO_EMAIL | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | The store's toProfile() | | IDENTITY_ALREADY_LINKED | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | provision() | | LINK_REFUSED | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | provision() | | USER_NOT_PROVISIONED | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | createAccountSetupLink() | | NOT_SUPPORTED | 501 | GENERIC_ERROR | GenericErrorException | errors[0].message | A management call the provider cannot perform | | NOT_CONFIGURED | 503 | GENERIC_ERROR | GenericErrorException | errors[0].message | A management call without credentials | | PROVIDER_UNREACHABLE | 503 | GENERIC_ERROR | GenericErrorException | errors[0].message | A provider that cannot reach its identity provider |

A frontend that maps the library's refusals reads the type from the field the table names; the code alone does not tell USER_NOT_LINKED apart from another 403, nor a 401 of the library from another UNAUTHENTICATED.

  • To react to one case, read the type with identityConnectorExceptionTypeOf(error) and compare it; never compare the message or the class. It answers only for an exception with the code and status the type is thrown with, and undefined for anything else.

    try {
      await this.customers.provision(user, transaction);
    } catch (error) {
      if (identityConnectorExceptionTypeOf(error) !== IdentityConnectorExceptionTypeEnum.NOT_CONFIGURED) throw error;
    }
  • To throw one, from a store or from a provider the app writes, use identityConnectorException(type): it picks the class and status the type reaches the client with, for example throw identityConnectorException(IdentityConnectorExceptionTypeEnum.NO_EMAIL) in toProfile().

Zitadel

ZitadelProvider from ./zitadel signs users in with access tokens of one Zitadel instance. The app extends it once per connection:

@Injectable()
export class ComplianceZitadel extends ZitadelProvider {
  constructor(config: ConfigService) {
    super({
      name: 'zitadel',
      issuer: config.get('ZITADEL_ISSUER'),
      projectId: config.get('ZITADEL_PROJECT_ID'),
      organizationIds: [config.get('ZITADEL_VDL_ORG_ID')],
      roleOrganizationIds: [config.get('ZITADEL_VDL_ORG_ID')],
      linkByEmail: true,
      serviceUserKey: config.get('ZITADEL_SERVICE_USER_KEY'),
    });
  }
}

| Option | Required | Meaning | | --- | --- | --- | | name | yes | The provider name; unique in the app | | issuer | yes | The Zitadel instance URL: the one issuer it accepts and the base of its endpoints. A trailing slash is dropped | | projectId | yes | The Zitadel project: the audience every token carries | | organizationIds | yes, at least one | The organizations whose users may be linked or created at sign-in | | roleOrganizationIds | yes, at least one | The organizations whose role grants count | | linkByEmail, createOnSignIn | no, both off | As for every provider | | serviceUserKey | no | The key file of the service user that calls the management API, parsed or as its JSON text. Left out or an empty string, every management call throws NOT_CONFIGURED; null or text that is not JSON stops the app at boot |

Both organization lists are required and may not be empty. An empty list would quietly let every organization in, or let every organization's role grants count: another organization with a grant on the project could then hand its users an elevated role. A connection with a missing or empty option stops the app at boot with a message that names the provider and every failing option.

The app's Zitadel application must issue JWT access tokens. The provider verifies each token against the instance's signing keys (RS256, this issuer, this project as audience) and caches the keys, so a signed-in user costs no call to Zitadel; an opaque access token cannot be verified and is refused as not valid.

The keys are cached by jose's createRemoteJWKSet. A token whose key is cached is answered from the cache. Once the keys are ten minutes old, the next token waits for a fresh set. A token with a key id the cache lacks fetches the keys again when the last fetch that succeeded is 30 seconds old or more; otherwise, it is refused as not valid (401). Every token waiting on a fetch shares it. Tokens with made-up key ids therefore cost Zitadel at most one request per 30 seconds and never lock out a user whose key is known. A key Zitadel adds is accepted within 30 seconds, and a key it withdraws is refused within ten minutes. A fetch gets 5 seconds; when the keys are needed and cannot be fetched, the token fails with PROVIDER_UNREACHABLE (503) rather than as not valid, so a user with a key Zitadel just added is not signed out. While Zitadel's key endpoint is down, every sign-in fails this way once the keys are ten minutes old.

On a first sign-in, when no user is linked yet, the provider calls Zitadel's userinfo endpoint to complete the identity: email, whether Zitadel verified it, and names. It refuses a user whose organization is not in organizationIds with USER_NOT_LINKED (403). The frontend must request the scope urn:zitadel:iam:user:resourceowner at sign-in: without it userinfo leaves the organization out, and every first sign-in is refused. The provider passes emailVerified on without checking it; a store that links by email decides whether an unverified email may link.

Managing Zitadel users

With serviceUserKey, an IdentityManagement on this provider provisions users at Zitadel. Its management options:

| Management option | Required | Meaning | | --- | --- | --- | | organizationId | yes | The organization provision() searches by email and creates new users in | | federatedOrganizationIds | no | Organizations whose users sign in elsewhere: isFederated() is true for an email on one of their domains |

The service user is a machine user with a key of type JSON. It needs to search and create users and create password codes in organizationId, and to read the domains of federatedOrganizationIds. The provider exchanges an assertion signed with its key for an access token (Zitadel's JWT profile grant) and reuses that token until a minute before it expires.

  • findByEmail searches organizationId alone, without regard to case. Two users there with one email are an error rather than a pick.
  • create makes a human user with a verified email and no password.
  • createAccountSetupLink returns a link to the password page of Zitadel's login (v2), with a password code Zitadel returns instead of mailing it. The code is valid as long as the instance's setting for password reset codes says, so ask for the link when the mail is sent; every call creates a new one. The page reads no return address, so returnUrl is ignored.
  • isFederated compares the email's domain with the domains of federatedOrganizationIds, exactly: a subdomain does not count. It caches each organization's domains for ten minutes, so a domain an admin adds counts within that time.
  • Every email is sent trimmed and in lowercase. Zitadel matches uppercase letters badly in its user search and its domain discovery (Zitadel issue #12025).

provisionMany() runs on the provider's two bulk calls, which send a 429 again, up to five times, after Zitadel's Retry-After (at most 30 seconds) or after 2, 4, 8, 16 and 32 seconds: Zitadel Cloud blocks for about half a minute and sends no Retry-After. Every other call fails at once, so a request never hangs on a rate limit.

  • findByEmails searches all emails of the call in one request, and keeps the first user Zitadel answers for an email with several. Zitadel answers at most 1000 users, so an answer that long throws rather than leave users out: pass a page of users, such as a hundred.
  • createMany imports two hundred users per request with Zitadel's import, each under the id identityIdOf names or a new random one, with the email as user name and verified, and a bcrypt hash of a random password nobody knows: without a password Zitadel marks the user initial, ignores the verified email and mails its own invitation. The import needs the IAM_OWNER role; without it Zitadel answers 403, and the provider creates the users one by one with create() instead. A user Zitadel refused fails with Zitadel's reason.

The management options are checked at boot when serviceUserKey is given: a missing organizationId stops the app with a message that names the identity management. Without the key they go unchecked, so an app on a local machine may leave both unset; every management call then throws NOT_CONFIGURED, which the app catches to skip provisioning.

A call Zitadel cannot answer, through a network failure, a timeout of 5 seconds, a 5xx, a 408 or a 429, is PROVIDER_UNREACHABLE (503). So is a 401: it may only mean Zitadel ended the service user's token early, so the provider drops that token and the next call fetches a new one; the app tries again, as for any 503. Any other refusal, such as a key Zitadel rejects when the provider asks for a token or a service user without a permission, is a plain Error with Zitadel's status and answer: a fault in the configuration that retrying does not fix, and that an app skipping NOT_CONFIGURED must not skip silently.

Entra

EntraProvider from ./entra signs users in with access tokens of one Entra tenant, and with acceptIdTokens also with its ID tokens (see ID tokens); without that option an ID token is refused. The app extends it once per tenant:

@Injectable()
export class ComplianceEntra extends EntraProvider {
  constructor(config: ConfigService) {
    super({
      name: 'entra',
      tenantId: config.get('AZURE_AD_TENANT_ID'),
      // Without ?., a missing variable fails here instead of in the provider's boot check.
      audience: config.get('AZURE_AD_AUDIENCE')?.split(','),
      createOnSignIn: true,
    });
  }
}

| Option | Required | Meaning | | --- | --- | --- | | name | yes | The provider name; unique in the app | | tenantId | yes | The GUID of the tenant. It gives the issuers and the URL of the signing keys. common and organizations name no single tenant and stop the app at boot | | audience | yes | The application ID URI or client id every token carries, or a list of them. Each is trimmed | | linkByEmail | no, off | Leave it off; see below | | createOnSignIn | no, off | As for every provider | | acceptIdTokens | no, off | Also accept an ID token of the tenant; see ID tokens |

One provider per tenant. Both of the tenant's issuers belong to the provider, and two providers may not list one issuer, so a second provider for the same tenant stops the app at boot. Several app registrations of the tenant share one provider through a list of audiences.

The provider accepts both of Entra's token versions: a v2.0 token, issued by login.microsoftonline.com/<tenant>/v2.0, and a v1.0 token, issued by sts.windows.net/<tenant>/. Which one Entra issues depends on the app registration; nothing there has to change. It verifies each token against the tenant's signing keys (RS256, one of those issuers, one of the audiences) and caches the keys, as the Zitadel provider does, with the same times. It reads the tenant's keys: an app registration with a claims-mapping policy gets its tokens signed with a key of its own, which those keys do not list, so every token of it is refused as not valid.

  • Identity.id is the oid claim, the identity's object id. sub differs per app registration, so a store that keeps the sub finds no user once another app registration signs the same person in.
  • A token without scp is refused with INVALID_TOKEN (401), unless it is an ID token and acceptIdTokens is on. Only an access token issued to an identity carries scopes; an app's own token, from the client credentials grant, has an oid and may carry app roles, but belongs to no identity. An app that calls the API with such a token is refused.
  • The email is the email claim, which Entra adds only when the app registration asks for it as an optional claim; without it the email is null. The names are given_name and family_name: a v1.0 access token carries them, a v2.0 one only as optional claims. For an access token, those optional claims are set on the app registration of the API, not of the frontend that asks for the token. preferred_username and upn look like an email but need not be one and can change, so the provider does not read them. emailVerified is always false: Entra's tokens do not say.
  • Leave linkByEmail off. The email claim is the identity's mail attribute, which an admin sets and Entra does not verify; on a guest it can be any address. A store that links by email would hand the user with that address to whoever carries it. Turn it on only with a store that trusts the tenant's mail attributes, and expect emailVerified to be false.
  • The roles are the app roles in the roles claim.
  • A first sign-in needs no call to Entra: the token carries all the provider knows, so readProfile returns the identity as it is.

ID tokens

The proper setup is an access token for an API scope the app registration exposes: the frontend asks for that scope, and the backend accepts what Entra issued for it. Some frontends send their ID token as the bearer instead, because they only ask for openid profile email and their access token is one for Microsoft Graph. acceptIdTokens: true lets such a frontend keep working while it moves to an API scope. An ID token's audience is the frontend's client id, so audience lists that client id.

With the option on, a token without scp passes as an ID token only when both hold:

  • It names no client. Every Entra access token names the client it was issued to, azp in a v2.0 token and appid in a v1.0 token, an app's own token from the client credentials grant included. An ID token carries neither. A token with idtyp: "app" is refused as well.
  • It names a person, in name, preferred_username or unique_name. An app's own token has none of them. An ID token with an oid does: Entra adds the oid only with the profile scope, which brings them.

Signature, issuer, audience, lifetime and oid are checked as for an access token, and the identity is read the same way. Delegated access tokens, with scp, are still accepted.

What the option does not protect against:

  • An ID token is meant for the frontend, not for an API. Anyone who gets hold of a user's ID token for that client, from the browser's storage or a log line, can call the API with it until it expires, usually after an hour. It cannot be narrowed to this API, and Entra does not end it early when the user signs out or loses access.
  • The rule rests on claims as Microsoft documents them today, which it does not promise to keep. Ask Entra for the idtyp optional claim on the access tokens of the API's app registration: an app's own token then says so explicitly.

Turn it off once the frontend sends an access token for the API's scope.

Managing Entra users

The management calls are not available yet. findByEmail and create throw NOT_CONFIGURED, which an app that provisions users catches to skip provisioning. createAccountSetupLink and isFederated throw NOT_SUPPORTED (501): the tenant's IT hands employees their password, and an Entra identity never signs in elsewhere.

Auth0

Auth0Provider from ./auth0 signs users in with access tokens of one Auth0 tenant for one or more of its APIs. The app extends it once per tenant:

@Injectable()
export class AppAuth0 extends Auth0Provider {
  constructor(config: ConfigService) {
    super({
      name: 'auth0',
      domain: config.get('AUTH0_DOMAIN'),
      // Without ?., a missing variable fails here instead of in the provider's boot check.
      audience: config.get('AUTH0_AUDIENCE')?.split(','),
      rolesClaim: '.roles',
      createOnSignIn: true,
    });
  }
}

| Option | Required | Meaning | | --- | --- | --- | | name | yes | The provider name; unique in the app | | domain | yes | The tenant's domain as the Auth0 dashboard shows it, such as <tenant>.<region>.auth0.com, or its custom domain. A host only: a scheme or a path stops the app at boot | | audience | yes | The identifier of the Auth0 API every token carries, or a list of them. Each is trimmed | | rolesClaim | no, none | The access token claim the post-login Action writes the roles to, such as .roles. Left out, the roles are none | | linkByEmail | no, off | As for every provider; see below | | createOnSignIn | no, off | As for every provider |

The provider verifies each token against the tenant's signing keys at https://<domain>/.well-known/jwks.json (RS256, the issuer https://<domain>/ with Auth0's trailing slash, one of the audiences) and caches the keys, as the other providers do, with the same times. A token names the domain it was requested on: a tenant with a custom domain passes that domain, and its frontend requests tokens on it, or every token is refused as one of another issuer.

  • Identity.id is the sub claim, such as auth0|<id>. Auth0 keeps it for the identity across every application and API of the tenant.

  • An app's own token is refused with INVALID_TOKEN (401). A token from the client credentials grant has the same issuer and audience as a user's, but Auth0 marks it with gty: "client-credentials" and names the client as its subject, <client id>@clients. Either one refuses it.

  • The email and names come from the token, through a post-login Action. An Auth0 access token carries no email or names by itself. Add an Action to the tenant's post-login flow that puts them in every access token:

    exports.onExecutePostLogin = async (event, api) => {
      api.accessToken.setCustomClaim('email', event.user.email);
      api.accessToken.setCustomClaim('email_verified', event.user.email_verified);
      api.accessToken.setCustomClaim('given_name', event.user.given_name);
      api.accessToken.setCustomClaim('family_name', event.user.family_name);
      // Only with rolesClaim: '.roles'.
      api.accessToken.setCustomClaim('.roles', event.authorization?.roles ?? []);
    };

    Auth0 drops email and email_verified from the token unless the login asks for the email scope, and the names unless it asks for profile, even when the Action sets them: the frontend asks for openid profile email.

    The provider reads email, email_verified, given_name and family_name on every sign-in, so sync() gets the same values each time, and a change in Auth0 reaches the user at the next sign-in. It calls Auth0 for nothing but its signing keys. Without the Action the email and names are null: a first sign-in creates a user without them, and toProfile later throws NO_EMAIL for that user.

  • emailVerified is the token's email_verified, and only next to an email of the same token. A user an admin created in the dashboard has an unverified email unless the admin marked it verified; with linkByEmail, whether such an email may be linked stays the store's decision.

  • The roles are the text entries of the rolesClaim list. Auth0 has no standard roles claim, and silently drops a custom claim named roles, so the tenant's Action writes them to a claim of its own choosing and the app names it. Without rolesClaim, or when the token's claim is missing or not a list, the roles are none. The roles go in the access token: a .roles claim the Action writes to the ID token never reaches the backend.

How the frontend gets the token, through Auth0's login page or the password grant on a server of the app, makes no difference to the provider.

Managing Auth0 users

The management calls are not available yet. findByEmail, create, createAccountSetupLink and isFederated throw NOT_CONFIGURED, which an app that provisions users catches to skip provisioning; provisionMany() fails through them as well. Each becomes possible once the provider calls Auth0's Management API.

Testing an app

./testing gives an app what it needs to test sign-in without an identity provider:

const provider = new TestIdentityProvider({ name: 'zitadel', issuers: ['https://test-issuer'] });

Test.createTestingModule({ imports: [AppModule] })
  .overrideProvider(ComplianceZitadel)
  .useValue(provider);

const token = provider.createToken({ id: 'zitadel-1', roles: ['ADMIN'] });

Run the store contract against the app's own store, so a store that breaks a rule the types cannot express fails in the app's CI:

for (const check of userStoreContract(() => ({ store, providers: ['zitadel'], createUser, userId: (user) => user.id }))) {
  it(check.name, check.run);
}

Good to know

  • A change at the provider takes up to signInCacheSeconds to arrive. The guard verifies the token on every request, but for an identity it saw recently it answers from its cache, without the store and without sync(). A revoked role therefore stays on request.user until the entry expires: 60 seconds by default. Set signInCacheSeconds: 0 to apply such a change on the next request, at the cost of a store call on every request.

  • A refused sign-in stays refused for up to signInCacheSeconds. The guard remembers a USER_NOT_LINKED refusal too. provision() drops it when it links the identity. A user the app links by other means is still refused until the entry expires, unless signInCacheSeconds is 0, and so is a sign-in that arrives between provision() and the commit of the app's transaction; calling provision() again after the commit clears it.

  • link() keeps one identity to one user. The library cannot tell two user objects apart, so the store compares users by primary key and checks within the write. On PostgreSQL, a conditional update does both at once, with a unique index on the identity column behind it. The example runs it in a nested transaction(), which TypeORM 0.3.22 turns into a savepoint inside the app's transaction; a version without nested transactions throws TransactionAlreadyStartedError there and needs a savepoint of its own through the query runner:

    async link(user: User, identityId: string, provider: string, transaction?: EntityManager): Promise<boolean> {
      try {
        // Within the app's transaction this is a savepoint, so a unique violation undoes this update alone.
        return await (transaction ?? this.manager).transaction(async (manager) => {
          const result = await manager
            .createQueryBuilder()
            .update(User)
            .set({ zitadelId: identityId })
            .where('id = :userId', { userId: user.id })
            .andWhere('("zitadelId" IS NULL OR "zitadelId" = :identityId)', { identityId })
            .andWhere('NOT EXISTS (SELECT 1 FROM "user" other WHERE other."zitadelId" = :identityId AND other.id <> :userId)')
            .execute();
    
          return result.affected === 1;
        });
      } catch (error) {
        // The identity column's own unique index: another transaction linked the identity at the same moment.
        if (error instanceof QueryFailedError && error.driverError?.constraint === 'UQ_user_zitadelId') {
          return false;
        }
        throw error;
      }
    }

    The unique index covers what the NOT EXISTS cannot: two transactions open at the same time do not see each other's writes, so both could pass it. Catching its violation turns it into a refusal rather than the database's own error. Match the index by its name, so a violation of another unique index on the table still surfaces as the data error it is; name it yourself, such as @Index('UQ_user_zitadelId', ['zitadelId'], { unique: true }), since TypeORM otherwise names it after a hash.

    The savepoint keeps the app's transaction usable after a violation. Without one, PostgreSQL refuses every further query of that transaction, so provision()'s read of the owner fails, and provision() throws that database error instead of IDENTITY_ALREADY_LINKED. A user object the app loaded before another call linked that user links fine, since the update checks the row, not the object.

    MySQL refuses a subquery on the table an update writes, so a MySQL store leaves out the NOT EXISTS, relies on the unique index alone and catches its ER_DUP_ENTRY (errno 1062) instead of 23505. The quoted table and column names are the database's; match them to the entity's table and the naming strategy.

  • Provision one user one call at a time. Two provision() calls for the same user that run at once can both miss the identity at the provider and each create one. The first links its identity; the second gets LINK_REFUSED, and its identity stays at the provider, linked to no one. Run provisioning for a user from one place, such as the job that invites them.

  • create() must be safe to run twice for one identity. Within one app instance the guard runs one sign-in per identity at a time, so parallel requests of a new user wait for a single create(). Two app instances can still each sign the same new identity in. Give the identity column a unique index and return the existing user on a conflict; the store contract checks it.

  • Treat request.user as read-only. While an identity is cached, all its requests share one request.user object. Keep per-request data elsewhere on the request.

  • A guard injects its providers by the class the app registered. It accepts exactly the instances it passes to super(), so inject ComplianceZitadel, the class listed in forRoot(), not a base class such as ZitadelProvider, which Nest cannot inject. A test that replaces ComplianceZitadel with overrideProvider replaces it in the guard too.

  • A provider tells an unreachable provider apart from a bad token. The guard passes an exception identityConnectorException made from authenticate() on unchanged, so a provider throws identityConnectorException(PROVIDER_UNREACHABLE) (503) when it cannot reach its identity provider. Anything else authenticate() throws, another exception of exception-types included, is a token that is not valid (401), so a bad token never reaches the client as a 500 or a 404. This matters only to an app that writes its own provider.

  • The guard links by email only an identity that has an email. Whether the email must be verified is the store's decision, in linkByEmail().

  • A store implements what its guard's providers allow. linkByEmail() and create() return null unless the store overrides them, which refuses the sign-in. When a provider the guard accepts has linkByEmail or createOnSignIn and the store leaves that method out, the app stops at boot with a message that names both. A guard that writes its own onModuleInit calls super.onModuleInit(), or the check does not run.

  • The guard guards HTTP routes. It reads the Authorization header of an HTTP request.