Authenticated Session
Sign users in with D9 Wallet and issue a session from your backend.
Prerequisites: Two backend routes (not implemented in this snippet):
POST /api/auth/challenges— generates a challenge (step 1), stores it, and returns it to the browser.POST /api/auth/challenges/:requestId/consume— verifies the CACAO proof against the stored challenge, marks the nonce consumed atomically, and issues a secure session. Follow the verification rules in Sign-In (SIWX).
Without server-side verification, no user is authenticated: a challenge payload alone does not establish identity.
1. Create the challenge on the server (server/challenge.ts)
Section titled “1. Create the challenge on the server (server/challenge.ts)”import crypto from "node:crypto";import type { D9AuthenticateParams } from "@d9-network/dapp-connector/protocol";
export function createChallengePayload( appDomain: string, appUri: string, requestId: string,): D9AuthenticateParams { const now = new Date(); const expiresAt = new Date(now.getTime() + 5 * 60 * 1000); // valid for 5 minutes
return { domain: appDomain, uri: appUri, chains: ["d9net:000000000000000000000000000000d9"], nonce: crypto.randomBytes(16).toString("hex"), requestId, version: "1", type: "caip122", iat: now.toISOString().replace(/\.\d{3}Z$/, "Z"), exp: expiresAt.toISOString().replace(/\.\d{3}Z$/, "Z"), statement: "Sign in to My DApp.", };}Persist the challenge before returning it from POST /api/auth/challenges.
2. Sign in from the browser (src/authenticate.ts)
Section titled “2. Sign in from the browser (src/authenticate.ts)”import { Effect, Schema } from "effect";import { D9DAppConnector } from "@d9-network/dapp-connector";import { D9AuthenticateParamsSchema } from "@d9-network/dapp-connector/protocol";import { walletRuntime } from "./wallet";
export async function signIn( showPairing: (uri: string, cancel: () => Promise<void>) => void, hidePairing: () => void,) { // 1. Fetch a fresh challenge from your backend const issued = await fetch("/api/auth/challenges", { method: "POST", headers: { "Content-Type": "application/json" }, }); if (!issued.ok) throw new Error("Challenge request failed"); const rawChallenge = await issued.json();
return walletRuntime.runPromise( Effect.scoped(Effect.gen(function* () { const connector = yield* D9DAppConnector; const params = yield* Schema.decodeUnknownEffect(D9AuthenticateParamsSchema)(rawChallenge);
// 2. Request a SIWX signature from D9 Wallet const start = yield* connector.authenticate(params); showPairing(start.uri, () => walletRuntime.runPromise(start.cancel));
yield* Effect.forkScoped( start.walletConnected.pipe(Effect.andThen(Effect.sync(hidePairing))), ); const result = yield* start.response; const [auth] = result.auths; if (result.auths.length !== 1 || !auth) { throw new Error("Expected exactly one approved authentication"); }
// 3. Submit the CACAO proof to your backend for verification const consumed = yield* Effect.tryPromise(() => fetch(`/api/auth/challenges/${encodeURIComponent(params.requestId)}/consume`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cacao: auth }), }), ); if (!consumed.ok) throw new Error("Sign-in verification failed"); return yield* Effect.tryPromise(() => consumed.json()); })).pipe(Effect.ensuring(Effect.sync(hidePairing))), );}Provide showPairing (to render the QR code and cancel button) and hidePairing callbacks from your UI.
Verify
Section titled “Verify”signIn resolves to your backend’s response and establishes an authenticated session for the user.
Common errors
Section titled “Common errors”| Error | Resolution |
|---|---|
Challenge request failed |
Inspect your POST /api/auth/challenges endpoint. |
Expected exactly one approved authentication |
The user must approve exactly one account in the wallet prompt. |
Sign-in verification failed |
Your backend rejected the proof. Review Sign-In (SIWX) and check whether the challenge expired or was already consumed. |
