跳到內容

登入認證工作階段

使用 D9 錢包完成使用者登入認證,並由後端驗證憑證後建立工作階段。

前置條件: 需自行提供兩個後端端點(本範例不包含伺服器端路由實作):

  • POST /api/auth/challenges — 產生登入 Challenge(第 1 步),持久化儲存後回傳給前端。
  • POST /api/auth/challenges/:requestId/consume — 對照已儲存的 Challenge 驗證 CACAO 認證憑證,以原子操作標記 Nonce 已使用並建立安全工作階段。驗證步驟詳見登入認證 (SIWX)。

缺少伺服器端驗證時不會建立任何有效登入狀態——僅有 Challenge 並不能證明使用者身分。

1. 在伺服器端產生 Challenge(server/challenge.ts)

Section titled “1. 在伺服器端產生 Challenge(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); // 有效期 5 分鐘
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.",
};
}

在 POST /api/auth/challenges 回傳該物件前,務必先寫入伺服器端儲存。

2. 在瀏覽器端發起登入(src/authenticate.ts)

Section titled “2. 在瀏覽器端發起登入(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. 向後端申請新的 Challenge
const issued = await fetch("/api/auth/challenges", {
method: "POST",
headers: { "Content-Type": "application/json" },
});
if (!issued.ok) throw new Error("Challenge 請求失敗");
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. 請求 D9 錢包簽署 SIWX 認證訊息
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("預期僅回傳一筆已核准的認證憑證");
}
// 3. 將 CACAO 憑證送交後端驗證
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("登入驗證失敗");
return yield* Effect.tryPromise(() => consumed.json());
})).pipe(Effect.ensuring(Effect.sync(hidePairing))),
);
}

由介面層傳入 showPairing(負責顯示 QR Code 與取消按鈕)及 hidePairing 回呼函式。

signIn 回傳後端回應,且使用者取得已認證的伺服器端工作階段。

錯誤訊息 處理方式
Challenge 請求失敗 檢查 POST /api/auth/challenges 端點是否正常回應。
預期僅回傳一筆已核准的認證憑證 使用者須在錢包彈窗中僅核准單一帳戶登入。
登入驗證失敗 後端拒絕了認證憑證,請對照登入認證 (SIWX)確認驗證流程,並檢查 Challenge 是否已過期或已被使用。