跳到內容

登入認證 (SIWX)

讓使用者在 D9 錢包中核准一次 CAIP-122 認證請求,隨後由後端驗證密碼學憑證並建立工作階段。整個流程於鏈下完成,不產生任何手續費。

前置條件: 已設定快速上手中的 walletRuntime,並具備可持久化儲存一次性 Challenge 的後端服務。

為每次登入嘗試產生全新的 Challenge,寫入資料庫後再回傳給前端:

欄位 說明
domain 精確的前端網域,例如 dapp.example.com
uri 精確的目標受眾 URI
chains ["d9net:000000000000000000000000000000d9"]
nonce 密碼學隨機、一次性的防重放字串(16–128 字元)
requestId 全新的 UUID
iat、exp 精確至秒的 ISO 8601 UTC 時間戳記;建議設定較短有效期(如 5 分鐘)
statement 顯示給使用者的純文字說明,清楚描述登入用途

將後端下發的 Challenge 傳入 requestWalletSignIn,函式會顯示配對介面、等待錢包核准並回傳單一 CACAO 認證憑證(auth):

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 requestWalletSignIn(
challengePayloadFromBackend: unknown,
showPairing: (uri: string, cancel: () => Promise<void>) => void,
hidePairing: () => void,
) {
return walletRuntime.runPromise(
Effect.scoped(Effect.gen(function* () {
const connector = yield* D9DAppConnector;
const params = yield* Schema.decodeUnknownEffect(D9AuthenticateParamsSchema)(
challengePayloadFromBackend,
);
const start = yield* connector.authenticate(params);
showPairing(start.uri, () => walletRuntime.runPromise(start.cancel));
// 錢包連線後立即關閉配對介面
yield* Effect.forkScoped(
Effect.gen(function* () {
yield* start.walletConnected;
yield* Effect.sync(hidePairing);
}),
);
const result = yield* start.response;
const [auth] = result.auths;
if (result.auths.length !== 1 || !auth) {
throw new Error("預期僅回傳一筆已核准的認證憑證");
}
return auth;
})).pipe(Effect.ensuring(Effect.sync(hidePairing))),
);
}

原樣將 auth POST 至後端端點。切勿信任前端另外傳入的帳戶位址——後端應直接從驗證通過的憑證中取得登入位址。

CACAO 憑證由三部分組成:

  • h:{ t: "caip122" }
  • p:domain、iss(did:pkh:d9net:...:<address>)、nonce、aud、exp、request_id 等負載欄位
  • s:簽章演算法(sr25519、ed25519 或 ecdsa)、十六進位簽章與公鑰

4. 驗證憑證並建立工作階段(後端)

Section titled “4. 驗證憑證並建立工作階段(後端)”

所有驗證皆須在伺服器端嚴格執行,切勿信任瀏覽器端提供的聲明:

  1. 依 nonce 與 request_id 查詢資料庫中的 Challenge,確認紀錄存在、未過期且尚未被使用。
  2. 以伺服器目前時間驗證 nbf <= now <= exp。
  3. 使用 @d9-network/dapp-connector/protocol 的 serializeD9SiwxMessage,依伺服器端儲存的 Challenge 重新組裝規範 SIWX 訊息。
  4. 對 <Bytes>${siwxMessage}</Bytes> 驗證簽章。
  5. 確認 s 中的公鑰與 p.iss 中的位址相符,該位址即為已認證的登入使用者。
  6. 在同一個原子資料庫交易中將 Challenge 標記為已使用,並核發工作階段 Cookie 或 Token,防止重放攻擊。
  • 首次送出有效憑證成功取得後端工作階段。
  • 重複送出同一憑證會在第 4.1 步遭到拒絕。

若錢包或連接器回傳錯誤,請參閱問題排查中的 authentication_* 錯誤碼。