import { NETWORK } from './testnet.ts'; // Off-chain wallet <-> eom.dev account proof. Pure, shared by node and client so the // client builds the exact text it signs and never signs server-chosen text. export type LinkChallenge = { nonce: string; expiresAt: number }; export const LINK_NONCE = /^[A-Za-z0-9_-]{16,64}$/; export const LINK_CHALLENGE_MAX_MS = 10 * 60_000; export function linkMessage(c: { issuer: string; sub: string; address: string; nonce: string; expiresAt: number }): string { return JSON.stringify(['wikideck:account-link:v1', NETWORK, c.issuer, c.sub, c.address, c.nonce, c.expiresAt]); } /** Client side: validate a node challenge and build the message locally. Throws on anything unexpected. */ export function clientLinkMessage(account: { issuer: string; sub: string }, address: string, challenge: { nonce?: unknown; expiresAt?: unknown; message?: unknown }, now = Date.now()): string { const { nonce, expiresAt } = challenge; if (typeof nonce !== 'string' || !LINK_NONCE.test(nonce)) throw new Error('The node sent an invalid link challenge.'); if (typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || expiresAt <= now || expiresAt > now + LINK_CHALLENGE_MAX_MS) throw new Error('The node sent an invalid link challenge.'); if (!/^[a-f0-9]{64}$/.test(address)) throw new Error('Invalid wallet address.'); const message = linkMessage({ issuer: account.issuer, sub: account.sub, address, nonce, expiresAt }); if (challenge.message !== undefined && challenge.message !== message) throw new Error('The node asked the wallet to sign something other than an account link. Nothing was signed.'); return message; }