Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frontend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
19 changes: 12 additions & 7 deletions frontend/guides/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down Expand Up @@ -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.
Expand Down
32 changes: 19 additions & 13 deletions frontend/src/hooks/useLicences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})),
});
Expand Down
29 changes: 24 additions & 5 deletions frontend/src/hooks/usePurchase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<UseOutcome, { kind: "granted" }> }
| {
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(
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}
Expand Down
97 changes: 96 additions & 1 deletion frontend/src/lib/api.paid.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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<string, string>;
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(
Expand Down
Loading
Loading