Compare commits
2 Commits
main
...
feat/state
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3f7b80ccf | ||
|
|
269992b8f3 |
@ -153,6 +153,12 @@ LICENSE_TOKEN_SECRET=settlekit-dev-license-secret
|
||||
# Dev default: settlekit-dev-auth-cookie-secret
|
||||
AUTH_COOKIE_SECRET=settlekit-dev-auth-cookie-secret
|
||||
|
||||
# HMAC secret used to sign proof-of-citation tokens (creator-dashboard +
|
||||
# citation-toll sidecar). MUST be set in production — if unset, the dashboard
|
||||
# falls back to a per-process random secret so a known constant is never shipped,
|
||||
# but proofs then won't verify across instances. Dev default: dev-citation-proof-secret
|
||||
CITATION_PROOF_SECRET=dev-citation-proof-secret
|
||||
|
||||
# --- API: runtime / identity --------------------------------------------------
|
||||
|
||||
# Static bootstrap Bearer key so the first authenticated call can mint real API
|
||||
|
||||
@ -3,10 +3,73 @@ import { detectGroundingForText } from "@/lib/data";
|
||||
|
||||
// Run reuse detection over the demo source corpus. The same call the
|
||||
// rsshub-citation-toll sidecar exposes at POST /attribution/detect.
|
||||
|
||||
// Cap the input: detection shingles the whole string, so an unbounded body is a
|
||||
// cheap CPU/memory DoS. Real agent answers are short — 20k chars is generous.
|
||||
const MAX_TEXT_LENGTH = 20_000;
|
||||
|
||||
// Fixed-window per-IP rate limit. This is an unauthenticated, CPU-bound endpoint,
|
||||
// so cap how often a single client can hit it. In-memory => per-instance only
|
||||
// (good enough for a single-node demo; front a shared store for multi-instance).
|
||||
const RATE_LIMIT = 30; // requests
|
||||
const RATE_WINDOW_MS = 60_000; // per minute
|
||||
|
||||
const hits = new Map<string, { count: number; resetAt: number }>();
|
||||
|
||||
function clientIp(request: Request): string {
|
||||
const fwd = request.headers.get("x-forwarded-for");
|
||||
if (fwd) return fwd.split(",")[0]!.trim();
|
||||
return request.headers.get("x-real-ip")?.trim() || "unknown";
|
||||
}
|
||||
|
||||
/** Returns null if allowed, or the seconds-until-reset if the client is limited. */
|
||||
function rateLimited(ip: string, now: number): number | null {
|
||||
const window = hits.get(ip);
|
||||
if (window === undefined || window.resetAt <= now) {
|
||||
hits.set(ip, { count: 1, resetAt: now + RATE_WINDOW_MS });
|
||||
return null;
|
||||
}
|
||||
if (window.count >= RATE_LIMIT) {
|
||||
return Math.ceil((window.resetAt - now) / 1000);
|
||||
}
|
||||
window.count++;
|
||||
return null;
|
||||
}
|
||||
|
||||
// Opportunistically evict stale windows so the map can't grow unbounded.
|
||||
function sweep(now: number): void {
|
||||
if (hits.size < 10_000) return;
|
||||
for (const [ip, window] of hits) {
|
||||
if (window.resetAt <= now) hits.delete(ip);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const now = Date.now();
|
||||
sweep(now);
|
||||
|
||||
const retryAfter = rateLimited(clientIp(request), now);
|
||||
if (retryAfter !== null) {
|
||||
return NextResponse.json(
|
||||
{ error: "rate limit exceeded" },
|
||||
{ status: 429, headers: { "retry-after": String(retryAfter) } },
|
||||
);
|
||||
}
|
||||
|
||||
const body = (await request.json().catch(() => null)) as { text?: string } | null;
|
||||
if (body === null || typeof body.text !== "string") {
|
||||
return NextResponse.json({ error: "text required" }, { status: 400 });
|
||||
}
|
||||
return NextResponse.json({ data: detectGroundingForText(body.text) });
|
||||
if (body.text.length > MAX_TEXT_LENGTH) {
|
||||
return NextResponse.json(
|
||||
{ error: `text too long (max ${MAX_TEXT_LENGTH} characters)` },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
return NextResponse.json({ data: detectGroundingForText(body.text) });
|
||||
} catch {
|
||||
return NextResponse.json({ error: "detection failed" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,6 +10,7 @@ export default function AttributionPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
eyebrow="Attribution"
|
||||
title="Reuse & proofs"
|
||||
description="The citation toll charges deliberate fetches. Attribution closes the loop — it detects when an agent's output was grounded in your work and charges that implicit reuse (RFB 6.01)."
|
||||
/>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,16 +1,33 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader, StatCard, StatGrid, StatusBadge } from "@/components/ui";
|
||||
import { DataTable, EmptyState, PageHeader, StatCard, StatGrid, StatusBadge } from "@/components/ui";
|
||||
import { getCreatorContext, type StatementLine } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc, formatDateTime } from "@/lib/format";
|
||||
import { addMoney, money } from "@settlekit/common";
|
||||
|
||||
function tierCell(depth: number) {
|
||||
if (depth === 0) return <span className="tier tier-author">Author</span>;
|
||||
return (
|
||||
<span className="tier tier-cite" style={{ paddingLeft: `${(depth - 1) * 12}px` }}>
|
||||
Citation · L{depth}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function StatementPage() {
|
||||
const ctx = getCreatorContext();
|
||||
const { totals, statement, me } = ctx;
|
||||
|
||||
// The foot nets exactly the lines printed on this statement — conserved to
|
||||
// the sub-cent, the way a real settlement statement balances.
|
||||
const netShown = statement.reduce((acc, l) => addMoney(acc, l.amount), money("0"));
|
||||
const period = statement.length > 0 ? formatDateTime(statement[0].createdAt) : "—";
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
eyebrow="Earnings"
|
||||
title="Statement"
|
||||
description={`Earnings for ${me.name} (${me.handle}) — your author share plus the recursive cut of everything that cites your work.`}
|
||||
description={`Your author share plus the recursive cut of everything that cites your work — every royalty line ${me.name} earned, printed as it settled.`}
|
||||
reference={{ label: "Statement ref", value: "SK-CR-0001" }}
|
||||
/>
|
||||
|
||||
<StatGrid>
|
||||
@ -21,33 +38,56 @@ export default function StatementPage() {
|
||||
<StatCard label="Sources" value={formatNumber(totals.sourcesAuthored)} hint="Works you authored" />
|
||||
</StatGrid>
|
||||
|
||||
<Card title="Recent royalty lines">
|
||||
<DataTable<StatementLine>
|
||||
rows={statement}
|
||||
getKey={(r) => `${r.accessId}-${r.depth}-${r.createdAt}`}
|
||||
columns={[
|
||||
{ header: "Posted", cell: (r) => <span className="mono">{formatDateTime(r.createdAt)}</span> },
|
||||
{ header: "Source", cell: (r) => r.sourceTitle },
|
||||
{
|
||||
header: "Tier",
|
||||
cell: (r) => (
|
||||
<span className="badge badge-neutral">{r.depth === 0 ? "Author" : `Citation · L${r.depth}`}</span>
|
||||
),
|
||||
},
|
||||
{ header: "Status", cell: (r) => <StatusBadge status={r.status} /> },
|
||||
{
|
||||
header: "Credit",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: "var(--good)", fontWeight: 600 }}>
|
||||
+{formatUsdc(r.amount.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No earnings yet" message="When agents cite your sources, royalty lines will print here." />}
|
||||
/>
|
||||
</Card>
|
||||
<section className="statement-doc" aria-label="Settlement statement of recent royalty lines">
|
||||
<div className="statement-doc-head">
|
||||
<div>
|
||||
<div className="statement-doc-title">Settlement Statement</div>
|
||||
<div className="statement-doc-sub">
|
||||
{me.name} · {me.handle} · arc · USDC ledger
|
||||
</div>
|
||||
</div>
|
||||
<div className="statement-doc-ref">
|
||||
Posted through
|
||||
<b>{period}</b>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="statement-doc-body">
|
||||
<DataTable<StatementLine>
|
||||
rows={statement}
|
||||
getKey={(r) => `${r.accessId}-${r.depth}-${r.createdAt}`}
|
||||
columns={[
|
||||
{ header: "Posted", cell: (r) => <span className="mono">{formatDateTime(r.createdAt)}</span> },
|
||||
{ header: "Source", cell: (r) => r.sourceTitle },
|
||||
{ header: "Tier", cell: (r) => tierCell(r.depth) },
|
||||
{ header: "Status", cell: (r) => <StatusBadge status={r.status} /> },
|
||||
{
|
||||
header: "Credit",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: "var(--good)", fontWeight: 600 }}>
|
||||
+{formatUsdc(r.amount.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No earnings yet" message="When agents cite your sources, royalty lines will print here." />}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{statement.length > 0 ? (
|
||||
<div className="statement-doc-foot">
|
||||
<span className="statement-doc-foot-label">
|
||||
Net on this statement · {statement.length} {statement.length === 1 ? "line" : "lines"}
|
||||
</span>
|
||||
<span className="statement-doc-total">+{formatUsdc(netShown.amount)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<p className="statement-note">
|
||||
Lines accrue per access and sweep into gas-free on-chain settlements — see Payouts for the batches.
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ export default function PayoutsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
eyebrow="Earnings"
|
||||
title="Payouts"
|
||||
description="Settled sweeps roll your accrued royalty lines into one gas-free on-chain settlement per batch."
|
||||
/>
|
||||
|
||||
@ -8,6 +8,7 @@ export default function WalletSettingsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
eyebrow="Account"
|
||||
title="Wallet"
|
||||
description="Your payout wallet is the rule that turns attribution into settlement. Map your identity once; every citation routes here."
|
||||
/>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader, StatusBadge } from "@/components/ui";
|
||||
import { Card, DataTable, EmptyState, PageHeader } from "@/components/ui";
|
||||
import { getCreatorContext, type SourceStat } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc } from "@/lib/format";
|
||||
|
||||
@ -10,6 +10,7 @@ export default function SourcesPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
eyebrow="Earnings"
|
||||
title="Sources"
|
||||
description="Your priced, citeable works — and the works you cite, which route a share back to their authors."
|
||||
/>
|
||||
@ -22,7 +23,15 @@ export default function SourcesPage() {
|
||||
{ header: "Title", cell: (r) => r.title },
|
||||
{ header: "Per-access toll", cell: (r) => <span className="mono">{formatUsdc(r.priceUsdc)}</span> },
|
||||
{ header: "Accesses", align: "right", cell: (r) => <span className="mono">{formatNumber(r.accesses)}</span> },
|
||||
{ header: "Cites", cell: (r) => (r.citesCount > 0 ? <StatusBadge status="active" /> : <span className="dim">—</span>) },
|
||||
{
|
||||
header: "Cites",
|
||||
cell: (r) =>
|
||||
r.citesCount > 0 ? (
|
||||
<span className="badge badge-neutral">routes {r.citesCount}</span>
|
||||
) : (
|
||||
<span className="dim">—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Earned by you",
|
||||
align: "right",
|
||||
|
||||
@ -15,8 +15,14 @@ export function Sidebar() {
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<span className="sidebar-logo">◆</span>
|
||||
<span>SettleKit · Creator</span>
|
||||
<span className="brand-mark" aria-hidden="true">
|
||||
SK
|
||||
</span>
|
||||
<span>
|
||||
SettleKit
|
||||
<br />
|
||||
<span className="sidebar-role">Creator Ledger</span>
|
||||
</span>
|
||||
</div>
|
||||
<nav className="sidebar-nav">
|
||||
{NAV_GROUPS.map((group) => (
|
||||
|
||||
@ -6,18 +6,31 @@ import type { ReactNode } from "react";
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
eyebrow,
|
||||
action,
|
||||
reference,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
/** Mono section label printed above the title (e.g. "Earnings"). */
|
||||
eyebrow?: string;
|
||||
action?: ReactNode;
|
||||
/** Optional document reference printed at the right (label + value). */
|
||||
reference?: { label: string; value: string };
|
||||
}) {
|
||||
return (
|
||||
<div className="page-header">
|
||||
<div>
|
||||
{eyebrow ? <div className="page-eyebrow">{eyebrow}</div> : null}
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{description ? <p className="page-desc">{description}</p> : null}
|
||||
</div>
|
||||
{reference ? (
|
||||
<div className="page-ref">
|
||||
{reference.label}
|
||||
<b>{reference.value}</b>
|
||||
</div>
|
||||
) : null}
|
||||
{action ? <div className="page-action">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
@ -33,7 +46,7 @@ export function Card({
|
||||
return (
|
||||
<section className="card">
|
||||
{title ? <h2 className="card-title">{title}</h2> : null}
|
||||
{children}
|
||||
<div className="card-body">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@ -16,6 +16,7 @@
|
||||
* renders. Swap this module for the Pg-backed stores to go live.
|
||||
*/
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import {
|
||||
type Money,
|
||||
addMoney,
|
||||
@ -328,29 +329,63 @@ export function getCreatorContext(): CreatorContext {
|
||||
/* Attribution worked example (real detectReuse + signed proof) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
const PROOF_SECRET = process.env.CITATION_PROOF_SECRET ?? "dev-citation-proof-secret";
|
||||
// Never ship a hard-coded signing secret. In dev a fixed string keeps proofs
|
||||
// reproducible; in production an unset secret falls back to a per-process random
|
||||
// one (forgery-proof) rather than a publicly-known constant.
|
||||
const PROOF_SECRET =
|
||||
process.env.CITATION_PROOF_SECRET ??
|
||||
(process.env.NODE_ENV === "production"
|
||||
? randomBytes(32).toString("hex")
|
||||
: "dev-citation-proof-secret");
|
||||
|
||||
/** A single grounding match, sanitized for the public detect endpoint. */
|
||||
export interface DetectedMatch {
|
||||
sourceId: string;
|
||||
title: string;
|
||||
score: number;
|
||||
matched: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
// The detect endpoint is unauthenticated, so build the comparison corpus once
|
||||
// (rebuilding it per request runs createSource hashing on every call — a cheap
|
||||
// amplification vector) and never carry author wallets into the response.
|
||||
interface DetectionCorpus {
|
||||
candidates: { id: string; text: string }[];
|
||||
titleById: Map<string, string>;
|
||||
priceById: Map<string, string>;
|
||||
}
|
||||
|
||||
let detectionCorpus: DetectionCorpus | null = null;
|
||||
|
||||
function getDetectionCorpus(): DetectionCorpus {
|
||||
if (detectionCorpus === null) {
|
||||
const all = buildRegistry().registry.all();
|
||||
detectionCorpus = {
|
||||
candidates: all.map((s) => ({ id: s.id, text: [s.title, s.summary, s.body].join(". ") })),
|
||||
titleById: new Map(all.map((s) => [s.id, s.title])),
|
||||
priceById: new Map(all.map((s) => [s.id, s.priceUsdc])),
|
||||
};
|
||||
}
|
||||
return detectionCorpus;
|
||||
}
|
||||
|
||||
/** Run reuse detection for arbitrary text against the demo source corpus. */
|
||||
export function detectGroundingForText(text: string): {
|
||||
grounded: boolean;
|
||||
matches: (ReuseMatch & { title: string })[];
|
||||
matches: DetectedMatch[];
|
||||
quoteUsdc: string;
|
||||
} {
|
||||
const { registry } = buildRegistry();
|
||||
const candidates = registry.all().map((s) => ({
|
||||
id: s.id,
|
||||
text: [s.title, s.summary, s.body].join(". "),
|
||||
wallet: s.authorWallet,
|
||||
}));
|
||||
const { candidates, titleById, priceById } = getDetectionCorpus();
|
||||
const report = detectReuse(text, candidates);
|
||||
const titleById = new Map(registry.all().map((s) => [s.id, s.title]));
|
||||
const matches = report.matches.map((m) => ({ ...m, title: titleById.get(m.sourceId) ?? m.sourceId }));
|
||||
const quote = sum(
|
||||
report.matches.map((m) => {
|
||||
const s = registry.get(m.sourceId);
|
||||
return s !== undefined ? money(s.priceUsdc) : money("0");
|
||||
}),
|
||||
);
|
||||
const matches: DetectedMatch[] = report.matches.map((m) => ({
|
||||
sourceId: m.sourceId,
|
||||
title: titleById.get(m.sourceId) ?? m.sourceId,
|
||||
score: m.score,
|
||||
matched: m.matched,
|
||||
total: m.total,
|
||||
}));
|
||||
const quote = sum(report.matches.map((m) => money(priceById.get(m.sourceId) ?? "0")));
|
||||
return { grounded: report.grounded, matches, quoteUsdc: quote.amount };
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user