x402-listing / tree / src/registry.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// Listing submissions: storage logic for the SQLite-backed Durable Object (registry-do.js). One record per paid
// submission under "s:<ref>". The storage arg is a DO storage (get/put/delete/list) or a test fake with the same shape.
// Lifecycle: pending_payment (handler ran, x402 not settled yet; never public) -> received (settled) -> approved |
// refund_pending (rejected, refund owed) -> refunded. "rejected" without refund only when the admin says no refund is owed.
import { TIERS, HOUR, DAY } from './tiers.js';

export const REF_RE = /^LST-[0-9A-HJKMNP-TV-Z]{10}$/;
const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; // Crockford base32
export function newRef() {
  const b = crypto.getRandomValues(new Uint8Array(10));
  return 'LST-' + Array.from(b, (x) => ALPHA[x & 31]).join('');
}
// Which admin actions may move a record from which status.
export const TRANSITIONS = {
  received: ['approved', 'refund_pending', 'rejected'],
  approved: ['received', 'refund_pending'],
  refund_pending: ['refunded', 'received'],
  rejected: ['received'],
  refunded: [],
};
const TX_RE = /^(0x[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,90})$/;
const PENDING_TTL = 10 * 60 * 1000;
const iso = (t) => (t ? new Date(t).toISOString() : null);

export class RegistryCore {
  constructor(storage) { this.s = storage; }
  key(ref) { return `s:${ref}`; }

  async create({ ref, tier, submission, now = Date.now() } = {}) {
    if (!REF_RE.test(String(ref)) || !TIERS[tier] || !submission) return { ok: false, reason: 'bad_request' };
    if (await this.s.get(this.key(ref))) return { ok: false, reason: 'exists' };
    const t = TIERS[tier];
    const rec = { ref, tier, amount: t.amount, status: 'pending_payment', submission, created: now, history: [{ at: now, status: 'pending_payment', by: 'system' }] };
    await this.s.put(this.key(ref), rec);
    return { ok: true, record: rec };
  }

  async confirm({ ref, payment, now = Date.now() } = {}) {
    const rec = await this.s.get(this.key(ref));
    if (!rec) return { ok: false, reason: 'not_found' };
    if (rec.status !== 'pending_payment') return { ok: true, record: rec, noop: true };
    const t = TIERS[rec.tier];
    rec.status = 'received';
    rec.payment = { network: payment?.network || null, transaction: payment?.transaction || null, payer: payment?.payer || null, amount: rec.amount, asset: 'USDC' };
    rec.paid_at = now;
    rec.review_by = now + t.reviewHours * HOUR;
    rec.history.push({ at: now, status: 'received', by: 'system', note: 'x402 payment settled' });
    await this.s.put(this.key(ref), rec);
    return { ok: true, record: rec };
  }

  async cancel({ ref } = {}) {
    const rec = await this.s.get(this.key(ref));
    if (rec && rec.status === 'pending_payment') await this.s.delete(this.key(ref));
    return { ok: true };
  }

  async get({ ref } = {}) {
    if (!REF_RE.test(String(ref))) return { ok: false, reason: 'not_found' };
    const rec = await this.s.get(this.key(ref));
    return rec ? { ok: true, record: rec } : { ok: false, reason: 'not_found' };
  }

  async list({ status, includePending = false, now = Date.now() } = {}) {
    const m = await this.s.list({ prefix: 's:' });
    const out = [];
    for (const rec of m.values()) {
      if (rec.status === 'pending_payment') {
        if (now - rec.created > PENDING_TTL) { await this.s.delete(this.key(rec.ref)); continue; } // never settled
        if (!includePending) continue;
      }
      if (status && rec.status !== status) continue;
      out.push(rec);
    }
    out.sort((a, b) => a.created - b.created);
    return { ok: true, records: out };
  }

  /** Admin: action = approved | rejected (-> refund_pending unless refund === false) | refund_pending | refunded | received */
  async setStatus({ ref, action, note, refund_tx, refund, public_note, featured_from, by = 'admin', now = Date.now() } = {}) {
    const rec = await this.s.get(this.key(ref));
    if (!rec || rec.status === 'pending_payment') return { ok: false, reason: 'not_found', http: 404 };
    let target = action;
    if (action === 'rejected') target = refund === false ? 'rejected' : 'refund_pending';
    if (!['approved', 'rejected', 'refund_pending', 'refunded', 'received'].includes(target)) return { ok: false, reason: 'bad_status', http: 400 };
    if (target === 'rejected' && !(typeof note === 'string' && note.trim())) return { ok: false, reason: 'note_required', message: 'A rejection without a refund needs a note saying why no refund is owed.', http: 400 };
    if (target === 'refunded' && !TX_RE.test(String(refund_tx || ''))) return { ok: false, reason: 'refund_tx_required', message: 'Set refunded only with refund_tx (the USDC refund transaction hash).', http: 400 };
    if (!TRANSITIONS[rec.status].includes(target)) return { ok: false, reason: 'bad_transition', message: `Cannot go from ${rec.status} to ${target}.`, http: 409 };
    const t = TIERS[rec.tier];
    rec.status = target; rec.updated = now;
    if (target === 'approved') {
      rec.decided_at = now;
      if (t.featuredDays) {
        const from = featured_from ? Date.parse(featured_from) : now;
        rec.featured_from = Number.isFinite(from) ? from : now;
        rec.featured_until = rec.featured_from + t.featuredDays * DAY;
      }
    }
    if (target === 'refund_pending' || target === 'rejected') { rec.decided_at = now; delete rec.featured_from; delete rec.featured_until; }
    if (target === 'refund_pending') rec.refund = { status: 'pending', to: rec.payment?.payer || null, network: rec.payment?.network || null, amount: rec.amount, asset: 'USDC', due_by: addBusinessDays(now, 3), needs: 'Crypto Money Maker OK before sending (swarm spending rule)' };
    if (target === 'refunded') rec.refund = { ...(rec.refund || {}), status: 'sent', tx: String(refund_tx), sent_at: now };
    if (target === 'received') { delete rec.decided_at; delete rec.featured_from; delete rec.featured_until; if (rec.refund && rec.refund.status !== 'sent') delete rec.refund; }
    if (typeof public_note === 'string') rec.public_note = public_note.trim().slice(0, 300) || undefined;
    rec.history.push({ at: now, status: target, by: String(by).slice(0, 40), ...(note ? { note: String(note).slice(0, 1000) } : {}), ...(refund_tx ? { refund_tx: String(refund_tx) } : {}) });
    await this.s.put(this.key(ref), rec);
    return { ok: true, record: rec };
  }
}

/** now + n business days (Mon-Fri, UTC), end of that day. */
export function addBusinessDays(t, n) {
  const d = new Date(t); let left = n;
  while (left > 0) { d.setUTCDate(d.getUTCDate() + 1); const w = d.getUTCDay(); if (w !== 0 && w !== 6) left--; }
  d.setUTCHours(23, 59, 59, 0);
  return d.getTime();
}

/** Public view: no email, no payer address, no internal notes or history details. */
export function publicView(rec, origin) {
  const t = TIERS[rec.tier];
  return {
    ref: rec.ref, status: rec.status, tier: rec.tier, tier_label: t.label, price_usd: (rec.amount / 1e6).toFixed(2),
    name: rec.submission.name, tool_url: rec.submission.tool_url, category: rec.submission.category,
    received_at: iso(rec.paid_at), review_by: iso(rec.review_by), decided_at: iso(rec.decided_at),
    ...(rec.featured_from ? { featured_from: iso(rec.featured_from), featured_until: iso(rec.featured_until) } : {}),
    ...(t.newsletter ? { newsletter: 'one mention once the newsletter has subscribers (none yet)' } : {}),
    payment: rec.payment ? { network: rec.payment.network, transaction: rec.payment.transaction } : null,
    ...(rec.refund ? { refund: { status: rec.refund.status, network: rec.refund.network, due_by: iso(rec.refund.due_by), ...(rec.refund.tx ? { transaction: rec.refund.tx } : {}) } } : {}),
    ...(rec.public_note ? { note: rec.public_note } : {}),
    status_url: `${origin}/v1/status/${rec.ref}`,
  };
}

/** Admin view: everything (email, payer, history), with ISO times. */
export function adminView(rec) {
  return {
    ...rec,
    created: iso(rec.created), paid_at: iso(rec.paid_at), review_by: iso(rec.review_by), decided_at: iso(rec.decided_at), updated: iso(rec.updated),
    featured_from: iso(rec.featured_from), featured_until: iso(rec.featured_until),
    price_usd: (rec.amount / 1e6).toFixed(2),
    refund: rec.refund ? { ...rec.refund, amount_usd: (rec.refund.amount / 1e6).toFixed(2), due_by: iso(rec.refund.due_by), sent_at: iso(rec.refund.sent_at) } : undefined,
    history: rec.history.map((h) => ({ ...h, at: iso(h.at) })),
  };
}

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