@xkova/browser
Call your XKOVA backend from a browser application. The client covers sign-in,
profiles, wallets, payments, and other account-holder features through your own
same-origin routes.
npm install @xkova/browser@alpha
import { createMemberClient } from '@xkova/browser';
const member = createMemberClient({ basePath: '/api/member' });
const session = await member.getSession();
if (session) {
const wallets = await member.listWallets();
if (wallets.length === 0) await member.ensureWalletProvisioning();
}
The client acts on the signed-in account holder.
Wallet setup and signing
Use the XKOVA API through your backend. Send the user to the XKOVA-hosted
wallet or signing page for the approved request and read the result from the
API when they return. The browser package provides the application transport
and session helpers.
Connect your backend
Implement the /api/member routes in your backend for frontend (BFF) with
@xkova/sdk@alpha. Its @xkova/sdk/member-bff entry point manages
session exchange, refresh, and logout. Installing the browser package does not
create routes or a session database.
The browser sends its application cookie. Before a mutation, the client fetches
a short-lived CSRF token from the BFF and sends it in X-XKOVA-Member-CSRF.
Your BFF must validate the exact Origin and bind the token to the session.
The fixed X-XKOVA-Member-Request header alone is not CSRF protection.
Keep API keys, provider proofs, XKOVA sessions, refresh tokens, and wallet
credentials on the server. The client accepts none of these, and it rejects
custom authorization headers. Your BFF resolves the acting member, selects the
configured asset and wallet, and checks permission for each operation. A
recipient or payer field identifies the other participant, never the caller.
Use the cookie helpers from @xkova/browser/server for host-only, Secure,
HttpOnly application cookies with SameSite=Strict. Implement the durable
store contracts from @xkova/sdk/member-bff. Serialize refresh and logout per
session across all BFF instances so two workers cannot reuse a rotating token.
Build the account screens
The client supports enrollment, profile and avatar changes, balances, history,
consents, data exports, verification, and wallet provisioning. Business methods
cover contacts, payment quotes and status, escrow reviews, payment requests,
deposits, withdrawals, bank transfers, and receiving QR codes. Check the
installed declarations for each method's inputs and results.
ensureWalletProvisioning() starts or resumes provisioning for the signed-in
member. It takes no body: wallet ownership, chain selection, and provider
registration belong to the BFF and XKOVA.
For an optional account, call getEnrollment() on page load. After the member
accepts your terms, call acceptEnrollment({ terms_version }). Your BFF binds
the route to its configured product and any sandbox welcome credit. Keep the
amount and token selection on the server. Show progress while status is
opening, enable account controls at active, and surface requires_review
without requesting another credit. Both methods accept an abort signal.
For transaction links, call transactionExplorerUrl(chainRef, transactionRef).
It returns a URL only for a supported explorer and a valid transaction hash.
Sign-in and security setup
Installing this package does not choose an identity provider. Your registered
application uses Hosted Auth, your OIDC provider, or a supported signed-launch
adapter. Confirm adapter support before enabling a provider's signed-launch
flow; never submit an unverified launch payload. Applications may also call
the same BFF routes with their own browser client.
Call getActionReadiness() before enabling signing controls. Keep controls
disabled while the request is pending or unavailable, and show any required
setup step. Readiness describes setup; each action still needs fresh approval.
Recheck after Account Center, credential changes, or session changes.
Account Center accepts security, sessions, and wallet_readiness intents.
Your BFF starts and completes the handoff with the SDK, validating the registered
origin, return URI, single-use state, and S256 PKCE. Applications using their
own OIDC provider continue to use that provider's account management and
step-up authentication.
Keep a review through reloads
For a send, escrow, withdrawal, or request payment, create one
createMemberActionReference() and keep it in the review URL. Save the input
with saveActionDraft(reference, input) before sending the person to security
setup. Restore it with getActionDraft(reference) when they return or reload.
Put only the reference in the URL, never amounts, recipients, or credentials.
On explicit approval, call authorizeActionDraft(reference). The BFF prepares
the resource and starts fresh authorization. Changed input with the same
reference is rejected. If a review has expired or is missing, ask the person
to check activity before starting a new review. Cancelling authorization does
not cancel an existing payment or sign the person out.
beginMemberAction() supports payment signing, escrow creation or cancellation,
and approval attestation. It validates the action, resource, and relative return
path. Your BFF uses the matching SDK methods to complete a Hosted passkey flow
or obtain a fresh proof from the registered OIDC provider. Provider proofs and
signing credentials must remain inaccessible to browser JavaScript.
Member panel on your own page
openXKOVAMemberAction from @xkova/browser/drawer shows a member action
(payment signing, escrow creation or cancellation, approval attestation) in an
XKOVA panel on your own page instead of a full-page redirect. It is opt-in:
nothing changes until you turn it on.
To turn it on:
- In the Console, on the member application, enable Embedded Presentation and
add your page's origin as an Embedding Origin (it must already be one of the
application's allowed origins).
- Allow both XKOVA panel origins in your page's Content-Security-Policy
frame-src. They are the two frame_origins your server receives (the
approval page, then the signing page), for example
frame-src https://member-login.xkova.com https://sign.xkova.com.
- In your server, call
beginMemberAction({ ..., presentation: 'embedded' })
from @xkova/sdk/member-bff. When the result has
presentation: 'embedded', return its drawer target to your page as is;
otherwise return authorizationUrl and redirect as today.
- In your page:
import { openXKOVAMemberAction } from '@xkova/browser/drawer';
const started = await fetch('/api/pay/authorize', { method: 'POST' }).then((r) => r.json());
if (!started.drawer) return location.assign(started.authorization_url);
const outcome = await openXKOVAMemberAction({ target: started.drawer, title: 'Approve Payment' });
if (outcome.kind === 'redirect_required') return startRedirectFlow(); // begin again with presentation: 'redirect'
if (outcome.kind === 'complete') await refreshPayment(outcome.resourceId); // read the result through your server
What the member sees: the panel slides in with your institution's branding,
the step ("Step 1 of 2"), the amount, recipient and network. Confirm with
Passkey opens a small XKOVA window for the passkey tap; it closes itself and
the panel continues with the signing step, then closes. The member never
leaves your page.
Approval passkeys: a member who added an approval passkey in Account Center
taps it inside the panel, with no window, only on browsers that can report
whether the panel is covered (Chrome, Edge and other Chromium browsers), and
only while the panel sees the whole review and the Confirm control fully
shown and uncovered. Everywhere else (Firefox, Safari, iPhone and iPad
browsers), and whenever part of the review is covered, cropped or scrolled
away, the panel uses the small XKOVA window, which repeats the review where
your page cannot draw; the action is never lost. XKOVA says per action whether
the in-panel tap is permitted (approvalTap: 'frame' on the target); the
panel then lets the XKOVA approval frame, and only it, use passkeys
(allow="publickey-credentials-get <approval origin>"). Setting approvalTap
yourself grants nothing beyond that frame permission: XKOVA accepts an
in-panel passkey only for an action it started that way, and never for an
application set to approve in a separate window.
Closing the panel hides it at once; its frame stays a moment (up to
closeGraceMs, 1.5 seconds) so it can end the action on XKOVA's side.
With the browser companion, ask for the panel first and the redirect after
redirect_required: authorizeActionDraft(reference, { presentation: 'embedded' }) and continuePayment(id, { presentation: 'embedded' }) send
{ presentation } as the JSON body and return MemberDraftAuthorizationStart:
today's MemberDraftAuthorization or MemberDraftEmbeddedAuthorization
({ presentation: 'embedded', drawer, return_path, resource }). Without the
option the request and result type are unchanged.
Fallback order. The panel first. If it never loads (for example your
frame-src does not allow the XKOVA origins), the panel offers Continue in a
New Window, which finishes the action in an XKOVA window. If a window is
blocked, or the member must sign in again, the outcome is redirect_required:
begin the action again from your server with presentation: 'redirect'. In a
mobile app's embedded web view (declare hostEnvironment: 'webview', or a
recognised in-app browser) the outcome is redirect_required at once; open
the redirect in the system browser.
What your page receives: progress (onStep, onWindow) and one outcome,
complete (with your own resource type and id), cancelled, failed (with a
reason) or redirect_required (with a reason). Never a code, session, passkey
result, signature or token, and never the XKOVA window. Always read the result
of the action through your server, as after a redirect; a completed panel
means the signature was submitted, not that the payment settled.
Members who sign in through their institution's own login always use the
redirect.
For local development only, the panel accepts http://localhost or
http://127.0.0.1 XKOVA origins when your page itself runs on a loopback
origin.
In-page drawer
openXKOVADrawer is the generic drawer the member panel and the XKOVA
Workspace Console are built on. Its contract:
- The drawer frames an XKOVA page whose URL and nonce your backend received,
and derives the frame origin from that URL. A target may list several exact
XKOVA
origins the frame moves between. It accepts a message only from that
frame window, at one of those origins, with that nonce, and posts only to
the origin of the frame's last valid message.
- The frame and your page exchange presentation events only (ready, step,
window, needs_popup, complete, cancelled, failed). No code, token, session,
signature or credential reaches your page.
- Panel and small window. A step that must run in a top-level window (some
passkey verifiers refuse a passkey made inside a frame) is opened by the
XKOVA frame itself, from the person's click inside the frame. Your page
never receives a reference to that window and never sees its messages; the
frame reports only
window with opened or closed (option onWindow),
and the drawer returns focus to itself when the window closes.
succeed(text) shows a short result line (for example "Approved.") and then
closes the drawer as complete (after resultDisplayMs, 1.2 seconds by
default).
- It is a modal dialog: the page is inert while it is open, focus stays inside
it and returns afterwards, and Close ends it as
cancelled.
- When the frame cannot be used, the drawer shows Continue in a New Window.
Its click opens an empty window, returned as
{ kind: 'popup', popup }; the
caller navigates that window to the address its backend returns for a
window presentation. A blocked window ends as { kind: 'redirect' }.
hostEnvironment: 'webview' (or a recognized in-app browser) never opens the
drawer.
Recover an unfinished payment
Open activity details with getPaymentRecovery(paymentId). Show Continue
Payment only when can_continue is true and Cancel Payment only when
can_cancel is true. An expired approval remains cancellable. A payment with
an accepted signature is processing and cannot be cancelled by the member.
On Continue, call continuePayment(paymentId) and navigate to its
authorization_url. On explicit cancellation confirmation, call
cancelPayment(paymentId) and render the returned state. Never recreate the
payment to resume it. Keep cancelled payments in history and distinguish them
from failed payments.
Implement these routes beneath the configured payments endpoint:
| Route |
Server operation |
GET /payments/:id/recovery |
Resolved resources.payments.recovery(id) |
POST /payments/:id/cancel |
Resolved resources.payments.cancelForMember(id) |
POST /payments/:id/continue |
Read recovery, then start a fresh member action for the existing payment |
Use the current server-held session for each request, including after a new
sign-in. Continue must preserve the payment's receipt destination and return to
its activity details if authorization is cancelled. Check status again after
a conflict or lost response; the browser client never retries a mutation.
Read-only polling can update an open dialog until a terminal state. Stop when
it closes and offer a retry if a read fails.
Wait for a result
waitForWalletReadiness, waitForPayment, waitForDeposit, and
waitForWithdrawal poll an existing operation. They accept an AbortSignal and
onUpdate, stop on HTTP errors, and never repeat a create request. A timeout
returns operation_pending; the outcome remains unknown. Abort polling when a
page unmounts. That stops observation, not the transaction.
waitForPayment, waitForDeposit and waitForWithdrawal resolve on the first
success or failure read and reject with operation_halted when the operation
needs an outside action, such as a staff review, instead of polling until the
timeout. A status this release does not know keeps the wait going; it is never
treated as success or failure.
A payment's success is provisional: a chain reorganization moves it to
failed. waitForPaymentOutcome, waitForDepositOutcome and
waitForWithdrawalOutcome return a typed result: succeeded (with final: false for a provisional success), failed, halted, or reversed when a
success was observed and then left. Pass finalityWindowMs to keep reading
after a provisional success:
const outcome = await member.waitForPaymentOutcome(paymentId, { finalityWindowMs: 60_000 });
if (outcome.kind === 'reversed') showNeedsReview(outcome.value);
operation_halted is a client-side MemberBffError code (its status is
0, because no HTTP request failed). It means the operation is waiting for an
outside action, such as a staff review; show its current status and do not
submit a duplicate. operation_pending means the polling window ended with the
outcome unresolved.
Resources your BFF relays may carry available_actions. That list names
operator actions for institution staff, not member actions; member cancel and
signing use the member operations. Ignore it in member interfaces, and ignore
values you do not know.
The package exports the same lifecycle helpers as @xkova/sdk: LIFECYCLES,
isTerminal, isSuccess, isKnownStatus, isProvisionalSuccess, isHalted,
statusOutcome and statusPresentation. Status fields are typed
KnownStatus | (string & {}). Adding a status value is a minor release;
removing or renaming one is a major release.