// Signing in with a wallet, and the two kinds of bearer token the API takes. // // challenge() a text for the wallet to sign (EIP-191 personal_sign). It costs nothing and sends nothing. // verifySignIn() checks the signature and gives a session token, good for 24 hours. // readSession() whose session a token is, or null. // newApiKey() a secret "idk_..." for a program; only its SHA-256 is ever stored. // // Nothing is stored for a sign-in. The nonce of a challenge is an HMAC of the address and of a 5-minute window, // so the server can rebuild the exact text it handed out and needs no write per visitor. A challenge is good for // 5 to 10 minutes; inside that time the same signature opens a session again, which gives nothing to someone who // does not already hold the signature. Only externally owned accounts can sign in (no EIP-1271 contract wallets). import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { getAddress, verifyMessage } from "ethers"; export const SESSION_MS = 24 * 3_600_000; export const CHALLENGE_WINDOW_MS = 5 * 60_000; const SESSION_PREFIX = "ids_"; export const API_KEY_PREFIX = "idk_"; const b64 = (buf) => Buffer.from(buf).toString("base64url"); const mac = (secret, text) => createHmac("sha256", secret).update(text).digest(); /** The address in lower case, or null when it is not one. */ export function normalAddress(a) { return typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a) ? a.toLowerCase() : null; } function challengeAt({ secret, address, windowStart, domain, chainId }) { const nonce = mac(secret, `challenge|${address}|${windowStart}`).subarray(0, 16).toString("hex"); const issuedAt = new Date(windowStart).toISOString(); const expiresAt = new Date(windowStart + 2 * CHALLENGE_WINDOW_MS).toISOString(); const message = [ `${domain} wants you to sign in with your wallet.`, "", `Address: ${getAddress(address)}`, `Chain ID: ${chainId}`, `Nonce: ${nonce}`, `Issued At: ${issuedAt}`, `Expires At: ${expiresAt}`, "", "Signing this message costs nothing and sends no transaction.", ].join("\n"); return { address, message, nonce, issuedAt, expiresAt }; } /** * @param {{secret:string, address:string, now:number, domain:string, chainId:number}} o `address` in lower case */ export function challenge(o) { return challengeAt({ ...o, windowStart: Math.floor(o.now / CHALLENGE_WINDOW_MS) * CHALLENGE_WINDOW_MS }); } /** * @returns {{ok:true, token:string, address:string, expiresAt:string} | {ok:false}} */ export function verifySignIn({ secret, address, signature, now, domain, chainId }) { if (typeof signature !== "string" || !/^0x[0-9a-fA-F]{130}$/.test(signature)) return { ok: false }; const current = Math.floor(now / CHALLENGE_WINDOW_MS) * CHALLENGE_WINDOW_MS; for (const windowStart of [current, current - CHALLENGE_WINDOW_MS]) { const { message } = challengeAt({ secret, address, windowStart, domain, chainId }); let signer = null; try { signer = verifyMessage(message, signature).toLowerCase(); } catch { signer = null; } if (signer === address) { const exp = now + SESSION_MS; return { ok: true, token: sessionToken(secret, address, exp), address, expiresAt: new Date(exp).toISOString() }; } } return { ok: false }; } export function sessionToken(secret, address, exp) { const body = b64(JSON.stringify({ a: address, e: exp })); return SESSION_PREFIX + body + "." + b64(mac(secret, "session|" + body)); } /** The address a session token belongs to, or null when the token is forged, damaged or expired. */ export function readSession(secret, token, now) { if (typeof token !== "string" || !token.startsWith(SESSION_PREFIX)) return null; const [body, sig, extra] = token.slice(SESSION_PREFIX.length).split("."); if (!body || !sig || extra !== undefined) return null; const want = mac(secret, "session|" + body); const got = Buffer.from(sig, "base64url"); if (got.length !== want.length || !timingSafeEqual(got, want)) return null; try { const { a, e } = JSON.parse(Buffer.from(body, "base64url").toString("utf8")); return normalAddress(a) === a && Number.isFinite(e) && now < e ? a : null; } catch { return null; } } export const hashApiKey = (secret) => createHash("sha256").update(String(secret)).digest("hex"); /** A new API key. `secret` is shown to its owner once; the state keeps `hash` and the first characters. */ export function newApiKey(random = randomBytes) { const secret = API_KEY_PREFIX + b64(random(32)); return { secret, hash: hashApiKey(secret), prefix: secret.slice(0, 10) }; }