sign-in-with-solana / tree / src/siws.ts ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
/**
 * Sign in with Solana (Kognai seat SEAT9): the message, ed25519 verification, a replay guard and an allowlist.
 * Pure: no network, the clock and the seen nonce store are passed in. ed25519 comes from node:crypto.
 *
 * Message format (lines joined by "\n", no trailing newline; the statement block is optional):
 *   <domain> wants you to sign in with your Solana account:
 *   <address>
 *
 *   <statement>
 *
 *   URI: <uri>
 *   Version: 1
 *   Chain ID: <chainId>
 *   Nonce: <nonce>
 *   Issued At: <ISO 8601 UTC>
 *   Expiration Time: <ISO 8601 UTC>
 */
import { createPublicKey, verify as edVerify } from 'node:crypto';
import { base58Decode } from './base58.ts';

export interface MessageParams {
  domain: string; address: string; nonce: string; issuedAt: string; expirationTime: string;
  statement?: string; uri?: string; chainId?: string;
}
export interface Verdict { ok: boolean; reason: string; fields?: MessageParams }
/** Remembers nonces already used: a Set, or any store with has and add. */
export interface Seen { has(nonce: string): boolean; add(nonce: string): unknown }
export interface VerifyInput {
  message: string;
  /** 64 bytes: Uint8Array, base58 (Solana wallets), or base64 */
  signature: string | Uint8Array;
  address: string;
  allowlist: Iterable<string>;
  now: number;
  seen: Seen;
  /** the domain this server expects; required, a message for another domain is refused */
  domain: string;
}

export const VERSION = '1';
export const DEFAULT_CHAIN = 'mainnet';
export const MAX_LIFETIME_MS = 24 * 60 * 60_000;
const HEAD = ' wants you to sign in with your Solana account:';
const DOMAIN = /^[a-z0-9.-]+(:\d{1,5})?$/;
const NONCE = /^[A-Za-z0-9]{8,64}$/;
const CHAIN = /^[a-z0-9-]{1,32}$/;
const isIso = (s: unknown): s is string => typeof s === 'string' && Number.isFinite(Date.parse(s)) && new Date(Date.parse(s)).toISOString() === s;
const no = (reason: string): Verdict => ({ ok: false, reason });

/** A Solana address: base58 that decodes to exactly 32 bytes. */
export function isAddress(a: unknown): a is string {
  if (typeof a !== 'string' || a.length < 32 || a.length > 44) return false;
  const b = base58Decode(a);
  return b !== null && b.length === 32;
}

function checkParams(p: MessageParams): void {
  if (typeof p.domain !== 'string' || !DOMAIN.test(p.domain)) throw new Error('domain must be a lowercase host, with an optional port');
  if (!isAddress(p.address)) throw new Error('address must be a base58 Solana address');
  if (typeof p.nonce !== 'string' || !NONCE.test(p.nonce)) throw new Error('nonce must be 8 to 64 letters or digits');
  if (!isIso(p.issuedAt) || !isIso(p.expirationTime)) throw new Error('issuedAt and expirationTime must be ISO 8601 UTC times');
  const life = Date.parse(p.expirationTime) - Date.parse(p.issuedAt);
  if (life <= 0 || life > MAX_LIFETIME_MS) throw new Error('expirationTime must be after issuedAt, by at most 24 hours');
  if (p.statement !== undefined && (typeof p.statement !== 'string' || !p.statement || /\n/.test(p.statement))) throw new Error('statement must be one non empty line');
  if (p.uri !== undefined && (typeof p.uri !== 'string' || !/^https?:\/\/\S+$/.test(p.uri))) throw new Error('uri must be an http or https url');
  if (p.chainId !== undefined && (typeof p.chainId !== 'string' || !CHAIN.test(p.chainId))) throw new Error('chainId must be a short lowercase id such as mainnet');
}

export function createMessage(params: MessageParams): string {
  const p = { ...(params ?? ({} as MessageParams)) };
  checkParams(p);
  const uri = p.uri ?? `https://${p.domain}`;
  return [
    p.domain + HEAD, p.address, '',
    ...(p.statement ? [p.statement, ''] : []),
    `URI: ${uri}`, `Version: ${VERSION}`, `Chain ID: ${p.chainId ?? DEFAULT_CHAIN}`,
    `Nonce: ${p.nonce}`, `Issued At: ${p.issuedAt}`, `Expiration Time: ${p.expirationTime}`,
  ].join('\n');
}

/** Parses a message made by createMessage; returns null when it is not exactly that format. */
export function parseMessage(message: string): MessageParams | null {
  if (typeof message !== 'string') return null;
  const l = message.split('\n');
  if (l.length !== 9 && l.length !== 11) return null;
  if (!l[0].endsWith(HEAD) || l[2] !== '') return null;
  const tail = l.length === 11 ? l.slice(5) : l.slice(3);
  const field = (line: string, key: string) => (line.startsWith(key + ': ') ? line.slice(key.length + 2) : null);
  const [uri, ver, chain, nonce, iat, exp] = ['URI', 'Version', 'Chain ID', 'Nonce', 'Issued At', 'Expiration Time'].map((k, i) => field(tail[i], k));
  if (uri === null || ver !== VERSION || chain === null || nonce === null || iat === null || exp === null) return null;
  const p: MessageParams = { domain: l[0].slice(0, -HEAD.length), address: l[1], nonce, issuedAt: iat, expirationTime: exp, uri, chainId: chain };
  if (l.length === 11) { if (l[4] !== '') return null; p.statement = l[3]; }
  try { checkParams(p); } catch { return null; }
  return p;
}

function signatureBytes(sig: unknown): Uint8Array | null {
  if (sig instanceof Uint8Array) return sig.length === 64 ? sig : null;
  if (typeof sig !== 'string') return null;
  const b58 = base58Decode(sig);
  if (b58 && b58.length === 64) return b58;
  if (/^[A-Za-z0-9+/]{86}==$/.test(sig)) return new Uint8Array(Buffer.from(sig, 'base64'));
  return null;
}

export function verifyEd25519(message: string, signature: Uint8Array, address: string): boolean {
  const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: Buffer.from(base58Decode(address)!).toString('base64url') }, format: 'jwk' });
  return edVerify(null, Buffer.from(message, 'utf8'), key, signature);
}

export function verify(input: VerifyInput): Verdict {
  const { message, signature, address, allowlist, now, seen, domain } = input ?? ({} as VerifyInput);
  if (typeof domain !== 'string' || !domain) return no('no expected domain was given');
  if (!seen || typeof seen.has !== 'function' || typeof seen.add !== 'function') return no('no replay store was given');
  if (typeof now !== 'number' || !Number.isFinite(now)) return no('now must be milliseconds since the epoch');
  const p = parseMessage(message);
  if (!p) return no('the message is not a Sign in with Solana message');
  if (p.domain !== domain) return no(`the message is for ${p.domain}, not ${domain} (wrong domain)`);
  if (!isAddress(address) || address !== p.address) return no('the address does not match the message');
  if (now < Date.parse(p.issuedAt)) return no('the message is not valid yet');
  if (now >= Date.parse(p.expirationTime)) return no('the message expired');
  if (seen.has(p.nonce)) return no('the nonce was already used (replay)');
  const list = allowlist == null || typeof (allowlist as Iterable<string>)[Symbol.iterator] !== 'function' ? [] : [...allowlist];
  if (!list.includes(address)) return no('the address is not on the allowlist');
  const sig = signatureBytes(signature);
  if (!sig) return no('the signature is malformed');
  // node:crypto returns false (never throws) for a 32 byte key that is not a curve point; test A7 covers it
  if (!verifyEd25519(message, sig, address)) return no('the signature does not match the address');
  seen.add(p.nonce);
  return { ok: true, reason: 'signed in', fields: p };
}

agentgate-source: code mirror on Cloudflare Pages. All repos