Documentation / v1 / Quickstarts

First-party OTP and fresh receipts

Keep the API key and central tokens on your backend. Bind every fresh login to one protected browser attempt.

Download the tested server receipt example

Use the registered first-party session profile

This is an API-key-authenticated first-party login extension, not an OAuth code or token-exchange shortcut. Third-party apps and agents keep OAuth/DCR, exact redirects, PKCE, resources and consent. Register a backend-only public client in the same application/environment/directory as the key, enable the real OTP channel, and grant only the intended application resource.

A nonce-bound receipt requires explicitly registered openid. Only mode: session accepts nonce, client_id and environment_id. verification_only returns verified identity without tokens and forbids nonce. Existing nonce-free SDK calls omit the field and do not gain fresh authentication evidence.

Generate and keep one server-side nonce

Generate exactly 32 cryptographically random bytes, encoded as 43 canonical, unpadded base64url characters. Never accept a browser-chosen nonce, regenerate it between send and verify, or infer freshness from an existing access token. Noncanonical tail bits and padded, shortened or non-URL-safe strings are rejected by the SDK before transport.

Store the nonce together with app, client, environment, configured issuer/resource, normalized recipient, actual delivery channel, browser/preauthentication ownership, CSRF binding and expiry in your BFF attempt. Provider fallback can change the channel returned by send; verification must use that actual channel. The issuer rejects nonce absence/presence mismatches and cooldown rebinding.

Node BFF · typescript
import { randomBytes } from "node:crypto";
import { OtpClient } from "@beyondigital/auth-sdk";

// Server code only. Never send this API key to a browser or mobile app.
const otp = new OtpClient({ issuerUrl: "https://auth.example.com",
  apiKey: process.env.AUTH_APPLICATION_KEY });
const binding = { mode: "session" as const,
  clientId: "your-backend-only-client",
  environmentId: "33333333-3333-4333-8333-333333333333",
  nonce: randomBytes(32).toString("base64url") };
// Persist binding, recipient/app and CSRF/browser ownership in a short-lived
// server-side attempt BEFORE send. Reuse this exact nonce for resend/verify.
const sent = await otp.sendServerOtp({ ...binding,
  recipient: "+15550001234", app: "your-registered-app", channel: "sms" });
const login = await otp.verifyServerOtp({ ...binding,
  recipient: sent.phone, app: "your-registered-app",
  channel: sent.delivery_channel, otp: enteredCode });
if (!("access_token" in login) || !login.id_token) {
  throw new Error("Fresh login receipt missing. Start again.");
}
// Flat login.access_token / login.id_token / login.user, no token wrapper.
// Verify the signed receipt and consume the BFF attempt once before a cookie.
Python binding · python
import os
import secrets
from beyondigital_auth import AsyncOtpClient

# Keep this mapping only in the BFF's protected, expiring attempt store.
binding = {"mode": "session", "client_id": "your-backend-only-client",
           "environment_id": "33333333-3333-4333-8333-333333333333",
           "nonce": secrets.token_urlsafe(32)}
# send_server_otp(..., **binding) and verify_server_otp(..., **binding)
# use the same nonce, app and normalized recipient; use the actual returned channel.
otp = AsyncOtpClient("https://auth.example.com",
                     api_key=os.environ["AUTH_APPLICATION_KEY"])
# Verify signatures/issuer/client/resource/nonce/auth_time/amr/at_hash,
# then atomically consume the one-use attempt and create a new opaque BFF session.

Verify the receipt, not just its presence

The response stays flat: access_token, id_token, optional refresh_token and user. SDK transport validation can require the ID token to be present; it does not prove its signature or freshness. Use the tested server-side otp-receipt.mjs example with the actual SDK verifier exports.

Require the explicit signed type: id purpose claim for this new receipt; legacy typeless ID-token compatibility is insufficient. Verify the ID signature with trusted JWKS and RS256, exact issuer and client audience, expiry and the original nonce. Verify the access JWT separately for its issuer, expected client and the exact intended application resource. Require matching verified sub claims and the OIDC at_hash of the exact returned access-token bytes. The subject may be pairwise and need not equal user.id.

Require auth_time from the actual OTP-consumption event within the stored attempt and a configured maximum age such as 300 seconds, allowing only a deliberate clock skew. Require amr to contain otp and the expected actual channel. Never substitute iat, a refreshed token, a browser-reported MFA boolean or invented tenant claims. The registered client and immutable server attempt carry application/environment/directory binding.

Protect and consume the BFF attempt once

Before send, issue an expiring opaque HttpOnly/Secure preauthentication cookie and a separate unpredictable CSRF token bound to that attempt. Require the token in a header and an exact allowed Origin for send, resend and verify. CORS alone is insufficient. Keep client/resource/tenant selection out of browser-controlled mutation fields.

Use a transactional or compare-and-swap store for single-use completion. Commit attempt consumption and the new opaque BFF session together; rotate away from the preauthentication identifier. Keep central tokens server-side and apply the application’s own roles and object/tenant permissions. On timeout, lost verify response, browser cancellation or missing/invalid receipt, keep a durable cancellation job and reconcile the original nonce before discarding its protected binding or starting a replacement attempt. A local fetch abort cannot prove that the issuer did not mint a session.

Refresh rotates tokens but does not reset authentication freshness or create a fresh receipt. Preserve the original verified auth_time and method in the BFF session. This OTP receipt is not X-Auth-Proof and cannot approve console, credential, payment or control-plane actions that require a separate user-verified passkey proof.

Cancel and reconcile an uncertain attempt

POST /auth/otp/session/cancel authenticates only the original application API key with otp:verify. Send exactly app, client_id, the raw environment UUID and the original canonical nonce; no recipient, OTP, channel, tokens or session ID. The TypeScript, Python and Rust helpers validate transport input and require the literal cancelled acknowledgement. They do not retry automatically.

Persist a cancellation/outbox record before dropping an uncertain attempt. Retry the same four-field binding with the same original key until status: cancelled is acknowledged. Keep that key available while pending attempts are reconciled: a rotated replacement key cannot cancel an attempt issued by the previous key. Network errors, redirects, unsupported routes and missing acknowledgements remain unresolved, not cancelled.

Cancellation is idempotent even before send: the issuer records a tombstone that prevents later minting for that binding. If issuance won the race, cancellation revokes only that attempt’s newly issued OAuth session and refresh descendants, preserving unrelated existing sessions. It returns no credentials and provides no token recovery. Pending nonce attempts last at most 600 seconds; tombstones are retained at least one day with seven-day cleanup retention, and issued provenance remains through its refresh deadline.

Store only the minimum protected attempt/cancellation binding with a deliberate retention policy. This guide does not authorize repurposing an existing contact-containing login-attempt store or extracting customer data.

The service limits new nonce-attempt/tombstone storage per application over a 24-hour budget. OTP_SESSION_ATTEMPT_LIMIT_PER_DAY defaults to 10,000 and is configurable. A new nonce send or previously unknown cancellation can return 429 with Retry-After: 86400 when that budget is exhausted. Existing-attempt cancellation and idempotent retries consume no new slot and are not refused solely because the budget is exhausted; normal key and ownership checks still apply. Keep the durable cancellation binding and original key while waiting, rather than abandoning it or creating replacement nonces.

Do not automatically replay OTP verification after a timeout or lost response: issuance may already have succeeded. Reconcile that uncertain outcome through the same nonce-scoped cancellation job until acknowledged. Retry-After is not a cancelled acknowledgement, and the SDK does not automatically retry verify or cancellation.

Node cancellation worker · typescript
import { OtpClient } from "@beyondigital/auth-sdk";
const otp = new OtpClient({ issuerUrl: "https://auth.example.com",
  apiKey: process.env.AUTH_APPLICATION_KEY });
// Pass the ORIGINAL nonce loaded from the protected durable cancellation job.
async function reconcileCancellation(storedAttemptNonce: string) {
  const acknowledgement = await otp.cancelServerOtpSession({
    app: "your-registered-app", clientId: "your-backend-only-client",
    environmentId: "33333333-3333-4333-8333-333333333333",
    nonce: storedAttemptNonce,
  });
  if (acknowledgement.status === "cancelled") {
    // Atomically mark this durable job reconciled; retain required audit metadata.
  }
}
Python cancellation worker · python
# Use the same AsyncOtpClient configured with the ORIGINAL application key.
ack = await otp.cancel_server_otp_session(
    "your-registered-app", client_id="your-backend-only-client",
    environment_id="33333333-3333-4333-8333-333333333333",
    nonce=stored_attempt_nonce,
)
assert ack.status == "cancelled"
# Mark reconciled transactionally only after this acknowledgement.

Preserve existing Rust consumers

ServerOtpClient adds send_session_otp_with_nonce and verify_session_otp_with_nonce. Existing methods, OtpSessionBinding struct literals and OtpVerificationResponse variants remain unchanged. The new verifier method returns OtpSessionReceipt: receipt.session.access_token and receipt.id_token are Rust fields; serde keeps the wire JSON flat. ServerOtpClient::cancel_session_otp(app, binding, nonce) is additive too, returns OtpSessionCancellation, and requires the raw environment UUID for cancellation.

The SDKs pass no arbitrary requested resource/scope through OTP bodies. Receipt checks still require the configured client and application resource; see the generated SDK reference for exact signatures. These sources and examples do not imply that the new backend, provider routing, keys, registered client or SDK archives are already deployed.