diff --git a/frontend/.env.example b/frontend/.env.example index 3832e30..f1d2700 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -5,14 +5,14 @@ # Where the verification API lives. Must be absolute: these reads also run in # server components, where a relative path has no origin to resolve against. # -# live testnet API https://api-sterish.jameshub.fun +# live testnet API https://api.sterish.xyz (canonical since STE-54) # local API http://localhost:8000 # fixtures, no API http://localhost:3000/api/mock # # The mock is served by this app itself and answers the read endpoints of # docs/api-spec.md with the four verdict cases, including WARNING and # UNAUDITED, which the live testnet registry does not currently hold. -NEXT_PUBLIC_API_URL=https://api-sterish.jameshub.fun +NEXT_PUBLIC_API_URL=https://api.sterish.xyz # Which Stellar network the wallet connects to, and which stellar.expert to # link at. The STE-13 contracts are on testnet. diff --git a/frontend/guides/ARCHITECTURE.md b/frontend/guides/ARCHITECTURE.md index 9924a0e..5d312b0 100644 --- a/frontend/guides/ARCHITECTURE.md +++ b/frontend/guides/ARCHITECTURE.md @@ -98,7 +98,7 @@ frontend/ │ ├── x402.ts buyer side of x402, lazily loaded │ ├── contentHash.ts content_hash v1 on WebCrypto │ ├── testnetSetup.ts Horizon account read, Friendbot, trustline - │ ├── tokens.ts licences read from the tokens contract (until STE-46) + │ ├── ownership.ts the STE-48 proof: challenge, signature, retry │ ├── artifact.ts save a delivered skill as one JSON file │ ├── fixtures.ts 4 verdict cases │ ├── mockApi.ts mock logic, outside app/ @@ -204,12 +204,17 @@ red-green colour-blind eyes. trustline to Circle's USDC, and the Circle faucet link. The trustline asset is checked by deriving its SAC address and comparing it with the 402's `asset`, because testnet is full of other tokens called USDC. None of it renders on a mainnet build. -- **Licences per address are read from the tokens contract (STE-47).** The API has no list - endpoint yet (STE-46), so `lib/tokens.ts` reads `total_supply` and then `get_token` for every - id, eight at a time, and keeps the `License` records owned by the address. `total_supply` is the - exact count and ids run from 1; a `TokenNotFound` (`Error(Contract, #2)`) is skipped, any other - failure throws, so an empty list only ever means "read, and holds nothing". Swap to the API - endpoint when STE-46 lands; the page already says the read is temporary. +- **A held licence has to be proved, not claimed (STE-48).** The free paths of `GET /use` answer + `401 OWNERSHIP_PROOF_REQUIRED` with a `challenge_url`. `lib/ownership.ts` fetches that exact URL, + has the wallet sign the `message` verbatim (SEP-43 `signMessage`, which is SEP-53), and repeats + the request with the nonce and signature. `requestSkillProving` wraps all of it, so the 401 is + part of the flow and never shown as a failure; a nonce is single use and short lived, so a proof + is built immediately before the request it belongs to. Paying is untouched: an x402 payment is + already signed by the payer. +- **Licences per address come from `GET /licenses` (STE-46).** STE-47 read the tokens contract from + the browser because no list endpoint existed; the API now builds it from the contract's own + enumeration, so a licence older than the RPC event window is still listed and `mint_tx` may be + null without the row disappearing. - **Wallet errors are classified by message, never by code.** The kit's `parseError` fills in `code: -1` for any error without one, so "Freighter is not connected" and a closed modal look the same by code. diff --git a/frontend/src/hooks/useLicences.ts b/frontend/src/hooks/useLicences.ts index 6e13a99..27e05d8 100644 --- a/frontend/src/hooks/useLicences.ts +++ b/frontend/src/hooks/useLicences.ts @@ -2,36 +2,42 @@ import { useQueries, useQuery } from "@tanstack/react-query"; -import { checkVersion } from "@/lib/api"; -import { isAccountAddress, readLicences, type Licence } from "@/lib/tokens"; +import { checkVersion, listLicenses } from "@/lib/api"; +import type { LicenseRecord } from "@/lib/types"; +import { isAccountAddress } from "@/utils/stellar"; /** - * Every licence an address holds, read from the tokens contract. + * Every licence an address holds, from `GET /licenses` (spec §3.10). * - * Not retried: a failed chain read has to surface as "could not read" rather - * than sit behind a silent retry, because the alternative a visitor would - * otherwise infer is "holds nothing". + * STE-47 read the tokens contract from the browser, id by id, because the API + * had no list. STE-46 gave it one, built from the contract's own enumeration + * rather than from events, so a licence older than the RPC event window is + * still listed. A failed chain read there is a 502, never a shorter list. + * + * Not retried: "could not read" has to surface promptly, because the wrong + * conclusion to draw from a slow failure is "this address holds nothing". */ export function useLicences(address: string) { return useQuery({ queryKey: ["licences", address], - queryFn: () => readLicences(address), + queryFn: () => listLicenses(address), enabled: isAccountAddress(address), retry: false, }); } /** - * The current verdict of each licensed version, one chain read per version. + * The current verdict of each licensed version, one read per version. * - * Read per version on purpose. A licence says what was bought; the verdict can - * have changed since, and that change is the reason this page exists. + * Deliberately separate: `/licenses` joins in no verdict, and that is the + * point. A licence says what was bought; the verdict can have changed since, + * and that change is the reason this page exists. */ -export function useLicenceVerdicts(licences: Licence[]) { +export function useLicenceVerdicts(licences: LicenseRecord[]) { return useQueries({ queries: licences.map((licence) => ({ - queryKey: ["check", licence.skillId, licence.version], - queryFn: () => checkVersion(licence.skillId, licence.version), + queryKey: ["check", licence.skill_id, licence.version], + queryFn: () => checkVersion(licence.skill_id, licence.version), retry: false, })), }); diff --git a/frontend/src/hooks/usePurchase.ts b/frontend/src/hooks/usePurchase.ts index 8dfbe67..c087dd8 100644 --- a/frontend/src/hooks/usePurchase.ts +++ b/frontend/src/hooks/usePurchase.ts @@ -4,6 +4,11 @@ import { useQueryClient } from "@tanstack/react-query"; import { useCallback, useRef, useState } from "react"; import { ApiError, requestSkill, type UseOutcome } from "@/lib/api"; +import { + describeProofFailure, + requestSkillProving, + type ProofFailure, +} from "@/lib/ownership"; import { queryKeys } from "@/lib/queryClient"; import type { PaymentRequired, PaymentRequirement } from "@/lib/types"; import { @@ -33,14 +38,15 @@ export type PurchaseState = /** Base units, null when the read failed, undefined while it is running. */ balance: bigint | null | undefined; } + | { step: "proving" } | { step: "signing"; requirement: PaymentRequirement } | { step: "settling"; requirement: PaymentRequirement } | { step: "granted"; outcome: Extract } | { step: "failed"; - error: ApiError | PaymentFailure; + error: ApiError | PaymentFailure | ProofFailure; /** Where it failed. After a signature, money may have moved. */ - after: "request" | "signature" | "payment"; + after: "request" | "signature" | "payment" | "proof"; }; export function usePurchase( @@ -71,7 +77,12 @@ export function usePurchase( inFlight.current = true; setState({ step: "requesting" }); try { - const outcome = await requestSkill(skillId, version, { agent }); + // The free paths need an ownership proof since STE-48, and the 401 that + // asks for one is part of the flow rather than a failure to report. + const outcome = await requestSkillProving(skillId, version, { + agent, + onProving: () => setState({ step: "proving" }), + }); if (outcome.kind === "granted") { setState({ step: "granted", outcome }); refreshLicence(); @@ -105,8 +116,16 @@ export function usePurchase( : current, ); } catch (cause) { - if (!(cause instanceof ApiError)) throw cause; - setState({ step: "failed", after: "request", error: cause }); + if (cause instanceof ApiError && cause.status !== 401) { + setState({ step: "failed", after: "request", error: cause }); + return; + } + // A refused or unsigned proof: the wallet's own words, not an API error. + setState({ + step: "failed", + after: "proof", + error: describeProofFailure(cause), + }); } finally { inFlight.current = false; } diff --git a/frontend/src/lib/api.paid.test.ts b/frontend/src/lib/api.paid.test.ts index c894d8b..11a5634 100644 --- a/frontend/src/lib/api.paid.test.ts +++ b/frontend/src/lib/api.paid.test.ts @@ -1,6 +1,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { ApiError, getLicense, requestSkill } from "./api"; +import { + ApiError, + getLicense, + getOwnershipChallenge, + listLicenses, + requestSkill, +} from "./api"; /** * The client half of the paid path. What is under test is mostly one @@ -223,6 +229,95 @@ describe("requestSkill with a payment", () => { }); }); +describe("the 401 that asks for an ownership proof", () => { + it("keeps the challenge_url the API pointed at", async () => { + respond( + Response.json( + { + error: "OWNERSHIP_PROOF_REQUIRED", + detail: "prove you control it", + challenge_url: "https://api.sterish.xyz/use/x/1/challenge?agent=G", + }, + { status: 401 }, + ), + ); + const error = (await requestSkill("x", "1", { agent: AGENT }).catch( + (cause: unknown) => cause, + )) as ApiError; + expect(error.status).toBe(401); + expect(error.challengeUrl).toBe( + "https://api.sterish.xyz/use/x/1/challenge?agent=G", + ); + }); + + it("leaves challengeUrl null on errors that carry none", async () => { + respond( + Response.json({ error: "NOT_VERIFIED", detail: "no" }, { status: 403 }), + ); + const error = (await requestSkill("x", "1", { agent: AGENT }).catch( + (cause: unknown) => cause, + )) as ApiError; + expect(error.challengeUrl).toBeNull(); + }); + + it("sends the proof headers when it has them", async () => { + const spy = respond(Response.json({ "SKILL.md": "# x" })); + await requestSkill("x", "1", { + agent: AGENT, + proof: { nonce: "n".repeat(32), signature: "sig" }, + }); + const headers = spy.mock.calls[0][1]?.headers as Record; + expect(headers["X-STERISH-PROOF-NONCE"]).toBe("n".repeat(32)); + expect(headers["X-STERISH-PROOF-SIGNATURE"]).toBe("sig"); + }); +}); + +describe("getOwnershipChallenge", () => { + it("fetches exactly the URL it was given", async () => { + const spy = respond(Response.json({ nonce: "abc", message: "m" })); + const url = "https://api.sterish.xyz/use/x/1/challenge?agent=G"; + await getOwnershipChallenge(url); + expect(String(spy.mock.calls[0][0])).toBe(url); + expect(spy.mock.calls[0][1]?.cache).toBe("no-store"); + }); + + it("throws an ApiError when the challenge is refused", async () => { + respond( + Response.json( + { error: "INVALID_AGENT", detail: "not a G account" }, + { status: 400 }, + ), + ); + const error = (await getOwnershipChallenge("https://api/x").catch( + (cause: unknown) => cause, + )) as ApiError; + expect(error).toBeInstanceOf(ApiError); + expect(error.code).toBe("INVALID_AGENT"); + }); +}); + +describe("listLicenses", () => { + it("asks for one agent's licences", async () => { + const spy = respond( + Response.json({ agent: AGENT, licenses: [], total: 0 }), + ); + await listLicenses(AGENT); + const url = String(spy.mock.calls[0][0]); + expect(url).toContain("/licenses?"); + expect(url).toContain(`agent=${AGENT}`); + }); + + it("throws on a failed chain read rather than reporting an empty list", async () => { + respond( + Response.json( + { error: "RPC_UNAVAILABLE", detail: "rpc down" }, + { status: 502 }, + ), + ); + await expect(listLicenses(AGENT)).rejects.toBeInstanceOf(ApiError); + }); +}); + describe("getLicense", () => { it("asks about one agent and one version", async () => { const spy = respond( diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 26d9b50..6e44217 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -11,7 +11,9 @@ import type { ApiErrorCode, FeedResponse, Health, + LicenseList, LicenseStatus, + OwnershipChallenge, PaymentRequired, SettlementReceipt, SkillArtifact, @@ -26,7 +28,7 @@ import { decodePaymentRequired, decodeSettlementReceipt } from "./x402"; * components too, where a relative path has no origin to resolve against. */ export const API_BASE_URL = ( - process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000" + process.env.NEXT_PUBLIC_API_URL ?? "https://api.sterish.xyz" ).replace(/\/+$/, ""); /** @@ -56,6 +58,11 @@ export class ApiError extends Error { readonly code: ApiErrorCode | string | null; readonly detail: string; readonly url: string; + /** + * Where to fetch an ownership challenge, carried by a 401 from the paid path + * (spec §3.7). Kept as the API gave it so no client ever builds that URL. + */ + readonly challengeUrl: string | null; constructor(args: { message: string; @@ -63,6 +70,7 @@ export class ApiError extends Error { code: ApiErrorCode | string | null; detail: string; url: string; + challengeUrl?: string | null; }) { super(args.message); this.name = "ApiError"; @@ -70,6 +78,7 @@ export class ApiError extends Error { this.code = args.code; this.detail = args.detail; this.url = args.url; + this.challengeUrl = args.challengeUrl ?? null; } /** True when the API was never reached, so retrying may genuinely help. */ @@ -133,12 +142,17 @@ async function errorFrom(response: Response, url: string): Promise { // exception that hides the real status code. const body: unknown = await response.json().catch(() => null); const parsed = isErrorBody(body) ? body : null; + const challengeUrl = + typeof (body as { challenge_url?: unknown })?.challenge_url === "string" + ? (body as { challenge_url: string }).challenge_url + : null; return new ApiError({ message: parsed?.detail ?? `The API answered ${response.status}`, status: response.status, code: parsed?.error ?? null, detail: parsed?.detail ?? response.statusText, url, + challengeUrl, }); } @@ -262,11 +276,20 @@ export type UseOutcome = export async function requestSkill( skillId: string, version: string, - opts: { agent: string; payment?: string }, + opts: { + agent: string; + payment?: string; + /** An ownership proof (spec §3.7). Required by the free paths since STE-48. */ + proof?: { nonce: string; signature: string }; + }, ): Promise { const path = `/use/${encodeURIComponent(skillId)}/${encodeURIComponent(version)}`; const headers: Record = { "X-AGENT-ADDRESS": opts.agent }; if (opts.payment) headers["X-PAYMENT"] = opts.payment; + if (opts.proof) { + headers["X-STERISH-PROOF-NONCE"] = opts.proof.nonce; + headers["X-STERISH-PROOF-SIGNATURE"] = opts.proof.signature; + } let sent: { response: Response; url: string }; try { @@ -323,3 +346,46 @@ export async function requestSkill( artifact: (await response.json()) as SkillArtifact, }; } + +/** + * Spec §3.7 step 1: a single-use message for `agent` to sign. + * + * Takes the absolute `challenge_url` the 401 carried rather than building a + * path, so the client never has to know the shape of that URL or which host + * serves it. + */ +export async function getOwnershipChallenge( + challengeUrl: string, +): Promise { + let response: Response; + try { + response = await fetch(challengeUrl, { + cache: "no-store", + signal: AbortSignal.timeout(TIMEOUT_MS), + headers: { accept: "application/json" }, + }); + } catch (cause) { + throw new ApiError({ + message: "Could not ask the API for an ownership challenge", + status: 0, + code: null, + detail: cause instanceof Error ? cause.message : String(cause), + url: challengeUrl, + }); + } + if (!response.ok) throw await errorFrom(response, challengeUrl); + return (await response.json()) as OwnershipChallenge; +} + +/** Spec §3.10. Every licence one address holds, newest first. */ +export function listLicenses( + agent: string, + params: { start?: number; limit?: number } = {}, +): Promise { + const query = new URLSearchParams({ + agent, + start: String(params.start ?? 0), + limit: String(params.limit ?? 200), + }); + return apiFetch(`/licenses?${query}`); +} diff --git a/frontend/src/lib/mockApi.paid.test.ts b/frontend/src/lib/mockApi.paid.test.ts index d24dc5c..3be4759 100644 --- a/frontend/src/lib/mockApi.paid.test.ts +++ b/frontend/src/lib/mockApi.paid.test.ts @@ -52,6 +52,21 @@ beforeEach(() => { resetMockLicences(); }); +/** A holder proves ownership before the free path serves them (STE-48). */ +async function proofHeaders( + agent: string, + skillVersion = SAFE, +): Promise> { + const challenge = await ( + await call(`use/${skillVersion}/challenge`, { query: `?agent=${agent}` }) + ).json(); + return { + "X-AGENT-ADDRESS": agent, + "X-STERISH-PROOF-NONCE": challenge.nonce, + "X-STERISH-PROOF-SIGNATURE": Buffer.alloc(64, 1).toString("base64"), + }; +} + describe("the licensable fixture", () => { it("serves bytes whose content hash is the one the registry holds", async () => { // The loop the check page closes: buy, save, drop the files back in, get @@ -129,12 +144,12 @@ describe("GET /use with a payment", () => { ); }); - it("serves the second request as held, with no payment attached", async () => { + it("serves the second request as held, with a proof and no payment", async () => { await call(`use/${SAFE}`, { headers: { "X-AGENT-ADDRESS": AGENT, "X-PAYMENT": paymentFor() }, }); const again = await call(`use/${SAFE}`, { - headers: { "X-AGENT-ADDRESS": AGENT }, + headers: await proofHeaders(AGENT), }); expect(again.status).toBe(200); expect(again.headers.get("X-STERISH-LICENSE")).toBe("held"); @@ -146,7 +161,7 @@ describe("GET /use with a payment", () => { headers: { "X-AGENT-ADDRESS": AGENT, "X-PAYMENT": paymentFor() }, }); const twice = await call(`use/${SAFE}`, { - headers: { "X-AGENT-ADDRESS": AGENT, "X-PAYMENT": paymentFor() }, + headers: { ...(await proofHeaders(AGENT)), "X-PAYMENT": paymentFor() }, }); expect(twice.headers.get("X-STERISH-LICENSE")).toBe("held"); expect(twice.headers.get("X-PAYMENT-RESPONSE")).toBeNull(); @@ -251,3 +266,69 @@ describe("GET /license", () => { expect((await response.json()).error).toBe("INVALID_AGENT"); }); }); + +describe("the ownership proof (STE-48)", () => { + async function buy() { + await call(`use/${SAFE}`, { + headers: { "X-AGENT-ADDRESS": AGENT, "X-PAYMENT": paymentFor() }, + }); + } + + it("refuses a holder who only names their address, and points at the challenge", async () => { + await buy(); + const response = await call(`use/${SAFE}`, { + headers: { "X-AGENT-ADDRESS": AGENT }, + }); + expect(response.status).toBe(401); + const body = await response.json(); + expect(body.error).toBe("OWNERSHIP_PROOF_REQUIRED"); + expect(String(body.challenge_url)).toContain(`/use/${SAFE}/challenge`); + // Never 402: this caller may already have paid. + expect(response.headers.get("PAYMENT-REQUIRED")).toBeNull(); + }); + + it("issues a challenge bound to one agent, skill and version", async () => { + const body = await ( + await call(`use/${SAFE}/challenge`, { query: `?agent=${AGENT}` }) + ).json(); + expect(body.agent).toBe(AGENT); + expect(body.skill_id).toBe("com.acme.pdf-suite"); + expect(body.version).toBe("0.9.0"); + expect(body.signature_scheme).toBe("SEP-53"); + expect(body.message).toContain(`nonce: ${body.nonce}`); + }); + + it("refuses a challenge for an address that cannot hold a licence", async () => { + const response = await call(`use/${SAFE}/challenge`, { + query: `?agent=${FIXTURE_PAYMENT_TERMS.asset}`, + }); + expect(response.status).toBe(400); + expect((await response.json()).error).toBe("INVALID_AGENT"); + }); + + it("consumes a nonce, so a replay is refused", async () => { + await buy(); + const headers = await proofHeaders(AGENT); + expect((await call(`use/${SAFE}`, { headers })).status).toBe(200); + const replay = await call(`use/${SAFE}`, { headers }); + expect(replay.status).toBe(401); + expect((await replay.json()).error).toBe("INVALID_OWNERSHIP_PROOF"); + }); + + it("refuses another agent's nonce", async () => { + await buy(); + const stolen = await proofHeaders(OTHER_AGENT); + const response = await call(`use/${SAFE}`, { + headers: { ...stolen, "X-AGENT-ADDRESS": AGENT }, + }); + expect(response.status).toBe(401); + expect((await response.json()).detail).toContain("another agent"); + }); + + it("still challenges for payment when the caller holds nothing", async () => { + const response = await call(`use/${SAFE}`, { + headers: await proofHeaders(OTHER_AGENT), + }); + expect(response.status).toBe(402); + }); +}); diff --git a/frontend/src/lib/mockApi.ts b/frontend/src/lib/mockApi.ts index e9f6689..4783317 100644 --- a/frontend/src/lib/mockApi.ts +++ b/frontend/src/lib/mockApi.ts @@ -14,6 +14,11 @@ * The paid path is the one place the mock cannot be faithful. There is no * facilitator behind it, so a payment is checked for shape only, never * verified or settled, and the "mint" is an entry in this process's memory. + * The STE-48 ownership proof is checked the same way: the nonce must be one + * this process issued for that agent, skill and version, and is consumed on + * use, but the signature itself cannot be verified without a wallet, so any + * well-formed signature passes. What that does exercise for real is the whole + * client dance: the 401, the challenge fetch, the wallet prompt, the retry. * What it does exercise for real is everything on the client side: the 402, * the decoded terms, the wallet signature over a genuine simulation of the * USDC transfer, and the 200 that follows. @@ -67,9 +72,135 @@ const ACCOUNT = /^G[A-Z2-7]{55}$/; */ const mintedLicences = new Set(); -/** Tests start from no licences. Not reachable over HTTP. */ +/** + * Ownership challenges this process issued, by nonce (STE-48). Single use and + * short lived, the same way the API treats them. + */ +const challenges = new Map< + string, + { agent: string; skillId: string; version: string; expiresAt: number } +>(); + +const PROOF_TTL_SECONDS = 300; + +/** Tests start from no licences and no challenges. Not reachable over HTTP. */ export function resetMockLicences(): void { mintedLicences.clear(); + challenges.clear(); +} + +function proofMessage( + agent: string, + skillId: string, + version: string, + nonce: string, + expiresAt: number, +): string { + return [ + "Sterish licence ownership proof", + `agent: ${agent}`, + `skill: ${skillId}`, + `version: ${version}`, + `nonce: ${nonce}`, + `expires: ${expiresAt}`, + "network: Test SDF Network ; September 2015", + ].join("\n"); +} + +function handleChallenge( + request: Request, + url: URL, + skillId: string, + version: string, +): Response { + const agent = agentOf(request, url); + if (!agent) { + return fail(400, "MISSING_AGENT", "send ?agent=G... or X-AGENT-ADDRESS"); + } + if (!ACCOUNT.test(agent)) { + return fail(400, "INVALID_AGENT", `'${agent}' is not a G... account`); + } + + // Issued for any valid account and version: who holds a licence is public + // anyway, so answering differently would reveal nothing. + const nonce = Array.from({ length: 32 }, () => + Math.floor(Math.random() * 16).toString(16), + ).join(""); + const expiresAt = Math.floor(Date.now() / 1000) + PROOF_TTL_SECONDS; + challenges.set(nonce, { agent, skillId, version, expiresAt }); + + return Response.json( + { + agent, + skill_id: skillId, + version, + nonce, + expires_at: expiresAt, + expires_at_iso: new Date(expiresAt * 1000).toISOString(), + message: proofMessage(agent, skillId, version, nonce, expiresAt), + signature_scheme: "SEP-53", + send_headers: { + "X-AGENT-ADDRESS": agent, + "X-STERISH-PROOF-NONCE": nonce, + "X-STERISH-PROOF-SIGNATURE": "", + }, + }, + { headers: { "Cache-Control": "no-store" } }, + ); +} + +/** Null when the proof is good; otherwise the response to send instead. */ +function checkProof( + request: Request, + url: URL, + agent: string, + skillId: string, + version: string, +): Response | null { + const challengeUrl = `${url.origin}${url.pathname}/challenge?agent=${agent}`; + const nonce = request.headers.get("X-STERISH-PROOF-NONCE"); + const signature = request.headers.get("X-STERISH-PROOF-SIGNATURE"); + + if (!nonce || !signature) { + return Response.json( + { + error: "OWNERSHIP_PROOF_REQUIRED", + detail: `${agent} holds a licence for this version; prove you control it`, + challenge_url: challengeUrl, + signature_scheme: "SEP-53", + }, + { status: 401 }, + ); + } + + const issued = challenges.get(nonce); + const reason = + issued === undefined + ? "unknown or already used nonce" + : issued.agent !== agent || + issued.skillId !== skillId || + issued.version !== version + ? "nonce was issued for another agent, skill or version" + : issued.expiresAt < Math.floor(Date.now() / 1000) + ? "nonce has expired" + : !/^[A-Za-z0-9+/]+={0,2}$/.test(signature) + ? "signature is not base64" + : null; + if (reason) { + // A failed signature never consumes the nonce, so nobody can burn another + // caller's challenge. + return Response.json( + { + error: "INVALID_OWNERSHIP_PROOF", + detail: reason, + challenge_url: challengeUrl, + }, + { status: 401 }, + ); + } + + challenges.delete(nonce); + return null; } function licenceKey(agent: string, skillId: string, version: string): string { @@ -181,6 +312,9 @@ function handleUse( const payment = request.headers.get("X-PAYMENT"); if (agent && mintedLicences.has(licenceKey(agent, skillId, version))) { + // STE-48: holders are public, so the free path needs a signed challenge. + const refusal = checkProof(request, url, agent, skillId, version); + if (refusal) return refusal; return Response.json(artifact, { headers: { "X-STERISH-LICENSE": "held" }, }); @@ -339,6 +473,49 @@ export function handleMockRequest(request: Request, path: string[]): Response { }); } + // GET /use/{skill_id}/{version}/challenge + if (path.length === 4 && path[0] === "use" && path[3] === "challenge") { + return handleChallenge(request, url, path[1], path[2]); + } + + // GET /licenses?agent= + if (path.length === 1 && path[0] === "licenses") { + const agent = agentOf(request, url); + if (!agent) { + return fail(400, "MISSING_AGENT", "send ?agent=G... or X-AGENT-ADDRESS"); + } + if (!ACCOUNT.test(agent)) { + return fail(400, "INVALID_AGENT", `'${agent}' is not a G... account`); + } + const licenses = [...mintedLicences] + .filter((key) => key.startsWith(`${agent}|`)) + .map((key, index) => { + const [, rest] = key.split("|"); + const at = rest.lastIndexOf("@"); + const skillId = rest.slice(0, at); + const version = rest.slice(at + 1); + return { + token_id: index + 1, + skill_id: skillId, + version, + minted_at: 1756810000, + minted_at_iso: "2026-09-02T09:26:40Z", + mint_tx: fakeTxHash(`mint|${key}`), + mint_tx_url: `https://stellar.expert/explorer/testnet/tx/${fakeTxHash(`mint|${key}`)}`, + }; + }); + return Response.json({ + agent, + licenses, + total: licenses.length, + start: 0, + limit: 50, + total_supply: licenses.length, + tokens_contract_id: FIXTURE_TOKENS_CONTRACT_ID, + contract_url: `https://stellar.expert/explorer/testnet/contract/${FIXTURE_TOKENS_CONTRACT_ID}`, + }); + } + // GET /license/{skill_id}/{version} if (path.length === 3 && path[0] === "license") { return handleLicense(request, url, path[1], path[2]); diff --git a/frontend/src/lib/ownership.test.ts b/frontend/src/lib/ownership.test.ts new file mode 100644 index 0000000..50f315c --- /dev/null +++ b/frontend/src/lib/ownership.test.ts @@ -0,0 +1,251 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { ApiError } from "./api"; +import { + describeProofFailure, + isChallengeUsable, + isValidSignature, + requestSkillProving, +} from "./ownership"; +import type { OwnershipChallenge } from "./types"; + +/** + * The ownership proof is what stands between "this wallet holds a licence" and + * "somebody typed a holder's address". Two things must hold: a 401 asking for a + * proof is part of the flow and never shown as a failure, and a proof is only + * ever built from the challenge the API itself pointed at. + */ + +const AGENT = "GDUKDRK63Q24NORQ4SQPUQKZNASZELTDXR7TCLV5T6X5X2BYCLEYNITH"; +const CHALLENGE_URL = + "https://api.sterish.xyz/use/org.example.skill/1.0.0/challenge?agent=" + + AGENT; +const SIGNATURE = Buffer.alloc(64, 7).toString("base64"); + +const CHALLENGE: OwnershipChallenge = { + agent: AGENT, + skill_id: "org.example.skill", + version: "1.0.0", + nonce: "a".repeat(32), + expires_at: Math.floor(Date.now() / 1000) + 300, + expires_at_iso: "2026-09-24T12:00:00Z", + message: "Sterish licence ownership proof\nagent: " + AGENT, + signature_scheme: "SEP-53", +}; + +vi.mock("./wallet", async () => { + const actual = await vi.importActual("./wallet"); + return { + ...actual, + signMessage: vi.fn(async () => SIGNATURE), + NETWORK_PASSPHRASE: "Test SDF Network ; September 2015", + }; +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +function proofRequired(): Response { + return Response.json( + { + error: "OWNERSHIP_PROOF_REQUIRED", + detail: "prove you control it", + challenge_url: CHALLENGE_URL, + }, + { status: 401 }, + ); +} + +describe("isValidSignature", () => { + it("accepts 64 bytes of base64, the SEP-53 shape", () => { + expect(isValidSignature(SIGNATURE)).toBe(true); + }); + + it("refuses anything else, rather than sending it and being told no", () => { + expect(isValidSignature(Buffer.alloc(32).toString("base64"))).toBe(false); + expect(isValidSignature("not base64 !!")).toBe(false); + expect(isValidSignature("")).toBe(false); + }); +}); + +describe("isChallengeUsable", () => { + const at = (expires: number) => ({ ...CHALLENGE, expires_at: expires }); + + it("is true while there is time to sign", () => { + expect(isChallengeUsable(at(1000), 700)).toBe(true); + }); + + it("is false once it has expired or is about to", () => { + expect(isChallengeUsable(at(1000), 1001)).toBe(false); + expect(isChallengeUsable(at(1000), 998)).toBe(false); + }); +}); + +describe("requestSkillProving", () => { + it("serves a skill with no proof when the API does not ask for one", async () => { + const spy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue( + Response.json({ "SKILL.md": "# x" }, { + headers: { "X-STERISH-LICENSE": "held" }, + }), + ); + + const outcome = await requestSkillProving("org.example.skill", "1.0.0", { + agent: AGENT, + }); + expect(outcome.kind).toBe("granted"); + expect(spy).toHaveBeenCalledTimes(1); + }); + + it("fetches the challenge the 401 named, signs it, and repeats the request", async () => { + const spy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(proofRequired()) + .mockResolvedValueOnce(Response.json(CHALLENGE)) + .mockResolvedValueOnce( + Response.json({ "SKILL.md": "# x" }, { + headers: { "X-STERISH-LICENSE": "held" }, + }), + ); + + const proving = vi.fn(); + const outcome = await requestSkillProving("org.example.skill", "1.0.0", { + agent: AGENT, + onProving: proving, + }); + + expect(outcome.kind).toBe("granted"); + expect(proving).toHaveBeenCalledOnce(); + // The challenge URL is taken from the body, never built by the client. + expect(String(spy.mock.calls[1][0])).toBe(CHALLENGE_URL); + const headers = spy.mock.calls[2][1]?.headers as Record; + expect(headers["X-STERISH-PROOF-NONCE"]).toBe(CHALLENGE.nonce); + expect(headers["X-STERISH-PROOF-SIGNATURE"]).toBe(SIGNATURE); + expect(headers["X-AGENT-ADDRESS"]).toBe(AGENT); + }); + + it("refuses a challenge issued for another address", async () => { + vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce(proofRequired()) + .mockResolvedValueOnce( + Response.json({ ...CHALLENGE, agent: "G" + "B".repeat(55) }), + ); + + await expect( + requestSkillProving("org.example.skill", "1.0.0", { agent: AGENT }), + ).rejects.toThrow("not for the connected wallet"); + }); + + it("refuses a scheme it does not sign", async () => { + vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce(proofRequired()) + .mockResolvedValueOnce( + Response.json({ ...CHALLENGE, signature_scheme: "SEP-99" }), + ); + + await expect( + requestSkillProving("org.example.skill", "1.0.0", { agent: AGENT }), + ).rejects.toThrow("SEP-99"); + }); + + it("passes a 402 challenge through untouched, so paying still works", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response("{}", { + status: 402, + headers: { + "PAYMENT-REQUIRED": Buffer.from( + JSON.stringify({ + x402Version: 2, + accepts: [ + { + scheme: "exact", + network: "stellar:testnet", + amount: "1000000", + asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + payTo: "GD73M4F7RN74KBLFGJP4WKBMCBJWBOA4SFNOP5HG4NBCDQUQCC2ARSZU", + }, + ], + }), + ).toString("base64"), + }, + }), + ); + + const outcome = await requestSkillProving("org.example.skill", "1.0.0", { + agent: AGENT, + }); + expect(outcome.kind).toBe("payment_required"); + }); + + it("does not try to prove an error that is not about proof", async () => { + const spy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue( + Response.json( + { error: "NOT_VERIFIED", detail: "x@1 is DANGEROUS" }, + { status: 403 }, + ), + ); + + await expect( + requestSkillProving("org.example.skill", "1.0.0", { agent: AGENT }), + ).rejects.toMatchObject({ code: "NOT_VERIFIED" }); + expect(spy).toHaveBeenCalledTimes(1); + }); +}); + +describe("describeProofFailure", () => { + it("tells a refused proof apart, and says a fresh one is needed", () => { + const failure = describeProofFailure( + new ApiError({ + message: "nonce already used", + status: 401, + code: "INVALID_OWNERSHIP_PROOF", + detail: "nonce already used", + url: "https://api.sterish.xyz/use/x/1", + }), + ); + expect(failure.kind).toBe("expired"); + expect(failure.message).toContain("single use"); + }); + + it("reads a declined signature as a decision, not a failure", () => { + const failure = describeProofFailure( + new Error("The user rejected this request."), + ); + expect(failure.kind).toBe("declined"); + // Nobody should think they were charged for refusing to sign. + expect(failure.message).toContain("not a payment"); + }); + + it("names a missing wallet as such", () => { + expect( + describeProofFailure(new Error("Freighter is not connected")).kind, + ).toBe("wallet_unavailable"); + }); + + it("reads a wallet's own rejection object, not [object Object]", () => { + // The kit rejects with a plain object; String() on it says nothing. + const failure = describeProofFailure({ + code: -4, + message: "The user rejected this request.", + }); + expect(failure.kind).toBe("declined"); + expect(failure.message).not.toContain("[object Object]"); + }); + + it("says something useful for an error object with no message at all", () => { + expect(describeProofFailure({ code: -3 }).message).toContain( + "without saying why", + ); + }); + + it("passes anything else through with its own message", () => { + expect(describeProofFailure(new Error("RPC timed out"))).toEqual({ + kind: "failed", + message: "RPC timed out", + }); + }); +}); diff --git a/frontend/src/lib/ownership.ts b/frontend/src/lib/ownership.ts new file mode 100644 index 0000000..d55d211 --- /dev/null +++ b/frontend/src/lib/ownership.ts @@ -0,0 +1,182 @@ +/** + * Proving to the API that this wallet is the address holding a licence. + * + * Who holds a licence is public: `license_minted` events, the tokens contract, + * and this dashboard's own `/licences/[address]` page. So since STE-48 the free + * paths of `GET /use` refuse an address alone and ask for a signature over a + * single-use challenge (api-spec §3.7): + * + * 1. `GET` the `challenge_url` the 401 carried, + * 2. sign `message` exactly as returned, with the wallet's SEP-43 + * `signMessage` (which is SEP-53: ed25519 over the prefixed sha256), + * 3. repeat the request with the nonce and the signature. + * + * A nonce is bound to one agent, one skill and one version, and is consumed by + * the first request that proves with it, so a proof is built immediately before + * the request it is for and never cached. + */ + +import { + ApiError, + getOwnershipChallenge, + requestSkill, + type UseOutcome, +} from "./api"; +import type { OwnershipChallenge } from "./types"; +import { signMessage, walletErrorMessage } from "./wallet"; + +/** SEP-53 signatures are 64 raw bytes, base64 encoded. */ +export function isValidSignature(value: string): boolean { + if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return false; + try { + return atob(value).length === 64; + } catch { + return false; + } +} + +/** The proof headers `requestSkill` sends, kept together so neither goes alone. */ +export interface OwnershipProof { + nonce: string; + signature: string; +} + +/** + * Whether a challenge still has time on it, with a small margin for the round + * trip. The API clamps its own TTL to at least 30 seconds. + */ +export function isChallengeUsable( + challenge: OwnershipChallenge, + now: number = Date.now() / 1000, +): boolean { + return challenge.expires_at - now > 5; +} + +/** + * Ask for a challenge and have the wallet sign it. + * + * The scheme is checked rather than assumed: if the API ever asks for something + * other than SEP-53, a wallet's `signMessage` would produce a signature in the + * wrong shape, and sending it would look like tampering rather than an + * unsupported client. + */ +export async function proveOwnership( + challengeUrl: string, + address: string, +): Promise { + const challenge = await getOwnershipChallenge(challengeUrl); + + if (challenge.agent !== address) { + throw new Error( + `The challenge was issued for ${challenge.agent}, not for the connected wallet`, + ); + } + if (challenge.signature_scheme !== "SEP-53") { + throw new Error( + `This dashboard signs SEP-53 challenges; the API asked for ${challenge.signature_scheme}`, + ); + } + if (!isChallengeUsable(challenge)) { + throw new Error("The challenge expired before it could be signed"); + } + + const signature = await signMessage(challenge.message, { address }); + if (!isValidSignature(signature)) { + throw new Error( + "The wallet returned a signature this dashboard cannot use: SEP-53 expects 64 bytes, base64 encoded", + ); + } + return { nonce: challenge.nonce, signature }; +} + +/** + * Ask for a skill, and prove ownership if the API asks for it. + * + * The 401 is not an error to show: it is the API saying "sign this first". The + * proof is fetched and signed on the spot, then the same request is repeated, + * so the nonce is used within seconds of being issued. `onProving` lets the UI + * say that a wallet prompt is coming, since the wallet opens in the middle of + * what looked like one click. + * + * Shared by the version card and the licences page: both hand over a skill + * somebody already holds, and both must ask for exactly one signature. + */ +export async function requestSkillProving( + skillId: string, + version: string, + opts: { agent: string; payment?: string; onProving?: () => void }, +): Promise { + try { + return await requestSkill(skillId, version, { + agent: opts.agent, + payment: opts.payment, + }); + } catch (cause) { + const needsProof = + cause instanceof ApiError && + cause.status === 401 && + cause.challengeUrl !== null; + if (!needsProof) throw cause; + + opts.onProving?.(); + const proof = await proveOwnership( + (cause as ApiError).challengeUrl as string, + opts.agent, + ); + return await requestSkill(skillId, version, { + agent: opts.agent, + payment: opts.payment, + proof, + }); + } +} + +/** Why a proof did not happen, in terms the card can word. */ +export type ProofFailure = { + kind: "declined" | "wallet_unavailable" | "expired" | "failed"; + message: string; +}; + +/** What to tell somebody when a proof did not work out. */ +export function describeProofFailure(cause: unknown): ProofFailure { + if (cause instanceof ApiError) { + if (cause.code === "INVALID_OWNERSHIP_PROOF") { + return { + kind: "expired", + message: `The API refused the proof (${cause.detail}). A challenge is single use and short lived, so try again to sign a fresh one.`, + }; + } + return { + kind: "failed", + message: `${cause.message}${cause.code ? ` (${cause.code})` : ""}`, + }; + } + + // Wallets reject with a plain object, not an Error, so its message has to be + // dug out rather than stringified: String({...}) is "[object Object]", which + // is what the licences page showed for a declined signature. + const message = walletErrorMessage(cause); + if ( + /not connected|not installed|not available|no wallet|locked/i.test(message) + ) { + return { + kind: "wallet_unavailable", + message: + "Your wallet did not respond. Make sure it is installed, unlocked and connected to this site, then try again.", + }; + } + if (/reject|declin|denied|cancel/i.test(message)) { + return { + kind: "declined", + message: + "You declined the signature. It proves this wallet holds the licence; it is not a payment and costs nothing.", + }; + } + return { + kind: "failed", + message: + message === "[object Object]" + ? "The wallet returned an error without saying why. Nothing was charged." + : message, + }; +} diff --git a/frontend/src/lib/testnetSetup.test.ts b/frontend/src/lib/testnetSetup.test.ts index a936da4..108991c 100644 --- a/frontend/src/lib/testnetSetup.test.ts +++ b/frontend/src/lib/testnetSetup.test.ts @@ -82,12 +82,14 @@ describe("parseAccountSetup", () => { }); describe("usdcAssetFor", () => { + // These two import the Stellar SDK to derive a contract id, which is slow to + // load the first time, so they get more than the default five seconds. it("recognises the SAC the live 402 names as Circle's USDC", async () => { await expect(usdcAssetFor({ asset: USDC_SAC })).resolves.toEqual({ code: "USDC", issuer: TESTNET_USDC_ISSUER, }); - }); + }, 30_000); it("offers no trustline for any other asset", async () => { await expect( @@ -95,7 +97,7 @@ describe("usdcAssetFor", () => { asset: "CDAYXDIDIINSVQVQRFCH7JSHTFZN4KIZKMNUZRVACHHFLTYGZEZV4OF2", }), ).resolves.toBeNull(); - }); + }, 30_000); }); describe("readAccountSetup", () => { diff --git a/frontend/src/lib/tokens.test.ts b/frontend/src/lib/tokens.test.ts deleted file mode 100644 index 97e0ba8..0000000 --- a/frontend/src/lib/tokens.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - ChainReadError, - isAccountAddress, - parseLicence, - readLicences, - type ContractCall, -} from "./tokens"; - -/** - * The licences page shows what an address holds. The two failures that matter: - * listing somebody else's licence as theirs, and turning a failed read into - * "holds nothing". - */ - -const ME = "GDAVKROBU6VGWMAY36YMHQ6LV7XD7D5R5T3LJTTEBJKX3EURZAEDHSPL"; -const OTHER = "GCF76SG6QUBTJHK6AEFPS22TOB6JO5TKXXR5FW3QSDFOFLNXNLCJTXSC"; - -function token( - id: number, - kind: "License" | "Verified", - owner: string, - mintedAt: number, - skill = `org.example.skill-${id}`, -) { - return { - kind: [kind], - minted_at: BigInt(mintedAt), - owner, - skill_id: skill, - token_id: id, - version: "1.0.0", - }; -} - -/** A fake contract holding `tokens`; total_supply is the count, ids from 1. */ -function contract( - tokens: ReturnType[], - supply = tokens.length, -): ContractCall { - return async (method, args) => { - if (method === "total_supply") return supply; - const id = args[0].value; - return tokens.find((t) => t.token_id === id) ?? { contractError: true }; - }; -} - -describe("isAccountAddress", () => { - it("accepts a G account", () => { - expect(isAccountAddress(ME)).toBe(true); - }); - - it("refuses contracts, muxed accounts, and anything else", () => { - expect( - isAccountAddress( - "CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T", - ), - ).toBe(false); - expect(isAccountAddress(`M${ME.slice(1)}AAAAAAAAAAAA`)).toBe(false); - expect(isAccountAddress(ME.toLowerCase())).toBe(false); - expect(isAccountAddress("hello")).toBe(false); - expect(isAccountAddress("")).toBe(false); - }); -}); - -describe("parseLicence", () => { - it("reads the shape scValToNative produces", () => { - expect(parseLicence(token(19, "License", ME, 1789548592))).toEqual({ - tokenId: 19, - skillId: "org.example.skill-19", - version: "1.0.0", - owner: ME, - mintedAt: 1789548592, - }); - }); - - it("ignores VERIFIED badges", () => { - expect(parseLicence(token(1, "Verified", ME, 1))).toBeNull(); - }); - - it("ignores anything that is not a token record", () => { - expect(parseLicence(null)).toBeNull(); - expect(parseLicence({ contractError: true })).toBeNull(); - expect(parseLicence({ kind: ["License"], owner: ME })).toBeNull(); - }); -}); - -describe("readLicences", () => { - it("returns only licences owned by the address, newest first", async () => { - const scan = await readLicences( - ME, - contract([ - token(1, "Verified", ME, 100), - token(2, "License", ME, 200, "org.example.older"), - token(3, "License", OTHER, 300), - token(4, "License", ME, 400, "org.example.newer"), - ]), - ); - expect(scan.licences.map((l) => l.skillId)).toEqual([ - "org.example.newer", - "org.example.older", - ]); - expect(scan.scanned).toBe(4); - }); - - it("reads every id from 1 to total_supply", async () => { - const calls: number[] = []; - const inner = contract([ - token(1, "License", ME, 1), - token(2, "License", ME, 2), - token(3, "License", ME, 3), - ]); - const scan = await readLicences(ME, async (method, args) => { - if (method === "get_token") calls.push(args[0].value); - return inner(method, args); - }); - expect(calls.sort((a, b) => a - b)).toEqual([1, 2, 3]); - expect(scan.scanned).toBe(3); - }); - - it("tolerates a token that is missing when read, instead of failing", async () => { - // A supply read that races ahead of the token reads. - const scan = await readLicences( - ME, - contract([token(1, "License", ME, 1)], 2), - ); - expect(scan.licences).toHaveLength(1); - expect(scan.scanned).toBe(1); - }); - - it("answers an empty list for an address that holds nothing", async () => { - const scan = await readLicences( - ME, - contract([token(1, "License", OTHER, 1)]), - ); - expect(scan.licences).toEqual([]); - expect(scan.scanned).toBe(1); - }); - - it("handles a contract that has minted nothing", async () => { - await expect(readLicences(ME, contract([]))).resolves.toEqual({ - licences: [], - scanned: 0, - }); - }); - - it("throws when a read fails, instead of reporting no licences", async () => { - const failing: ContractCall = async (method, args) => { - if (method === "total_supply") return 3; - if (args[0].value === 2) throw new ChainReadError("RPC down"); - return token(args[0].value, "License", ME, 1); - }; - await expect(readLicences(ME, failing)).rejects.toThrow("RPC down"); - }); - - it("throws on a nonsensical supply", async () => { - await expect( - readLicences(ME, async () => "not a number"), - ).rejects.toBeInstanceOf(ChainReadError); - }); -}); diff --git a/frontend/src/lib/tokens.ts b/frontend/src/lib/tokens.ts deleted file mode 100644 index 23510f7..0000000 --- a/frontend/src/lib/tokens.ts +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Licences held by an address, read straight from the tokens contract. - * - * Temporary, and says so on screen. The API has no "licences of this address" - * endpoint yet (STE-46); until it does, the page reads every token record and - * keeps the licences owned by the address. That is one simulation per token - * ever minted, which is fine at a few dozen tokens (19 took 0.47s on - * 2026-09-16) and is exactly why STE-46 exists. - * - * Reads only. Every call is a `simulateTransaction` from a throwaway source - * account, the same way the API reads the chain, so no key is involved. - */ - -import { NETWORK_PASSPHRASE, RPC_URL } from "./wallet"; - -/** Tokens v2, deployed in STE-44. Overridable for a redeploy. */ -export const TOKENS_CONTRACT_ID = - process.env.NEXT_PUBLIC_TOKENS_CONTRACT_ID ?? - "CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T"; - -/** - * `TokenError::TokenNotFound = 2` in contracts/tokens/src/data.rs. Only this - * error means "no token at this id"; every other contract error is a real - * failure and must not be skipped as if the slot were empty. - */ -const TOKEN_NOT_FOUND = /Error\(Contract, #2\)/; - -/** Simultaneous simulations. Enough to be quick, few enough to be polite. */ -const CONCURRENCY = 8; - -export interface Licence { - tokenId: number; - skillId: string; - version: string; - owner: string; - /** Ledger timestamp, unix seconds. */ - mintedAt: number; -} - -export interface LicenceScan { - licences: Licence[]; - /** How many token records were read to produce the list. */ - scanned: number; -} - -/** A classic `G...` account. Contracts and muxed accounts hold no licences. */ -export function isAccountAddress(value: string): boolean { - return /^G[A-Z2-7]{55}$/.test(value); -} - -/** - * One `get_token` result, as `scValToNative` decodes it, into a licence. Returns - * null for a VERIFIED badge or anything that does not have the licence shape. - * - * `kind` arrives as a one-element array (`["License"]`) because the contract - * enum is a unit variant. - */ -export function parseLicence(record: unknown): Licence | null { - if (typeof record !== "object" || record === null) return null; - const r = record as Record; - const kind = Array.isArray(r.kind) ? r.kind[0] : r.kind; - if (kind !== "License") return null; - if ( - typeof r.skill_id !== "string" || - typeof r.version !== "string" || - typeof r.owner !== "string" - ) { - return null; - } - return { - tokenId: Number(r.token_id), - skillId: r.skill_id, - version: r.version, - owner: r.owner, - mintedAt: Number(r.minted_at), - }; -} - -/** A contract read: method plus native arguments in, decoded result out. */ -export type ContractCall = ( - method: string, - args: Array<{ value: number; type: "u32" }>, -) => Promise; - -/** A read that failed for a reason other than the contract's own answer. */ -export class ChainReadError extends Error { - constructor(message: string) { - super(message); - this.name = "ChainReadError"; - } -} - -/** The real contract read, over Soroban RPC. */ -async function rpcCall( - method: string, - args: Array<{ value: number; type: "u32" }>, -): Promise { - const { - Account, - Contract, - TransactionBuilder, - nativeToScVal, - rpc, - scValToNative, - } = await import("@stellar/stellar-sdk"); - const server = new rpc.Server(RPC_URL); - const tx = new TransactionBuilder( - new Account( - "GD73M4F7RN74KBLFGJP4WKBMCBJWBOA4SFNOP5HG4NBCDQUQCC2ARSZU", - "0", - ), - { fee: "100", networkPassphrase: NETWORK_PASSPHRASE }, - ) - .addOperation( - new Contract(TOKENS_CONTRACT_ID).call( - method, - ...args.map((a) => nativeToScVal(a.value, { type: a.type })), - ), - ) - .setTimeout(30) - .build(); - - let simulation; - try { - simulation = await server.simulateTransaction(tx); - } catch (cause) { - throw new ChainReadError( - `Soroban RPC is unreachable: ${cause instanceof Error ? cause.message : String(cause)}`, - ); - } - if (rpc.Api.isSimulationError(simulation)) { - // A contract error is an answer, not an outage; the caller decides what - // it means. Anything else is a failed read. - if (TOKEN_NOT_FOUND.test(simulation.error)) return { contractError: true }; - throw new ChainReadError( - `The tokens contract read failed: ${simulation.error}`, - ); - } - if (!rpc.Api.isSimulationSuccess(simulation) || !simulation.result) { - throw new ChainReadError("The tokens contract returned no result"); - } - return scValToNative(simulation.result.retval); -} - -/** - * Every licence `address` holds, newest first. - * - * `total_supply` is the number of tokens ever minted, and ids run from 1 to it - * with nothing ever burned, so every id in that range is read. A - * `TokenNotFound` is still tolerated rather than fatal: a mint landing between - * the supply read and the token reads must not turn the page into an error. A - * failed read throws: an empty list must only ever mean the chain was read and - * holds nothing for this address. - */ -export async function readLicences( - address: string, - call: ContractCall = rpcCall, -): Promise { - const supply = Number(await call("total_supply", [])); - if (!Number.isInteger(supply) || supply < 0) { - throw new ChainReadError(`total_supply returned ${String(supply)}`); - } - - const ids = Array.from({ length: supply }, (_, i) => i + 1); - const records: unknown[] = []; - for (let start = 0; start < ids.length; start += CONCURRENCY) { - const batch = ids.slice(start, start + CONCURRENCY); - records.push( - ...(await Promise.all( - batch.map((id) => call("get_token", [{ value: id, type: "u32" }])), - )), - ); - } - - const found = records.filter( - (r) => !(typeof r === "object" && r !== null && "contractError" in r), - ); - const licences = found - .map(parseLicence) - .filter((l): l is Licence => l !== null && l.owner === address) - .sort((a, b) => b.mintedAt - a.mintedAt || b.tokenId - a.tokenId); - - return { licences, scanned: found.length }; -} diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index 8d5e3cc..fed4d66 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -158,9 +158,58 @@ export type ApiErrorCode = | "LICENSE_MINT_PENDING" | "MISSING_AGENT" | "INVALID_AGENT" + | "OWNERSHIP_PROOF_REQUIRED" + | "INVALID_OWNERSHIP_PROOF" + | "LICENSE_READ_FAILED" + | "FACILITATOR_BAD_RESPONSE" | "PAYMENT_OUTCOME_UNKNOWN" | "INVALID_CHALLENGE"; +/** + * Spec §3.7, the ownership challenge (STE-48). + * + * Who holds a licence is public, so the free path asks the caller to sign a + * single-use message with the address's own key. The signed text is `message` + * exactly as returned: the server rebuilds it from its own record of the nonce + * and trusts nothing the client echoes back. + */ +export interface OwnershipChallenge { + agent: string; + skill_id: string; + version: string; + nonce: string; + expires_at: number; + expires_at_iso: string; + message: string; + /** Always "SEP-53" today: ed25519 over sha256("Stellar Signed Message:\n" + message). */ + signature_scheme: string; +} + +/** One row of spec §3.10. No verdict: that is a separate read against the registry. */ +export interface LicenseRecord { + token_id: number; + skill_id: string; + version: string; + minted_at: number; + minted_at_iso: string; + /** Null when the mint is older than the indexer's event window, or not indexed yet. */ + mint_tx: string | null; + mint_tx_url: string | null; +} + +/** Spec §3.10. Read from the tokens contract's own enumeration, not from events. */ +export interface LicenseList { + agent: string; + licenses: LicenseRecord[]; + total: number; + start: number; + limit: number; + /** What the contract's supply was when this list was built. */ + total_supply: number; + tokens_contract_id: string; + contract_url: string; +} + /** * Spec §3.8. Whether one agent holds a licence for one exact version. * diff --git a/frontend/src/lib/wallet.ts b/frontend/src/lib/wallet.ts index 4ffefc6..6d04c97 100644 --- a/frontend/src/lib/wallet.ts +++ b/frontend/src/lib/wallet.ts @@ -150,6 +150,27 @@ export async function signAuthEntry( }); } +/** + * Sign a plain message with the connected wallet (SEP-43 `signMessage`). + * + * Sterish's ownership proof (api-spec §3.7) is SEP-53: ed25519 over + * `sha256("Stellar Signed Message: +" + message)`, base64. That prefixing and + * hashing is the wallet's job, which is why the message goes out exactly as the + * API returned it and nothing is pre-hashed here. + */ +export async function signMessage( + message: string, + opts: { address: string; networkPassphrase?: string }, +): Promise { + const { StellarWalletsKit } = await loadKit(); + const { signedMessage } = await StellarWalletsKit.signMessage(message, { + address: opts.address, + networkPassphrase: opts.networkPassphrase ?? NETWORK_PASSPHRASE, + }); + return signedMessage; +} + /** * Sign a whole transaction envelope with the connected wallet. * diff --git a/frontend/src/modules/licences/Licences.tsx b/frontend/src/modules/licences/Licences.tsx index 97913f5..01fe447 100644 --- a/frontend/src/modules/licences/Licences.tsx +++ b/frontend/src/modules/licences/Licences.tsx @@ -26,16 +26,13 @@ import { Input } from "@/components/ui/input"; import { Skeleton } from "@/components/ui/skeleton"; import { useLicences, useLicenceVerdicts } from "@/hooks/useLicences"; import { useWallet } from "@/hooks/useWallet"; -import { ApiError, requestSkill } from "@/lib/api"; +import { ApiError } from "@/lib/api"; import { downloadArtifact } from "@/lib/artifact"; -import { - TOKENS_CONTRACT_ID, - isAccountAddress, - type Licence, -} from "@/lib/tokens"; -import type { VersionCheck } from "@/lib/types"; +import { describeProofFailure, requestSkillProving } from "@/lib/ownership"; +import type { LicenseRecord, VersionCheck } from "@/lib/types"; import { EXPLORER_BASE } from "@/lib/wallet"; import { formatLedgerTime } from "@/utils/format"; +import { isAccountAddress } from "@/utils/stellar"; /** * Every licence one address holds, with the verdict of each version today. @@ -103,12 +100,14 @@ function LicenceRow({ verdict, own, }: { - licence: Licence; + licence: LicenseRecord; verdict: { data?: VersionCheck; error: Error | null; isPending: boolean }; own: boolean; }) { const wallet = useWallet(); - const [state, setState] = useState<"idle" | "loading" | "error">("idle"); + const [state, setState] = useState<"idle" | "loading" | "proving" | "error">( + "idle", + ); const [message, setMessage] = useState(null); const safe = verdict.data?.is_verified === true; @@ -117,11 +116,15 @@ function LicenceRow({ setState("loading"); setMessage(null); try { - const outcome = await requestSkill(licence.skillId, licence.version, { - agent: wallet.address, - }); + // Since STE-48 the API serves a held licence only to a caller that signs + // a one-off challenge, so a wallet prompt appears mid-flight. + const outcome = await requestSkillProving( + licence.skill_id, + licence.version, + { agent: wallet.address, onProving: () => setState("proving") }, + ); if (outcome.kind === "granted") { - downloadArtifact(licence.skillId, licence.version, outcome.artifact); + downloadArtifact(licence.skill_id, licence.version, outcome.artifact); setState("idle"); } else { setState("error"); @@ -132,9 +135,9 @@ function LicenceRow({ } catch (cause) { setState("error"); setMessage( - cause instanceof ApiError + cause instanceof ApiError && cause.status !== 401 ? `${cause.message}${cause.code ? ` (${cause.code})` : ""}` - : String(cause), + : describeProofFailure(cause).message, ); } } @@ -143,19 +146,36 @@ function LicenceRow({
  • - {licence.skillId} + {licence.skill_id} {/* The version never splits: "2026.8.3" on one line and "1" on the next reads as a different version. The id may wrap, it is long. */} @{licence.version} -

    - Minted {formatLedgerTime(licence.mintedAt)} UTC, token # - {licence.tokenId} +

    + + Minted {formatLedgerTime(licence.minted_at)} UTC, token # + {licence.token_id} + + {licence.mint_tx_url ? ( + + mint transaction + + + ) : ( + // The indexer only reaches back about a week, and the licence is + // listed from the contract either way. Saying so beats an empty gap. + mint transaction not indexed + )}

    {message ?

    {message}

    : null}
    @@ -173,14 +193,14 @@ function LicenceRow({ variant="outline" size="sm" onClick={() => void getSkill()} - disabled={state === "loading"} + disabled={state === "loading" || state === "proving"} > - {state === "loading" ? ( + {state === "loading" || state === "proving" ? ( ) : ( )} - Get the skill + {state === "proving" ? "Sign in your wallet..." : "Get the skill"} ) : null} @@ -191,7 +211,7 @@ function LicenceRow({ function LicenceList({ address }: { address: string }) { const wallet = useWallet(); const scan = useLicences(address); - const licences = scan.data?.licences ?? []; + const licences = scan.data?.licenses ?? []; const verdicts = useLicenceVerdicts(licences); const own = wallet.status === "connected" && wallet.address === address; @@ -199,7 +219,7 @@ function LicenceList({ address }: { address: string }) { return (

    - Reading every token from the tokens contract... + Reading the licences this account holds...

    {[0, 1, 2].map((row) => ( @@ -215,7 +235,7 @@ function LicenceList({ address }: { address: string }) { - Could not read the tokens contract + Could not read this account's licences {scan.error.message}. This is not the same as holding no licences: nothing is listed because nothing could be read. @@ -241,9 +261,9 @@ function LicenceList({ address }: { address: string }) { const source = (

    - Read directly from the{" "} + Listed by the API from the{" "} - , {scan.data.scanned} tokens scanned. Verdicts are read per version from - the registry. This page reads the chain token by token until the API - serves this list itself. + , complete up to its supply of {scan.data.total_supply} tokens. Verdicts + are a separate read per version against the registry, because holding a + licence and a version still being SAFE are two different facts.

    ); @@ -314,7 +334,7 @@ function LicenceList({ address }: { address: string }) {
      {[...flagged, ...rest].map(({ licence, verdict }) => ( ); + case "proving": + return ( +
      +

      + + Sign the message in your wallet to prove this licence is yours... +

      + + A signature, not a payment: nothing is charged and no transaction is + sent. + + +
      + ); + case "quoted": { const { requirement, balance } = state; const price = formatBaseUnits(requirement.amount); diff --git a/frontend/src/utils/stellar.test.ts b/frontend/src/utils/stellar.test.ts new file mode 100644 index 0000000..0a6a559 --- /dev/null +++ b/frontend/src/utils/stellar.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; + +import { isAccountAddress } from "./stellar"; + +describe("isAccountAddress", () => { + it("accepts a classic G account", () => { + expect( + isAccountAddress( + "GDAVKROBU6VGWMAY36YMHQ6LV7XD7D5R5T3LJTTEBJKX3EURZAEDHSPL", + ), + ).toBe(true); + }); + + it("refuses what cannot hold a licence", () => { + // Contract and muxed addresses, and anything of the wrong shape. + expect( + isAccountAddress("CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T"), + ).toBe(false); + expect( + isAccountAddress( + "MDAVKROBU6VGWMAY36YMHQ6LV7XD7D5R5T3LJTTEBJKX3EURZAEDHSPLAAAAAAAAAAAAA", + ), + ).toBe(false); + expect( + isAccountAddress( + "gdavkrobu6vgwmay36ymhq6lv7xd7d5r5t3ljtteBJKX3EURZAEDHSPL", + ), + ).toBe(false); + expect(isAccountAddress("G")).toBe(false); + expect(isAccountAddress("")).toBe(false); + }); +}); diff --git a/frontend/src/utils/stellar.ts b/frontend/src/utils/stellar.ts new file mode 100644 index 0000000..61c563f --- /dev/null +++ b/frontend/src/utils/stellar.ts @@ -0,0 +1,10 @@ +/** + * Stellar address shapes, as text. No network, no SDK: a 56 character `G...` + * is the only thing that can hold a licence, and both the licences page and + * its route check that before asking the API. + */ + +/** A classic ed25519 account. Contract (`C...`) and muxed (`M...`) are not. */ +export function isAccountAddress(value: string): boolean { + return /^G[A-Z2-7]{55}$/.test(value); +}