Skip to Content
OpenE2EEDocs

Custom-token identity

Bind Relay accounts to application members with signed ES256 assertions.

Reviewed: 2026-11-10.

Use this path when your backend authenticates application members. Your backend signs an assertion for the member from its verified server session. The OpenE2EE Signal Protocol Relay verifies that assertion before it registers a device.

Custom-token identity works in Sandbox and Production. Every environment, Production included, starts device-owned. Select a custom-token profile before the first device registers in that environment.

Configure an unused environment

  1. Open your Relay project, select Identity, and choose Sandbox or Production in the environment switcher.
  2. Find the matching Identity in Sandbox or Identity in Production card.
  3. Select Custom token from your backend (ES256).
  4. Enter the issuer, audience, subject claim, and public signing keys.
  5. Validate a fresh registration assertion for a test member.
  6. Save the configuration.
  7. Reload identity status to confirm the saved profile.

Initial selection requires an environment without account history. An in-use environment keeps its identity profile. See in-use environments. A missing response does not prove failure. Retry the same operation or reload its status. Cancel only before its configuration commits.

Keep private signing keys on your backend. The Console accepts only public JWKs. A public key has this shape:

{
  "kid": "inties-2026-10",
  "kty": "EC",
  "crv": "P-256",
  "x": "<base64url P-256 x coordinate>",
  "y": "<base64url P-256 y coordinate>"
}

Paste a JSON array of these keys into the form. Each coordinate encodes 32 bytes without padding. Each kid must be unique. The form accepts at most 32 keys.

Select stable identity values

FieldContract
IssuerAn exact HTTPS iss string that your backend signs. Keep it stable.
AudienceOne exact aud string for this environment. Keep Sandbox and Production audiences distinct. Arrays are invalid.
Subject claimUse sub for an immutable, non-reassigned member ID. A different claim requires the same stable mapping.
Signing keyA public P-256 JWK. Sign with ES256 and its configured kid.

Derive the member ID from the authenticated server session. Do not trust a member ID supplied by the client. Email addresses and display names can change. A matching email does not authorize account migration.

If one issuer serves more than one tenant or organization, make the subject unique across them. Sign a tenant-qualified value, for example JSON.stringify([tenantId, memberId]). Relay compares the subject as an exact string. Equal member IDs in different tenants then select different accounts. Do not change the encoding for an environment that is in use. See in-use environments.

The backend assertion signing key is separate from Signal identity keys and device authentication keys. Keep each key under its own storage contract.

An issuer or subject change can select a different Relay account. Signing-key rotation must preserve the issuer, mode, audience, and subject mapping.

Assertion contract

Return a compact signed JWT. Its protected header contains alg: "ES256", typ: "JWT", and a configured kid. External assertions cannot embed a key or supply jku, x5c, x5u, or crit.

ClaimRequired value
issThe configured issuer.
audThe configured audience string.
subThe authenticated member ID, when the configured subject claim is sub.
iat, nbf, expInteger Unix seconds. exp must exceed iat by at most 600 seconds.
jtiA nonempty assertion ID. Generate a fresh ID for each new assertion.
token_use"identity".
purposeThe requested operation: "register", "refresh", or "recover".
assurance"normal", "recent", or "step-up", supported by actual server authentication evidence.

Relay permits 30 seconds of clock tolerance. Keep the backend clock synchronized. The encoded assertion must not exceed 65,536 bytes.

The sample below signs five-minute assertions. It uses jose on a Node.js backend. The session argument must come from your application's server authentication. The client must never supply it.

The example defaults to Production. For Sandbox, set environment: 'sandbox' with its own publishable key and audience in trusted backend configuration. Do not select those values from the incoming request.

signal-relay-assertion-issuer.mjs
import { randomUUID } from 'node:crypto';
import { importJWK, SignJWT } from 'jose';

export async function createSignalProtocolRelayAssertionIssuer({
  privateJwk, kid, issuer, audience, publishableKey, environment = 'production',
  nowSeconds = () => Math.floor(Date.now() / 1000),
}) {
  if (environment !== 'sandbox' && environment !== 'production') {
    throw new Error('The configured Relay environment is invalid.');
  }
  const privateKey = await importJWK(privateJwk, 'ES256');
  const rank = { normal: 0, recent: 1, 'step-up': 2 };

  return async function issue(session, request) {
    if (session?.active !== true || typeof session.memberId !== 'string' || !session.memberId) {
      throw new Error('An active authenticated member is required.');
    }
    if (!request || request.environment !== environment ||
        request.publishableKey !== publishableKey ||
        !['register', 'refresh', 'recover'].includes(request.purpose)) {
      throw new Error('The Relay assertion request is invalid.');
    }
    const required = request.assurance ?? 'normal';
    if (typeof required !== 'string' || !Object.hasOwn(rank, required)) {
      throw new Error('Invalid assurance.');
    }
    const now = nowSeconds();
    const recent = (time) => Number.isSafeInteger(time) &&
      time <= now && now - time <= 300;
    const available = recent(session.secondFactorAtSeconds) ? 'step-up'
      : recent(session.authenticatedAtSeconds) ? 'recent' : 'normal';
    if (rank[available] < rank[required]) {
      throw new Error('Reauthentication is required.');
    }
    return new SignJWT({
      token_use: 'identity', purpose: request.purpose, assurance: required,
    })
      .setProtectedHeader({ alg: 'ES256', typ: 'JWT', kid })
      .setIssuer(issuer)
      .setAudience(audience)
      .setSubject(session.memberId)
      .setIssuedAt(now)
      .setNotBefore(now)
      .setExpirationTime(now + 300)
      .setJti(randomUUID())
      .sign(privateKey);
  };
}

Use the actual sign-in and second-factor times from server authentication. Refreshing an application token does not establish a recent sign-in. Do not copy requested assurance into a claim without checking that evidence.

The example considers authentication evidence recent for 300 seconds. This window is an example application policy. It does not define Relay's assertion lifetime or clock tolerance.

Create an authenticated application endpoint, such as /api/signal-relay-identity, that calls this function. It must check the server session and current member status on every request. Protect cookie-authenticated requests against cross-site request forgery. Return { "assertion": "<signed JWT>" } with Cache-Control: no-store. Do not log assertions or private keys.

A browser endpoint keeps its cross-site request forgery and Origin checks. A native endpoint authenticates the app's session credential from the Authorization bearer header. It refuses a request that carries only a cookie. See native apps.

Recovery also requires a configured Relay recovery policy. Relay refuses recovery without that policy or its required recent or step-up assurance. A valid recover assertion does not enable recovery.

For a real server-session integration, use the Better Auth recipe. Other authentication systems follow the backend identity contract. Their evidence levels and customer lifecycle limits remain explicit.

Connect the SDK callback

The SDK calls getIdentityAssertion(request) with the operation purpose, requested assurance, environment, and publishable key. This callback calls your authenticated application endpoint:

async function getIdentityAssertion(request) {
  const response = await fetch('/api/signal-relay-identity', {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(request),
    cache: 'no-store',
  });
  if (!response.ok) throw new Error('Application authentication is required.');
  const answer = await response.json();
  if (typeof answer.assertion !== 'string') throw new Error('Identity assertion missing.');
  return answer.assertion;
}

Pass this callback as hosted.getIdentityAssertion to createHostedSignalProtocolClient(). Use the selected environment's connection URL and persistent device storage. The hostedSignalProtocolRelaySandboxIdentity() helper cannot authenticate a custom-token profile.

Native apps (React Native and Expo)

A React Native or Expo app has no page origin, so a relative URL does not identify your backend. The app holds its own session credential for that backend. The callback below calls an absolute HTTPS endpoint. It sends the app's own session credential in an Authorization header:

signal-relay-identity-native-callback.mjs
export function createNativeIdentityCallback({ endpoint, getSessionToken }) {
  const url = new URL(endpoint);
  if (url.protocol !== 'https:') {
    throw new Error('The identity endpoint must use HTTPS.');
  }
  return async function getIdentityAssertion(request) {
    if (request.migration !== undefined) {
      throw new Error('Identity migration is not supported by this callback.');
    }
    const sessionToken = await getSessionToken();
    if (typeof sessionToken !== 'string' || !sessionToken) {
      throw new Error('Application authentication is required.');
    }
    const response = await fetch(url.href, {
      method: 'POST',
      credentials: 'omit',
      headers: {
        authorization: `Bearer ${sessionToken}`,
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        purpose: request.purpose,
        assurance: request.assurance,
        environment: request.environment,
        publishableKey: request.publishableKey,
      }),
    });
    if (!response.ok) throw new Error('Application authentication is required.');
    const answer = await response.json();
    if (typeof answer.assertion !== 'string') throw new Error('Identity assertion missing.');
    return answer.assertion;
  };
}

Read endpoint from trusted build configuration. Do not take it from a deep link, a push payload, or a server response. getSessionToken returns the app's current session credential for your backend. Pass the returned function as hosted.getIdentityAssertion to createHostedSignalProtocolClient().

Keep credentials: 'omit'. React Native implements fetch on its XMLHttpRequest, and the native networking layer attaches stored cookies unless credentials is 'omit'. The callback sends only the request fields that the issuer reads. It refuses a request with identity migration context, because an in-use environment keeps its identity profile.

Your native endpoint verifies the bearer session credential and the current member status on every request. It does not depend on the Origin header, because a native request has no page origin to check. Refuse a request without a valid bearer credential, including a request that carries only a cookie. Return { "assertion": "<signed JWT>" } with Cache-Control: no-store. Do not log session credentials or assertions.

Evidence level: a local docs test runs this exact callback with a stubbed fetch. No device test or hosted endpoint test covers it.

Verify the member binding

Test registration for two different members. Confirm that they receive different Relay accounts. Confirm that repeat authentication for the same member preserves its Relay account. Confirm that a registration from a second new store for the same member gets HTTP 409 DEVICE_LINK_REQUIRED. Confirm that a link from the first device adds that device. Reject a client-supplied ID for another member at your application endpoint.

Test disabled members, expired sessions, wrong issuer, wrong audience, unknown kid, changed subjects, and insufficient recovery assurance. The Console test checks one assertion against a draft. It does not test your endpoint's authorization rules or register a device.

A valid identity assertion does not restore lost private keys, sessions, or old message plaintext. See what identity does not do. Device-owned account-key loss has no provider sign-in recovery path.

Complete an encrypted exchange between test devices before member-device rollout. Keep Sandbox and Production storage separate.

Key rotation and revocation limits

The custom-token verifier uses configured public keys. It does not fetch a JWKS URL.

When your environment offers Signing keys, use that card to replace the complete public verification set. The initial identity form cannot replace an in-use identity.

  1. Add the new public key while you retain the old verification key.
  2. Confirm the exact key set in the correct environment.
  3. Start signing new assertions with the new key on your backend.
  4. Keep the old verification key until outstanding assertions expire, including clock tolerance.
  5. Remove the old key in a later confirmed change.

The replacement contains 1–32 public P-256 keys with unique key IDs. Keep private keys on your backend. The Console shows which IDs remain, which IDs enter the set, and which IDs leave it. A malformed key or duplicate ID cannot authorize a replacement.

For emergency removal, review every removed key before confirmation. After the replacement applies, new registrations and recoveries signed with a removed key fail. Key removal does not suspend an account or stop your application from issuing assertions.

Signing-key removal and assertion expiry do not revoke registered Relay devices. Those devices can renew Relay credentials with a device proof. Application logout does not revoke them either.

Use Account lifecycle to request suspension of an account or member. Stop issuing assertions for a suspended member in your application. Account recovery replaces encryption identity and starts an empty mailbox generation. Do not use recovery as an account-disable operation.

Anonymous sending capabilities can remain usable under their own lifetime and recipient or group policy. They do not carry a sender member identity for targeted cancellation. Attachment upload URLs, sender certificates and group tokens also retain their independent limits. Relay cannot recall content already downloaded or decrypted.

Interrupted changes

The Console retains a public change record before it sends a mutation. Keep the original record after a timeout, missing result, stale response or access failure. Retry the same original operation and public input. Do not create a replacement merely because a read cannot find the original.

A key cancellation has its own retained identifier beside the original replacement identifier. After a lost cancellation reply, retry that cancellation. A current configuration summary cannot prove the original operation's terminal result.

A lifecycle receipt describes the requested operation. Pending phases remain pending even when mailbox counts match. A converged status read can still require explicit same-ID continuation. Neither convergence nor a receipt acknowledgment certifies current account service, application membership or encrypted exchange.

The controls and their deployment checks do not certify your application. Complete registration, member-isolation and encrypted-exchange checks before member rollout. If required lifecycle or key controls are unavailable, keep registration paused until those operations and their limits pass your acceptance checks.

On this page