Login Providers

Last Updated: November 2026 · Plugin API: 1.4

A plugin can add a way to sign in: Google, a company’s Keycloak, a signed link from an app, a Telegram Mini App. It registers a provider with registry.auth.registerProvider(). Core does everything that is the same for every provider (the OAuth 2.0 / OpenID Connect round trip, PKCE, state and nonce, the account rules, two-factor authentication, sessions, the buttons on the login pages), and the plugin supplies only what is specific to the provider: where to send the player, how to prove who they are, and how to turn the provider’s answer into a profile.

No core change is needed for a new provider. The first-party social-login plugin (Google, Discord, X, Apple, generic OIDC) and telegram-auth are built on exactly this API.

SectionWhat it covers
ConceptsKinds, intents, sign-up modes, trustEmail, anonymous providers, provisioning, redirect and credential flows, descriptors and buttons
The provider definitionEvery field of a definition
The registry APIregistry.auth.*, registry.secrets, capabilities
Example: an OIDC provider pluginA complete plugin with defineOAuthProvider
Example: a credential provider pluginA complete plugin with defineCredentialProvider
TestingThe test doubles, runTestMapProfile and runTestCredential
Security modelWhat core guarantees and what the provider must do
ErrorsError codes

Concepts

Kinds

KindThe player is sent toThe plugin supplies
oidcAn OpenID Connect issuer (found through <issuer>/.well-known/openid-configuration)issuer, scopes, client credentials, mapProfile
oauth2An OAuth 2.0 authorization server that is not OpenID Connect (Discord, X)authorizationEndpoint, tokenEndpoint, usually userinfoEndpoint, scopes, client credentials, mapProfile (which fetches the profile)
credentialNowhere. The client already holds a credential (Telegram initData, a signed token, the identity token of native Sign in with Apple) and posts it to coreverifyCredential

An oidc or oauth2 provider may also define verifyCredential (native Sign in with Apple does).

The two flows

Redirect flow (oidc, oauth2). The login page links to GET /api/v1/auth/external/<id>/start. Core creates a single-use flow (PKCE verifier, state, nonce), sets a binding cookie and redirects to the provider. The provider redirects back to GET|POST /api/v1/auth/external/<id>/callback. Core checks the flow, exchanges the code at the token endpoint, verifies the id_token (OIDC), fetches the userinfo, calls the plugin’s mapProfile, and hands the browser a one-time code. The client exchanges the code for a session. The provider’s access and refresh tokens are used once to read the profile and then discarded; they are never stored.

Credential flow (credential). The client posts { credential, intent } to POST /api/v1/auth/external/<id>/credential. Core calls the plugin’s verifyCredential and answers with the same result as the redirect flow’s exchange.

The request may add signup: false (optional, since API 1.4; default: the provider’s sign-up mode applies). It makes the request sign-in only: an identity that already has an account signs in as usual (guards, 2FA), and an identity without one is refused with EXTERNAL_AUTH_NOT_LINKED (403) instead of a complete_signup step, an auto-provisioned account or a link_required ticket. Send it when the client cannot vouch that the credential belongs to the person at the keyboard. telegram-auth does this for launch data outside a confirmed Telegram client, because anyone can send a link that carries their own signed initData.

Both flows end in the same place: core turns the ExternalIdentityInput the plugin returned into one of the outcomes under Intents.

Intents

IntentMeaningNeeds
loginSign in to an existing accountnothing
signupCreate an account (also used when a login finds no account)nothing
linkAdd this provider to the signed-in player’s accounta signed-in player
reauthThe signed-in player proves again that this provider is theirs (to set a first password)a signed-in player
testAn admin runs the flow and sees the mapped profile; nothing is writtenan admin session

A definition lists the intents it supports with intents (login, signup, link; default all three). reauth and test are implied for every provider.

What happens to an identity

For a provider identity that core has not seen (login or signup intent):

  1. signupMode: 'link_only': no account is created; the player gets EXTERNAL_AUTH_NOT_LINKED ("sign in with your password and link it in Settings").
  2. The provider’s email matches an existing account (verified or not): core never signs the player in. It answers link_required; the player signs in with their password (and 2FA) and the provider is then linked. Accounts are never merged by email.
  3. signupMode: 'auto' and everything needed is known (a username can be derived, and the email is trusted-verified or the provider defines a placeholderEmail): core creates the account at once.
  4. Otherwise (signupMode: 'complete', or something is missing): core shows a short "complete your profile" step, pre-filled from the profile.

For a known identity core signs the player in after the same checks as a password login: blocked and frozen accounts, manual approval, email verification, rate limits and two-factor authentication. Admin accounts never sign in through a provider.

signupMode

ValueBehaviour
autoCreate the account immediately when the provider gave everything required
completeAlways show the "complete your profile" step first (the default)
link_onlyNever create accounts; only players who linked the provider in Settings can use it

signupMode is the provider’s default. An admin can override it per provider in Settings › Login Providers.

trustEmail

A provider reports email and emailVerified. Core treats emailVerified: true as proof of the address only when the definition sets trustEmail: true. A trusted-verified email makes the new account’s email confirmed (no verification mail) and lets an existing identity sign in without a fresh email verification. An email that is not trusted is shown to the player to confirm and goes through the normal verification policy. Default: false. Set it only for a provider that really verifies email addresses (Google, Apple), never for one where players type anything (a generic OIDC issuer an admin points at an open registration page).

Anonymous providers (anonymous)

Set anonymous: true on a provider that creates accounts without identifying the player, such as a guest sign-in kept by the device (guest-login’s guest). Core then marks every account the provider creates, by auto-provisioning or complete-signup, in User.metadata.anonymousAccount ({ provider, ownerPlugin, createdAt }), and keeps that account to play money until it has a real email address that is confirmed: every real-money action (deposit, withdrawal, purchase, a real-money transfer either way, a seat at a REAL_MONEY table, a tournament not in VIRTUAL_CHIPS) is refused with REAL_EMAIL_REQUIRED (see player:eligibility). The marker is on the account, so the rule holds when your plugin is deactivated, auto-disabled or removed, and you do not need a player:eligibility filter for it.

The account qualifies once its email is no longer a .invalid placeholder and is confirmed. A first email set with registry.auth.identities.setFirstCredentials (or POST /user/identities/password) starts unconfirmed and gets a verification email; linking another sign-in method, or a password alone, does not change the email, so the account stays play-money only. An admin can confirm an email in Players › Users (Confirm email in the player’s details). Default false: a provider that identifies the player (Telegram, Google, Discord) is not anonymous, even when its accounts have placeholder addresses, and its players keep real money. Identities of an anonymous provider linked to an existing account do not mark that account.

Provisioning

An auto-provisioned account needs a username and an email. provisioning controls the fallbacks:

  • placeholderEmail(identity): an address for providers that give none, e.g. tg_<id>@telegram.invalid. Use a reserved domain (.invalid) so it can never receive mail. Without it, a provider that gives no trusted email falls back to the "complete your profile" step.
  • usernamePrefix: the prefix for a generated username when the profile offers no usable handle (default <id>_; 1 to 16 letters, digits or _).

Accounts created this way get a random unusable password (passwordSetAt stays null). The player can set a first password later in Settings → Sign-in methods after re-authenticating with the provider.

Descriptors and buttons

Clients never see the definition. They see the descriptor (GET /api/v1/auth/providers → descriptors, enabled providers only):

interface AuthProviderDescriptor {
  id: string; displayName: string; kind: 'oidc' | 'oauth2' | 'credential';
  icon: { svg?: string; url?: string } | null;
  brand: { background: string; foreground: string; border?: string } | null;
  intents: AuthIntent[]; platforms: ('web' | 'mobile')[];
  button: boolean;
  nativeCredential?: 'apple' | null;
}
  • button (default true for oidc and oauth2, false for credential): core renders a "Continue with <displayName>" button on the login and register pages, in every theme, and a link button in Settings → Sign-in methods. A credential provider has no page to send the player to, so its plugin either supplies the UI (a slot fill, as Telegram does inside its WebView) and sets button: false, or (API 1.4) sets button: true and registers a client starter with engine.auth.registerCredentialStarter(providerType, providerId, start): the host then lists the button on the login and register screens (never for link, nor as a Sign-in methods re-auth button) and calls start({ intent, returnTo, ref }) on click; the starter posts the credential and hands the answer to engine.auth.continueExternalSignIn. Without a registered starter the button is left out. guest-login is the example.
  • icon: inline svg (sanitised by core: no scripts, external references or event handlers; at most 8 KB) or an https url.
  • brand: #rrggbb colours for the button.
  • platforms: web, mobile or both (default both). A web-only credential provider lists ['web'].
  • nativeCredential: 'apple': the mobile app shows the native Sign in with Apple sheet and posts the identity token to the credential endpoint instead of opening the browser.
  • isEnabled(): disabled providers are hidden and refused with PROVIDER_DISABLED. It runs on every request, so read the plugin’s settings there rather than capturing them at registration.

The provider definition

AuthProviderDefinition is OAuthProviderDefinition | CredentialProviderDefinition, both exported by the SDK.

Fields of every provider

FieldTypeDescription
idstring^[a-z][a-z0-9-]{0,31}(:[a-z0-9-]{1,32})?$, e.g. google, x, oidc:acme. Global across plugins. local and password are reserved.
displayNamestring1 to 40 characters. Shown on buttons.
icon, brandSee Descriptors and buttons.
intents('login' | 'signup' | 'link')[]Default all three.
platforms('web' | 'mobile')[]Default both.
buttonbooleanDefault true for oidc and oauth2, false for credential.
trustEmailbooleanDefault false.
anonymousbooleanDefault false. Accounts it creates are play-money only until they have a confirmed real email. See Anonymous providers.
signupMode'auto' | 'complete' | 'link_only'Default complete. An admin may override it.
provisioning{ placeholderEmail?, usernamePrefix? }See Provisioning.
nativeCredential'apple' | nullMobile native flow.
isEnabled()Promise<boolean>Required.
verifyCredential(credential, ctx)Promise<ExternalIdentityInput>Required for credential; optional for the others.

oidc and oauth2 providers

FieldDescription
kind'oidc' or 'oauth2'
issueroidc: required. Discovery runs at <issuer>/.well-known/openid-configuration; the issuer is also the expected iss of the id_token.
authorizationEndpoint, tokenEndpointoauth2: required. For oidc they override the discovered values.
userinfoEndpoint, jwksUriOptional overrides (userinfo is fetched when set or discovered).
scopesRequired, non-empty.
responseModequery (default) or form_post. A form_post callback is a cross-site POST, so core sets the flow’s binding cookie SameSite=None; Secure. Apple needs it.
tokenEndpointAuthclient_secret_basic (default), client_secret_post or none.
extraAuthorizeParamsAdded to the authorize URL (prompt: 'select_account'). May not contain a parameter core sets itself: client_id, redirect_uri, response_type, response_mode, scope, state, nonce, code_challenge, code_challenge_method.
getClientCredentials()Returns { clientId, clientSecret? }. Called for every flow, so a provider that builds its client secret per flow (Apple signs a JWT) can.
mapProfile(input)Turns the provider’s answer into an ExternalIdentityInput.

mapProfile receives:

interface MapProfileInput {
  idTokenClaims: Record<string, unknown> | null;  // verified by core: signature, iss, aud, exp, nonce. null for oauth2
  userinfo: Record<string, unknown> | null;       // fetched by core when there is a userinfo endpoint
  callbackParams: Record<string, string>;         // every callback parameter except code and state (Apple's first-login `user`)
  fetchJson(url: string): Promise<unknown>;       // GET with the access token (https, 5 s, 256 KB)
}

It returns:

interface ExternalIdentityInput {
  providerUserId: string;          // required, 1..255, stable for the person: the OIDC `sub`, the Discord user id
  email?: string | null;
  emailVerified?: boolean;         // the provider's claim; core believes it only with trustEmail
  displayName?: string | null;
  username?: string | null;        // the provider's handle; used for username suggestions
  firstName?: string | null;
  lastName?: string | null;
  avatarUrl?: string | null;       // https only
  locale?: string | null;
  profile?: Record<string, string | number | boolean | null>;   // small extras, at most 4 KB as JSON
}

Core validates the result with externalIdentityInputSchema: text is trimmed, the email lower-cased, empty strings become null, a non-https avatar or an invalid email fails the sign-in with PROVIDER_RESPONSE_INVALID. So map leniently (drop what you cannot trust) and return what you have.

credential providers

verifyCredential(credential, ctx) receives the object the client posted and { intent, ip, userAgent?, client }. It returns an ExternalIdentityInput or throws to refuse; a throw becomes CREDENTIAL_INVALID (401) and its message is logged, never sent to the client.

The registry API

Every method below needs the auth:provider capability, except registry.secrets (capability storage). Both capabilities are high trust: a provider decides who is signed in, and the admin consent dialog says so. Declare them in the manifest and set apiVersion: "1.4":

"pokerEnginePlugin": {
  "apiVersion": "1.4",
  "providerType": "acme-sso",
  "capabilities": ["auth:provider", "storage"]
}
MethodDescription
registry.auth.registerProvider(definition)Validates the definition with zod and registers it. Registering an id you already registered replaces it. Throws AUTH_PROVIDER_INVALID, AUTH_PROVIDER_ID_RESERVED, AUTH_PROVIDER_ID_TAKEN (another plugin holds the id) or AUTH_PROVIDER_LIMIT (20 providers per plugin). Providers are removed again when the plugin is rolled back, deactivated or deleted.
registry.auth.unregisterProvider(id)Removes a provider this plugin registered; false for any other id.
registry.auth.getCallbackUrl(id)The absolute callback URL, built from the Site URL setting, to show an admin what to enter at the identity provider (https://poker.example.com/api/v1/auth/external/<id>/callback).
registry.auth.verifyIdToken(token, { issuer, audience, jwksUri, nonce?, algorithms?, clockToleranceSeconds?, maxAgeSeconds?, requireSubject? })Verifies a JWT with core’s JWKS cache (10 minutes, refetch on an unknown kid; RS256 and ES256 only). Throws PROVIDER_RESPONSE_INVALID. For tokens that do not come through the redirect flow, such as native Apple sign-in and server notifications. exp, iat and sub are required, except: with maxAgeSeconds (1 to 604800) a token without exp is accepted and any token whose iat is older is refused; requireSubject: false accepts a token without sub (returned as ""). Apple’s server notifications need both: they carry no exp, and their sub is inside events.
registry.auth.reserveOnce(key, ttlSeconds)A cluster-wide replay guard: true the first time within the TTL, false after. The key is namespaced by plugin. It fails closed: if the store is unavailable it throws.
registry.auth.identities.unlinkByProviderUserId(providerId, providerUserId, reason)For a provider the plugin owns: the provider withdrew the identity (Apple consent revoked). Deletes it, revokes the player’s sessions, fires auth:identity:unlinked with by: 'provider'. If it was the player’s last credential the account stays and is recovered by password reset or an admin.
registry.auth.identities.updateEmail(providerId, providerUserId, email, emailVerified)For a provider the plugin owns. Updates the identity’s email, never User.email.
registry.auth.identities.setFirstCredentials(providerId, providerUserId, { expectedUserId, password, email? })API 1.4. For an identity the plugin created, belonging to expectedUserId, on an account without a password (not an admin): sets the first password and, when the account’s email is a .invalid placeholder, the first real email (unconfirmed, verification email sent). Fires auth:password:set. Prove the player controls the identity first (a fresh credential); a session alone is not enough. Throws IDENTITY_MISMATCH, PASSWORD_ALREADY_SET, EXTERNAL_AUTH_ADMIN_FORBIDDEN, VALIDATION_ERROR, CONFLICT.
registry.secrets.get / set / delete / list(prefix?)Encrypted per-plugin values with dynamic keys: key ^[a-zA-Z0-9:._-]{1,100}$, value up to 16 KB, 200 keys per plugin. Values never appear in any admin API response. Use it for secrets that do not fit one settings field, such as one client secret per instance of a multi-instance provider. A single secret is simpler as a password config field.

Two hooks round this out (see Server Hooks):

  • auth:external:profile (async filter, needs auth:provider): value ExternalIdentityInput, argument { provider }. Adjust a profile after mapProfile and before validation.
  • auth:identity:linked / auth:identity:unlinked actions, and the method (provider id) on auth:user:login and source on auth:user:registered.

Example: an OIDC provider plugin

A plugin that signs players in with one company identity provider ("Acme SSO"). The admin enters the issuer, the client ID and the client secret in the plugin’s Settings (Extensions › Plugins, then Settings on the Acme SSO row).

package.json:

{
  "name": "acme-sso",
  "version": "1.0.0",
  "type": "module",
  "main": "dist/server/index.js",
  "pokerEnginePlugin": {
    "apiVersion": "1.4",
    "providerType": "acme-sso",
    "displayName": "Acme SSO",
    "description": "Sign in with Acme SSO",
    "hasFrontend": false,
    "capabilities": ["auth:provider"],
    "configFields": [
      { "key": "issuer", "label": "Issuer URL", "type": "text", "required": true,
        "description": "e.g. https://sso.acme.example (discovery is read from /.well-known/openid-configuration)" },
      { "key": "clientId", "label": "Client ID", "type": "text", "required": true },
      { "key": "clientSecret", "label": "Client secret", "type": "password", "required": true },
      { "key": "enabled", "label": "Enabled", "type": "toggle", "default": true }
    ]
  }
}

src/server/index.ts:

import {
  defineOAuthProvider,
  definePlugin,
  settingsOf,
  type PluginRegistry,
} from '@poker-engine/plugin-sdk';

export const PROVIDER_ID = 'acme-sso';

/** The standard OIDC claims to a profile. `claims` were verified by core; userinfo fills the gaps. */
export function mapAcmeProfile(
  idTokenClaims: Record<string, unknown> | null,
  userinfo: Record<string, unknown> | null
) {
  const claims = { ...userinfo, ...idTokenClaims };
  const text = (value: unknown): string | null =>
    typeof value === 'string' && value.trim() !== '' ? value : null;
  if (!text(claims.sub)) {
    throw new Error('the id_token has no sub');
  }
  return {
    providerUserId: String(claims.sub),
    email: text(claims.email),
    emailVerified: claims.email_verified === true,
    displayName: text(claims.name),
    username: text(claims.preferred_username),
    avatarUrl: text(claims.picture)?.startsWith('https://') ? text(claims.picture) : null,
    locale: text(claims.locale),
  };
}

function buildProvider(registry: PluginRegistry, issuer: string) {
  const settings = settingsOf(registry);
  return defineOAuthProvider({
    kind: 'oidc',
    id: PROVIDER_ID,
    displayName: 'Acme SSO',
    issuer,
    scopes: ['openid', 'email', 'profile'],
    brand: { background: '#0b3d91', foreground: '#ffffff' },
    // Acme verifies every address its employees have, so core may believe email_verified.
    trustEmail: true,
    signupMode: 'auto',
    extraAuthorizeParams: { prompt: 'select_account' },
    // Read on every request, so toggling the setting hides the button without a restart.
    isEnabled: () => settings.boolean('enabled', true),
    // Read per flow, so a rotated secret works at once. The engine decrypts password fields.
    getClientCredentials: async () => ({
      clientId: await settings.string('clientId'),
      clientSecret: await settings.string('clientSecret'),
    }),
    mapProfile: async ({ idTokenClaims, userinfo }) => mapAcmeProfile(idTokenClaims, userinfo),
  });
}

/** Register when the settings are complete; unregister otherwise. */
async function sync(registry: PluginRegistry): Promise<void> {
  const settings = settingsOf(registry);
  const issuer = (await settings.string('issuer')).trim().replace(/\/+$/, '');
  const complete = issuer !== '' && (await settings.string('clientId')) !== '' && (await settings.string('clientSecret')) !== '';
  if (!complete) {
    registry.auth.unregisterProvider(PROVIDER_ID);
    return;
  }
  try {
    registry.auth.registerProvider(buildProvider(registry, issuer));
  } catch (error) {
    // A malformed issuer must not break activation or the settings save.
    registry.auth.unregisterProvider(PROVIDER_ID);
    registry.logger.warn(`${PROVIDER_ID} not registered: ${error instanceof Error ? error.message : String(error)}`);
  }
}

const plugin = definePlugin({
  async register(registry) {
    await sync(registry);
    registry.addAction('plugin:settings:saved', async (providerType) => {
      if (providerType === registry.providerType) {
        await sync(registry);
      }
    });
  },
});

export const { register } = plugin;
export default plugin;

What the admin does next: copy the callback URL (registry.auth.getCallbackUrl('acme-sso')) into the identity provider as the redirect URI, enter the issuer and client credentials, and press Test sign-in on the Login providers page (the test intent, which shows the mapped profile and writes nothing).

defineOAuthProvider is an identity function with a dev-time check: outside production it validates the definition with the same rules the engine applies when you register it (the id pattern, reserved ids, display name length, #rrggbb brand colours, a non-empty scope list, an issuer for oidc or both endpoints for oauth2, extraAuthorizeParams that do not override a reserved parameter), so a mistake fails in your unit test with the offending field named instead of when an admin activates the plugin.

An OAuth 2.0 provider without OIDC

oauth2 has no id_token, so mapProfile reads the userinfo (or calls fetchJson):

defineOAuthProvider({
  kind: 'oauth2',
  id: 'chatly',
  displayName: 'Chatly',
  authorizationEndpoint: 'https://chatly.example/oauth2/authorize',
  tokenEndpoint: 'https://chatly.example/api/oauth2/token',
  userinfoEndpoint: 'https://chatly.example/api/users/@me',
  scopes: ['identify', 'email'],
  tokenEndpointAuth: 'client_secret_post',
  trustEmail: false,
  isEnabled: async () => true,
  getClientCredentials: async () => ({ clientId, clientSecret }),
  async mapProfile({ userinfo, fetchJson }) {
    const me = (userinfo ?? (await fetchJson('https://chatly.example/api/users/@me'))) as {
      id: string; username: string; email?: string; verified?: boolean; avatar?: string;
    };
    return {
      providerUserId: me.id,
      username: me.username,
      email: me.email ?? null,
      emailVerified: me.verified === true,
      avatarUrl: me.avatar ? `https://cdn.chatly.example/avatars/${me.id}/${me.avatar}.png` : null,
    };
  },
});

Example: a credential provider plugin

A plugin that signs players in with a short-lived signed token minted by another application ("Portal"). The portal shares an HMAC key with the plugin; the player arrives at the poker site with ?token=..., a slot fill reads it and posts { credential: { token } } to POST /api/v1/auth/external/portal/credential.

The token is <sub>:<email>:<expiresAtSeconds>:<hmac> (the email has no colon, so : separates the parts safely). The signing key lives in registry.secrets (the admin page writes it with registry.secrets.set('signing-key', ...)).

import { createHmac, timingSafeEqual } from 'node:crypto';
import { defineCredentialProvider, definePlugin, type PluginRegistry } from '@poker-engine/plugin-sdk';

const PROVIDER_ID = 'portal';

function sign(key: string, payload: string): string {
  return createHmac('sha256', key).update(payload).digest('hex');
}

function buildProvider(registry: PluginRegistry) {
  return defineCredentialProvider({
    kind: 'credential',
    id: PROVIDER_ID,
    displayName: 'Portal',
    // No button: the plugin's slot fill signs the player in when the portal sends them here.
    button: false,
    platforms: ['web'],
    // The portal only issues tokens for verified addresses.
    trustEmail: true,
    signupMode: 'auto',
    provisioning: {
      // For a token without an email: an address that can never receive mail.
      placeholderEmail: (identity) => `portal_${identity.providerUserId.toLowerCase()}@portal.invalid`,
      usernamePrefix: 'portal_',
    },
    isEnabled: async () => (await registry.secrets.get('signing-key')) !== null,

    async verifyCredential(credential, ctx) {
      const key = await registry.secrets.get('signing-key');
      const token = credential.token;
      if (!key || typeof token !== 'string' || token.length > 512) {
        throw new Error('no key or no token');
      }
      const [sub, email, expires, signature] = token.split(':');
      if (!sub || signature === undefined) {
        throw new Error('malformed token');
      }
      // 1. Signature, compared in constant time.
      const expected = Buffer.from(sign(key, `${sub}:${email}:${expires}`), 'hex');
      const given = Buffer.from(signature, 'hex');
      if (expected.length !== given.length || !timingSafeEqual(expected, given)) {
        throw new Error('bad signature');
      }
      // 2. Freshness.
      if (!(Number(expires) > Date.now() / 1000)) {
        throw new Error('expired');
      }
      // 3. Single use across the whole cluster. A re-authentication (set a first password) may
      //    present the token the login just used, so skip the guard for it.
      if (ctx.intent !== 'reauth' && !(await registry.auth.reserveOnce(`token:${signature}`, 300))) {
        throw new Error('already used');
      }
      return {
        providerUserId: sub,
        email: email || null,
        emailVerified: Boolean(email),
      };
    },
  });
}

const plugin = definePlugin({
  register(registry) {
    registry.auth.registerProvider(buildProvider(registry));
  },
});
export const { register } = plugin;

Notes:

  • verifyCredential only proves who the credential belongs to. Whether that person gets an account, is asked to complete a profile, or is told to link first is core’s decision (see What happens to an identity).
  • Throw to refuse. The message is for your logs; the player sees a generic "credential is invalid or expired".
  • reserveOnce is what stops a stolen token from being replayed; a signature and an expiry alone do not.
  • The fill posts with mode: 'cookie' and hands the answer to engine.auth.continueExternalSignIn(data) (Client Toolkit), so 2FA, complete-profile and the link notice continue on the core screens. A provider without a button also has no core "Link" or "Set a password" button in Settings → Sign-in methods: give the player those actions in a settings.sections fill that posts intent: 'link' or intent: 'reauth' (session + CSRF) and continues the same way; reauth_ok opens the Sign-in methods password form. telegram-auth 2.0 is a complete example.

Testing

The test doubles

createTestRegistry() from @poker-engine/plugin-sdk/testing includes working doubles of registry.auth and registry.secrets, with the engine’s validation and error codes (they throw AuthProviderError, whose code is the engine’s):

import { createTestRegistry } from '@poker-engine/plugin-sdk/testing';
import { register } from '../server/index';

it('registers acme-sso once configured', async () => {
  const registry = createTestRegistry({
    providerType: 'acme-sso',
    settings: { issuer: 'https://sso.acme.example', clientId: 'cid', clientSecret: 'secret' },
  });
  await register(registry);
  expect(registry.test.providers.get('acme-sso')).toMatchObject({ kind: 'oidc', trustEmail: true });
  expect(registry.test.describeProvider('acme-sso')).toMatchObject({ button: true, platforms: ['web', 'mobile'] });
});
DoubleBehaviour
registry.auth.registerProvider(def) / unregisterProvider(id)Record into registry.test.providers (a Map by id). The same validation as the engine: AUTH_PROVIDER_INVALID (with the offending fields), AUTH_PROVIDER_ID_RESERVED, AUTH_PROVIDER_ID_TAKEN for an id in registry.test.foreignProviderIds (or createTestRegistry({ auth: { foreignProviderIds } })), AUTH_PROVIDER_LIMIT at 20. Registering an id again replaces it. unregisterProvider returns false for an id the plugin did not register.
registry.auth.getCallbackUrl(id)http://localhost/api/v1/auth/external/<id>/callback (createTestRegistry({ auth: { callbackOrigin } }) changes the origin).
registry.auth.reserveOnce(key, ttl)In-memory TTL set (follows vi.useFakeTimers()); registry.test.reservedKeys shows what is held.
registry.auth.verifyIdToken(token, options)Verifies against the keys in registry.test.idTokenKeys: signature, RS256 and ES256 only, iss, aud, exp, nbf, iat, nonce, and maxAgeSeconds / requireSubject like the engine. Throws PROVIDER_RESPONSE_INVALID. A claim set to undefined in signIdToken is left out, so exp: undefined signs a token without exp.
registry.test.signIdToken(claims, { key?, alg?, header?, tamper? })Signs a JWT with a generated key (created and trusted on first use). Fills iat and exp. tamper: true corrupts the signature; header overrides header fields. registry.test.addIdTokenKey('ES256', 'my-kid') adds a key; push { kid, alg, publicJwk } into idTokenKeys to trust an external key.
registry.auth.identities.*Record every call in registry.test.identityCalls. They act on identities added with registry.test.addIdentity(providerId, providerUserId, { email, emailVerified }) and return false for unknown ones. A provider the plugin does not own throws AUTH_PROVIDER_NOT_OWNED.
registry.secretsIn-memory store (createTestRegistry({ secrets: { key: 'value' } }), registry.test.secrets) with the engine’s key pattern, 16 KB value and 200-key limits (PluginSecretError, code VALIDATION_ERROR or PLUGIN_SECRET_LIMIT).

runTestMapProfile and runTestCredential

Unit-test mapProfile and verifyCredential the way core calls them, and get the validated ExternalIdentityInput back (text trimmed, email lower-cased, empty strings turned into null) or an AuthProviderError with the engine’s code:

import { runTestCredential, runTestMapProfile } from '@poker-engine/plugin-sdk/testing';

it('maps the claims', async () => {
  const identity = await runTestMapProfile(provider, {
    claims: { sub: 'u1', email: 'Ann@Example.com', email_verified: true, name: 'Ann' },
    // userinfo: { ... }, callbackParams: { user: '{"name":{"firstName":"Ann"}}' },
    // fetchJson: { 'https://api.example/me': { id: 7 } }      // a map or a function
  });
  expect(identity).toEqual({ providerUserId: 'u1', email: 'ann@example.com', emailVerified: true, displayName: 'Ann' });
});

it('rejects a profile without a subject', async () => {
  await expect(runTestMapProfile(provider, { claims: {} })).rejects.toMatchObject({ code: 'PROVIDER_RESPONSE_INVALID' });
});

it('refuses a forged credential', async () => {
  await expect(runTestCredential(credentialProvider, { token: 'forged' })).rejects.toMatchObject({ code: 'CREDENTIAL_INVALID' });
  // runTestCredential(def, credential, { intent: 'reauth', client: 'mobile', ip })  overrides the context
});
SituationCode
mapProfile throws, or returns an identity the engine would rejectPROVIDER_RESPONSE_INVALID
verifyCredential throwsCREDENTIAL_INVALID
verifyCredential returns an invalid identityPROVIDER_RESPONSE_INVALID
The provider throws an AuthProviderError itselfIts own code

runTestMapProfile needs an oidc or oauth2 definition; runTestCredential any definition with verifyCredential. Both skip isEnabled, redirects and the id_token check (core’s job; test that part with registry.auth.verifyIdToken and signIdToken).

Security model

What core guarantees

You do not have to implement any of this, and cannot weaken it:

  • PKCE (S256) on every redirect flow, a single-use state, a nonce for oidc, and a binding cookie that ties the callback to the browser that started it (the app’s own PKCE verifier for mobile). A callback from another browser, a replayed state or an expired flow is refused.
  • The id_token is always verified: signature against the issuer’s JWKS (RS256 or ES256 only, over https), iss, aud (your client ID), exp, iat skew and nonce. mapProfile only ever sees verified claims.
  • Redirect targets: the provider’s redirect_uri is built by core from the Site URL; returnTo must be a same-origin relative path; a mobile app redirect must be in an exact-match allowlist.
  • No provider tokens are stored or logged. Access and refresh tokens are used once and discarded. One-time codes and tickets are stored hashed, their payloads and PKCE verifiers encrypted. Logs never contain codes, tokens, the emails of unknown identities or credentials.
  • Outbound requests (discovery, JWKS, token, userinfo, fetchJson): https only outside development and test environments, 5 s timeout, 256 KB cap, no redirect to a non-https URL, and private and loopback addresses are blocked, because an admin can type an issuer.
  • Account rules: an email that matches an existing account never signs anyone in without that account’s password (and 2FA); admin accounts never sign in through a provider; every provider sign-in goes through the same blocked, frozen, approval, email-verification, rate-limit and 2FA checks as a password login; a player cannot remove their last credential; an admin unlink revokes sessions and is audited.
  • Icons: SVG is sanitised (no scripts, external references or event handlers) and capped at 8 KB.
  • Rate limits on start, callback, exchange and credential routes.
  • Capability checks: the registry methods work only with auth:provider, and registry.auth.identities.* only for providers the plugin registered.

What the provider must do

  • Return a stable providerUserId. Use the provider’s immutable subject (sub, the numeric id), never an email or a username that can change or be reassigned: the account is keyed on it.
  • Set trustEmail: true only when the provider verifies email addresses, and set emailVerified truthfully. Claiming emailVerified: true for an address the provider did not verify, with trustEmail on, hands the player a confirmed email that anyone could have typed. When unsure, leave trustEmail off: the player confirms the address instead.
  • Map defensively and keep mapProfile pure. No writes, no side effects, no calls to services other than the provider’s own profile endpoints through fetchJson. Drop fields you cannot trust instead of failing the sign-in, and never put a token in profile.
  • In verifyCredential, verify everything a credential claims: the signature (compare in constant time), the expiry or freshness window, the audience, and single use with registry.auth.reserveOnce for anything replayable. Throw on any doubt. Skip only the single-use check for reauth, which may present a credential the login just used.
  • Keep secrets out of definitions, logs and responses. Client secrets belong in password config fields (encrypted by the engine) or registry.secrets. Read them inside getClientCredentials() / verifyCredential() so a rotation applies at once. Do not log credentials, tokens or callbackParams.
  • Honour isEnabled(). Return false when the plugin is not configured; a half-configured provider must not appear on the login page.
  • Do not register more than you serve. Declare only the intents and platforms you support. A provider that cannot be linked afterwards should not list link.
  • Treat provider callbacks you receive yourself as untrusted input. If the plugin adds a webhook (Apple’s server-to-server notifications), verify the request’s signature (registry.auth.verifyIdToken) and its audience before calling registry.auth.identities.*, and use reserveOnce against replays.
  • Use a reserved domain for placeholder emails (.invalid), so no mail ever reaches a stranger.

Errors

Routes answer { success: false, error: { code, message } }. Codes a plugin author meets:

CodeStatusWhen
AUTH_PROVIDER_INVALID400The definition failed validation (thrown by registerProvider)
AUTH_PROVIDER_ID_RESERVED400The id is local or password
AUTH_PROVIDER_ID_TAKEN409Another plugin already registered the id
AUTH_PROVIDER_LIMIT400More than 20 providers in one plugin
AUTH_PROVIDER_NOT_OWNED403registry.auth.identities.* for a provider the plugin did not register
PROVIDER_NOT_FOUND / PROVIDER_DISABLED404 / 403Unknown provider, or isEnabled() returned false
PROVIDER_DENIED400The provider answered with an error (the player cancelled)
PROVIDER_ERROR502Token endpoint, discovery, JWKS or userinfo failed
PROVIDER_RESPONSE_INVALID502The id_token failed verification, or mapProfile / verifyCredential returned an invalid identity
CREDENTIAL_INVALID401verifyCredential threw
INTENT_NOT_ALLOWED403The provider does not list the intent, or the intent needs a session (link, reauth) or an admin (test)
FLOW_INVALID / FLOW_BINDING_MISMATCH400Unknown, used or expired flow; started in another browser
EXTERNAL_AUTH_NOT_LINKED403signupMode: 'link_only' and no linked account
EXTERNAL_AUTH_ADMIN_FORBIDDEN403The account is an admin
IDENTITY_ALREADY_LINKED / IDENTITY_PROVIDER_ALREADY_LINKED409The identity belongs to another account / the account already has this provider
IDENTITY_LAST_CREDENTIAL409Unlinking would leave the account with no way to sign in

The SDK exports ExternalAuthErrorCode (the union of every code), and the test doubles throw AuthProviderError carrying the same codes.

Try the live demo Pricing

Have questions about Poker Engine? We reply fast.