cerberus-identity / tree / src/identity.ts ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
/**
 * Cerberus chamber 1: identity of a listed LAX agent.
 * createChallenge issues (did, listingId, nonce, issuedAt, expiresAt) and its exact message;
 * verifyChallenge checks the EIP-191 signature of the listing owner address over that message,
 * and refuses a tampered, expired, replayed or wrongly signed challenge. Pure: no network, clock injected.
 */
import { randomBytes } from 'node:crypto';
import { verifyMessage } from 'viem';
import type { Challenge, IdentityOptions, NonceStore, Verdict } from './types.ts';

export const MIN_TTL_MS = 60_000;
export const MAX_TTL_MS = 15 * 60_000;
export const DEFAULT_TTL_MS = 10 * 60_000;
export const HEADER = 'LAX identity challenge';

const DID = /^did:[a-z0-9]+:\S+$/;
const NONCE = /^[0-9a-f]{32,}$/;
const SIG = /^0x[0-9a-fA-F]{130}$/;
const ADDR = /^0x[0-9a-fA-F]{40}$/;

const no = (reason: string): Verdict => ({ ok: false, reason });
const isTime = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n);
const isIso = (s: unknown): s is string => typeof s === 'string' && Number.isFinite(Date.parse(s)) && new Date(Date.parse(s)).toISOString() === s;
const isId = (s: unknown): s is string => typeof s === 'string' && s.length > 0 && !/\s/.test(s);

/** Six lines joined by "\n", no trailing newline. */
export function challengeMessage(c: Pick<Challenge, 'did' | 'listingId' | 'nonce' | 'issuedAt' | 'expiresAt'>): string {
  return [HEADER, `did: ${c.did}`, `listing: ${c.listingId}`, `nonce: ${c.nonce}`, `issued: ${c.issuedAt}`, `expires: ${c.expiresAt}`].join('\n');
}

export function createIdentityChamber(opts: IdentityOptions = {}) {
  const ttl = opts.ttlMs ?? DEFAULT_TTL_MS;
  if (!isTime(ttl) || ttl < MIN_TTL_MS || ttl > MAX_TTL_MS) throw new Error('ttlMs must be between 1 and 15 minutes');
  const nonceOf = opts.randomNonce ?? (() => randomBytes(16).toString('hex'));
  const seen: NonceStore = opts.seen ?? new Set<string>();

  function createChallenge(input: { did: string; listingId: string; now: number }): Challenge {
    const { did, listingId, now } = input ?? ({} as never);
    if (typeof did !== 'string' || !DID.test(did)) throw new Error('did must be a DID');
    if (!isId(listingId)) throw new Error('listingId must be a non empty id without spaces');
    if (!isTime(now)) throw new Error('now must be milliseconds since the epoch');
    const nonce = nonceOf();
    if (!NONCE.test(nonce)) throw new Error('randomNonce must return at least 32 lowercase hex characters');
    const c = { did, listingId, nonce, issuedAt: new Date(now).toISOString(), expiresAt: new Date(now + ttl).toISOString() };
    return { ...c, message: challengeMessage(c) };
  }

  async function verifyChallenge(input: { challenge: Challenge; signature: string; ownerAddress: string; now: number }): Promise<Verdict> {
    const { challenge: c, signature, ownerAddress, now } = input ?? ({} as never);
    if (!c || typeof c !== 'object') return no('no challenge');
    if (typeof c.did !== 'string' || !DID.test(c.did) || !isId(c.listingId) || !NONCE.test(String(c.nonce)) || !isIso(c.issuedAt) || !isIso(c.expiresAt)) {
      return no('the challenge is malformed');
    }
    if (c.message !== challengeMessage(c)) return no('the challenge text does not match its fields (tampered)');
    const life = Date.parse(c.expiresAt) - Date.parse(c.issuedAt);
    if (life < MIN_TTL_MS || life > MAX_TTL_MS) return no('the challenge lifetime is not between 1 and 15 minutes');
    if (!isTime(now)) return no('now must be milliseconds since the epoch');
    if (now < Date.parse(c.issuedAt)) return no('the challenge is not valid yet');
    if (now >= Date.parse(c.expiresAt)) return no('the challenge expired');
    if (seen.has(c.nonce)) return no('the challenge was already used (replay)');
    if (typeof signature !== 'string' || !SIG.test(signature)) return no('the signature is malformed');
    if (typeof ownerAddress !== 'string' || !ADDR.test(ownerAddress)) return no('the owner address is malformed');
    const ok = await verifyMessage({ address: ownerAddress as `0x${string}`, message: c.message, signature: signature as `0x${string}` }).catch(() => false);
    if (!ok) return no('the challenge is not signed by the listing owner');
    seen.add(c.nonce);
    return { ok: true, reason: 'signed by the listing owner' };
  }

  return { createChallenge, challengeMessage, verifyChallenge };
}

const shared = createIdentityChamber();
/** Module level chamber with its own in memory replay guard, matching the kit's IdentityChamber. */
export const createChallenge = shared.createChallenge;
export const verifyChallenge = shared.verifyChallenge;

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