Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

refactor: unify username and email conflict error messages in registration flow

nirholas41b45e69662f
diff --git a/3d-demo/.prettierrc b/3d-demo/.prettierrc
index adeaa28fb..8aba132db 100644
--- a/3d-demo/.prettierrc
+++ b/3d-demo/.prettierrc
@@ -6,5 +6,5 @@
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
- "jsxBracketSameLine": true
-}
\ No newline at end of file
+ "bracketSameLine": true
+}
diff --git a/3d-demo/package.json b/3d-demo/package.json
index ff7db0096..7b2e9f467 100644
--- a/3d-demo/package.json
+++ b/3d-demo/package.json
@@ -32,4 +32,4 @@
"not ie <= 11",
"not op_mini all"
]
-}
\ No newline at end of file
+}
diff --git a/3d-demo/public/index.html b/3d-demo/public/index.html
index 42ae2d2dc..5021a5e8c 100644
--- a/3d-demo/public/index.html
+++ b/3d-demo/public/index.html
@@ -1,17 +1,16 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- <meta name="theme-color" content="#000000">
- <!--
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
+ <meta name="theme-color" content="#000000" />
+ <!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
- <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
- <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
- <!--
+ <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+ <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
+ <!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
@@ -20,15 +19,13 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
- <title>React App</title>
-</head>
+ <title>React App</title>
+ </head>
-<body>
- <noscript>
- You need to enable JavaScript to run this app.
- </noscript>
- <div id="root"></div>
- <!--
+ <body>
+ <noscript> You need to enable JavaScript to run this app. </noscript>
+ <div id="root"></div>
+ <!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
@@ -38,6 +35,5 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
-</body>
-
-</html>
\ No newline at end of file
+ </body>
+</html>
diff --git a/AUTO_DRIVE_REPORT.md b/AUTO_DRIVE_REPORT.md
new file mode 100644
index 000000000..f036ce961
--- /dev/null
+++ b/AUTO_DRIVE_REPORT.md
@@ -0,0 +1,144 @@
+# Autonomous Drive Report
+
+Started: 2026-04-20
+Scope: full project, no commits (user handles), uncommitted changes untouched.
+
+## Baseline
+
+- Branch: `main`, clean against origin/main per `git status`.
+- Heavy WIP: 60+ modified files + several untracked tests (api-keys, validator,
+ widget-types). Did not modify any of these.
+- Pre-run test count: 220 passing, 1 failing in `tests/api/api-keys.test.js`
+ (pre-existing; see "Findings" below).
+
+## Actions taken
+
+### 1. New OAuth authorize tests — `tests/api/oauth-authorize.test.js`
+
+22 tests covering the security-critical authorization endpoint:
+
+- **Validation**: response_type, client_id, redirect_uri, code_challenge,
+ code_challenge_method (PKCE mandatory, S256 only — rejects `plain`).
+- **Strict redirect_uri matching (RFC 6749 §3.1.2.2)**: different host, extra
+ path segment, different protocol, different port, query string, fragment —
+ all rejected.
+- **Unauthenticated flow**: bounce to `/login?next=…` preserving consent URL.
+- **Consent page**: HTML render, CSP/frame-options headers, hidden inputs
+ for PKCE round-trip.
+- **POST consent**: code issuance, deny path, CSRF rejection, cross-site
+ Origin rejection, scope intersection (drops scopes not in client.scope).
+- **Method handling**: 405 on DELETE, 204 on OPTIONS preflight.
+
+### 2. New OAuth token tests — `tests/api/oauth-token.test.js`
+
+24 tests covering the token endpoint:
+
+- **Client auth**: missing client_id, rate limit, unknown client, bad
+ confidential secret, HTTP Basic credentials.
+- **authorization_code grant**: missing fields, unknown code, replay defence
+ (consumed code → revokes refresh chain), expired code, client mismatch,
+ redirect_uri mismatch, PKCE failure, success path issues access+refresh
+ with correct scope, omits refresh when client lacks the grant type.
+- **refresh_token grant**: missing token, success rotation, scope narrowing
+ on subset, **scope-widening attempt rejected with `invalid_scope`**,
+ unknown-scope rejection, propagation of `invalid_grant` and
+ `refresh_reuse_detected` errors.
+
+### 3. New LLM proxy tests — `tests/api/llm-anthropic.test.js`
+
+22 tests covering the we-pay LLM proxy:
+
+- **Policy gating**: missing agent param (400), policy not found (404),
+ brain.mode != we-pay (402), surface.script disabled (403).
+- **Origin enforcement**: attacker origin rejected, server-to-server
+ allowed, first-party localhost allowed.
+- **Rate limiting**: per-IP and per-agent (when policy declares limit).
+- **Monthly call quota**: enforced via Redis counter, `quota_exceeded` 429.
+- **Monthly token budget**: enforced before forwarding (default
+ 1,000,000 tokens; `cost_limit_cents` overrides), debits actual usage on
+ success, does NOT debit on upstream error.
+- **Body + model**: empty messages rejected, model allowlist enforced,
+ policy-default model used when omitted, caller override accepted.
+- **Upstream**: success proxied unchanged, errors sanitized to generic 502
+ (no leaking of upstream error body), usage event recorded with token
+ counts.
+
+### 4. ENS dedup TODO — re-examined and replaced with rationale
+
+The TODO at `api/agents/ens/[name].js:45` suggested deduping with
+`/api/agents/by-address/[addr].js`. After reading both endpoints, they
+return very different shapes:
+
+- ENS endpoint returns a full agent profile (name, description, avatar_id,
+ erc8004_*, etc.).
+- by-address returns a minimal NFT-style shape ({id, chainId, agentURI,
+ manifestUrl, onChain, source}) with chain enumeration fallback.
+
+Extracting a shared helper would add abstraction without removing real
+duplication (only ~6 lines of SQL overlap). Replaced the TODO with a
+comment explaining the divergence so a future reader doesn't repeat the
+investigation.
+
+### 5. Removed-deps verification
+
+`grep -r "fbx-parser|tweakpane"` across `src/`, `api/`, `public/`,
+`scripts/` returned zero hits. `npm run build` succeeded (5.47s, 138 PWA
+precache entries). The package.json removal of these two deps is clean.
+
+## Test summary
+
+| Suite | Tests | Status |
+| --- | --- | --- |
+| OAuth authorize | 22 | ✅ |
+| OAuth token | 24 | ✅ |
+| LLM proxy | 22 | ✅ |
+| **Newly added** | **68** | **✅** |
+| Full suite | 289 | 288 ✅ / 1 ❌ (pre-existing) |
+
+## Findings requiring your decision
+
+### 1. Pre-existing test failure (not caused by this session)
+
+`tests/api/api-keys.test.js:166` expects:
+
+```js
+expect(body.data.token).toMatch(/^sk_live_[a-f0-9]+$/);
+```
+
+But `randomToken()` in `api/_lib/crypto.js` returns base64url, which uses
+`-` and `_` and mixed case. The actual token format is, e.g.,
+`sk_live_3pmN4jIKEd_eeKm4VFdvge_j8K1s_QeVcbLJlKNuTCY`. The regex was
+written against a hex assumption that doesn't match the implementation.
+
+**Suggested fix** (one-line): change the regex to
+`/^sk_live_[A-Za-z0-9_-]+$/`. Did not edit because this test file is in
+your untracked WIP and I don't want to step on in-progress work.
+
+### 2. Coverage gaps still open
+
+Areas with significant uncommitted security logic but no tests yet:
+
+- `api/auth/register.js` — unified error-message changes (now returns
+ `conflict` instead of `username_taken` / `email_taken`).
+- `api/_lib/auth.js` — session rotation logic in `getSessionUser` (rolling
+ refresh window).
+- `api/oauth/introspect.js` and `api/oauth/revoke.js` — both modified, no
+ dedicated test files.
+
+These are good candidates for a follow-on session.
+
+### 3. Things I deliberately did NOT touch
+
+- All 60+ files in your `git status` modified list.
+- All other untracked files (`tests/api/api-keys.test.js`,
+ `tests/src/validator.test.js`, `tests/src/widget-types.test.js`).
+- `package.json` (already in your WIP).
+- `CLAUDE.md` and other docs in your WIP.
+
+Nothing was committed or pushed. All changes from this session are:
+
+- New: `tests/api/oauth-authorize.test.js`
+- New: `tests/api/oauth-token.test.js`
+- New: `tests/api/llm-anthropic.test.js`
+- Edited: `api/agents/ens/[name].js` (TODO → rationale comment, ~6 lines)
+- Edited: this report.
diff --git a/CLAUDE.md b/CLAUDE.md
index ca1043e50..66cd1ae7e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9,6 +9,7 @@ Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-s
**Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing:
+
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
@@ -31,12 +32,14 @@ Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, sim
**Touch only what you must. Clean up only your own mess.**
When editing existing code:
+
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
+
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
@@ -47,11 +50,13 @@ The test: Every changed line should trace directly to the user's request.
**Define success criteria. Loop until verified.**
Transform tasks into verifiable goals:
+
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
+
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
@@ -62,4 +67,4 @@ Strong success criteria let you loop independently. Weak criteria ("make it work
---
-**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
\ No newline at end of file
+**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
diff --git a/README.md b/README.md
index 7fff0efbd..3bf64e9cd 100644
--- a/README.md
+++ b/README.md
@@ -19,11 +19,11 @@ description: 3D Agent is an open-source, browser-native 3D model viewer built on
---
-## 🧠 What is 3D Agent?
+## 🧠 What is 3D Agent?
**3D Agent** is an open-source, browser-native 3D model viewer built on [three.js](https://threejs.org/) (r176). It renders **glTF 2.0** and **GLB** files directly in WebGL — no plugins, no server uploads, no installs. Just open [3dagent.vercel.app](https://3dagent.vercel.app), drop a file, and inspect your model instantly.
-It's built for **3D artists** previewing exports, **game developers** debugging assets, **web developers** integrating models, and **anyone curious** about 3D on the web.
+It's built for **3D artists** previewing exports, **game developers** debugging assets, **web developers** integrating models, and **anyone curious** about 3D on the web.
<br/>
@@ -109,22 +109,22 @@ Open **http://localhost:3000** for the landing page, or **http://localhost:3000/
### Available Scripts
-| Command | What It Does |
-| :----------------------- | :-------------------------------------------------------------------- |
-| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |
-| `npm run dev:lib` | Dev server in library-build mode (`TARGET=lib`) |
-| `npm run build` | Production build to `dist/` |
-| `npm run build:lib` | Build the embeddable library bundle to `dist-lib/` |
-| `npm run build:artifact` | Build the standalone artifact bundle (`vite.config.artifact.js`) |
-| `npm run build:all` | `build` + `build:lib` + `publish:lib` |
-| `npm run publish:lib` | Run `scripts/publish-lib.mjs` to publish versioned `agent-3d` bundles |
-| `npm run test` | Run Vitest test suite |
-| `npm run verify` | `prettier --check .` + `vite build` |
-| `npm run format` | Run Prettier write across the repo |
-| `npm run deploy` | `build:all` + `vercel --prod` |
-| `npm run clean` | Wipe `dist/` and `dist-lib/` |
-| `npm run generate-icons` | Regenerate PWA icons (`scripts/generate-pwa-icons.mjs`) |
-| `npm run fetch-animations` | Download animation assets (`scripts/download-animations.mjs`) |
+| Command | What It Does |
+| :------------------------- | :-------------------------------------------------------------------- |
+| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |
+| `npm run dev:lib` | Dev server in library-build mode (`TARGET=lib`) |
+| `npm run build` | Production build to `dist/` |
+| `npm run build:lib` | Build the embeddable library bundle to `dist-lib/` |
+| `npm run build:artifact` | Build the standalone artifact bundle (`vite.config.artifact.js`) |
+| `npm run build:all` | `build` + `build:lib` + `publish:lib` |
+| `npm run publish:lib` | Run `scripts/publish-lib.mjs` to publish versioned `agent-3d` bundles |
+| `npm run test` | Run Vitest test suite |
+| `npm run verify` | `prettier --check .` + `vite build` |
+| `npm run format` | Run Prettier write across the repo |
+| `npm run deploy` | `build:all` + `vercel --prod` |
+| `npm run clean` | Wipe `dist/` and `dist-lib/` |
+| `npm run generate-icons` | Regenerate PWA icons (`scripts/generate-pwa-icons.mjs`) |
+| `npm run fetch-animations` | Download animation assets (`scripts/download-animations.mjs`) |
<br/>
@@ -191,20 +191,20 @@ Open **http://localhost:3000** for the landing page, or **http://localhost:3000/
### Tech Stack
-| Layer | Technology |
-| :---------------- | :----------------------------------------------------------------------------------------- |
-| **Rendering** | [three.js](https://threejs.org/) r176 — WebGL 2.0 |
-| **Model Loading** | `GLTFLoader` + `DRACOLoader` + `KTX2Loader` + `MeshoptDecoder` |
-| **Controls** | `OrbitControls` — pan, zoom, rotate |
-| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) + [tweakpane](https://tweakpane.github.io/docs/) — real-time parameter tweaking |
-| **Validation** | [gltf-validator](https://github.com/KhronosGroup/gltf-validator) — Khronos spec compliance |
-| **Templating** | [vhtml](https://github.com/developit/vhtml) — JSX → HTML string rendering |
-| **Drag & Drop** | [simple-dropzone](https://github.com/donmccurdy/simple-dropzone) |
-| **Build** | [Vite](https://vitejs.dev/) 7 — sub-second HMR |
-| **Backend** | Vercel serverless functions · [Neon](https://neon.tech/) Postgres · Cloudflare R2 · [Upstash](https://upstash.com/) Redis |
+| Layer | Technology |
+| :---------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Rendering** | [three.js](https://threejs.org/) r176 — WebGL 2.0 |
+| **Model Loading** | `GLTFLoader` + `DRACOLoader` + `KTX2Loader` + `MeshoptDecoder` |
+| **Controls** | `OrbitControls` — pan, zoom, rotate |
+| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) + [tweakpane](https://tweakpane.github.io/docs/) — real-time parameter tweaking |
+| **Validation** | [gltf-validator](https://github.com/KhronosGroup/gltf-validator) — Khronos spec compliance |
+| **Templating** | [vhtml](https://github.com/developit/vhtml) — JSX → HTML string rendering |
+| **Drag & Drop** | [simple-dropzone](https://github.com/donmccurdy/simple-dropzone) |
+| **Build** | [Vite](https://vitejs.dev/) 7 — sub-second HMR |
+| **Backend** | Vercel serverless functions · [Neon](https://neon.tech/) Postgres · Cloudflare R2 · [Upstash](https://upstash.com/) Redis |
| **Auth** | Session JWT ([`jose`](https://github.com/panva/jose)) · [SIWE](https://eips.ethereum.org/EIPS/eip-4361) / [viem](https://viem.sh/) + [ethers](https://ethers.org/) · [Privy](https://www.privy.io/) |
-| **Testing** | [Vitest](https://vitest.dev/) |
-| **Hosting** | [Vercel](https://vercel.com/) — edge CDN + cron |
+| **Testing** | [Vitest](https://vitest.dev/) |
+| **Hosting** | [Vercel](https://vercel.com/) — edge CDN + cron |
<br/>
@@ -245,53 +245,53 @@ Routing is driven by [`vercel.json`](vercel.json). High-level map:
### Pages
-| Path | Serves |
-| :------------------------------ | :-------------------------------------------- |
-| `/` | `index.html` — landing |
-| `/app`, `/deploy`, `/a/*` | `app.html` — viewer + deploy flow |
-| `/home` | `home.html` |
-| `/features` | `features.html` |
-| `/create` | `create.html` — avatar + agent creation |
-| `/agent`, `/agent/<id>` | Agent detail page |
-| `/agent/<id>/edit`, `/embed` | Agent edit + embed surfaces |
-| `/studio`, `/widgets`, `/widgets/...` | Widget Studio + gallery |
-| `/w/<id>` | Rendered widget page (with OG + oEmbed) |
-| `/dashboard`, `/dashboard/...` | Authenticated dashboard (storage, usage) |
-| `/discover`, `/explore` | Directories |
-| `/artifact`, `/hydrate`, `/cz`, `/validation`, `/lobehub/iframe` | Standalone subapps |
-| `/login`, `/register` | Auth pages |
-| `/docs/widgets` | Widgets documentation |
+| Path | Serves |
+| :--------------------------------------------------------------- | :--------------------------------------- |
+| `/` | `index.html` — landing |
+| `/app`, `/deploy`, `/a/*` | `app.html` — viewer + deploy flow |
+| `/home` | `home.html` |
+| `/features` | `features.html` |
+| `/create` | `create.html` — avatar + agent creation |
+| `/agent`, `/agent/<id>` | Agent detail page |
+| `/agent/<id>/edit`, `/embed` | Agent edit + embed surfaces |
+| `/studio`, `/widgets`, `/widgets/...` | Widget Studio + gallery |
+| `/w/<id>` | Rendered widget page (with OG + oEmbed) |
+| `/dashboard`, `/dashboard/...` | Authenticated dashboard (storage, usage) |
+| `/discover`, `/explore` | Directories |
+| `/artifact`, `/hydrate`, `/cz`, `/validation`, `/lobehub/iframe` | Standalone subapps |
+| `/login`, `/register` | Auth pages |
+| `/docs/widgets` | Widgets documentation |
### API
-| Path | Purpose |
-| :------------------------------------------------ | :--------------------------------------------------- |
-| `/api/agents`, `/api/agents/<id>` | Agent CRUD, wallet, sign, embed-policy, usage |
-| `/api/agents/suggest`, `/api/agents/by-wallet` | Lookup helpers |
-| `/api/agent-actions`, `/api/agent-memory` | Agent actions + memory store |
-| `/api/widgets`, `/api/widgets/<id>` | Widget CRUD, duplicate, stats, view |
-| `/api/widgets/oembed`, `/api/widgets/<id>/og` | oEmbed + Open Graph card |
-| `/api/avatars/<id>/...` | Storage mode + IPFS pinning |
-| `/api/auth/...`, `/oauth/...` | Sessions + OAuth 2.1 authorization server |
-| `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource` | Discovery docs |
-| `/api/mcp` | Model Context Protocol endpoint |
-| `/api/llm/anthropic` | LLM proxy |
-| `/api/erc8004/hydrate`, `/api/erc8004/import`, `/api/erc8004/pin` | ERC-8004 passport tools |
-| `/api/dca-strategies`, `/api/subscriptions.js` | Scheduled on-chain actions |
-| `/api/cz/claim` | CZ claim flow |
-| `/api/chat`, `/api/tts/*`, `/api/animations/*` | Chat, TTS, animation services |
-| `/a/<chain>/<id>`, `/a/<chain>/<id>/embed`, `/api/a/<chain>/<id>/og` | Attestation pages + OG |
+| Path | Purpose |
+| :--------------------------------------------------------------------------------- | :-------------------------------------------- |
+| `/api/agents`, `/api/agents/<id>` | Agent CRUD, wallet, sign, embed-policy, usage |
+| `/api/agents/suggest`, `/api/agents/by-wallet` | Lookup helpers |
+| `/api/agent-actions`, `/api/agent-memory` | Agent actions + memory store |
+| `/api/widgets`, `/api/widgets/<id>` | Widget CRUD, duplicate, stats, view |
+| `/api/widgets/oembed`, `/api/widgets/<id>/og` | oEmbed + Open Graph card |
+| `/api/avatars/<id>/...` | Storage mode + IPFS pinning |
+| `/api/auth/...`, `/oauth/...` | Sessions + OAuth 2.1 authorization server |
+| `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource` | Discovery docs |
+| `/api/mcp` | Model Context Protocol endpoint |
+| `/api/llm/anthropic` | LLM proxy |
+| `/api/erc8004/hydrate`, `/api/erc8004/import`, `/api/erc8004/pin` | ERC-8004 passport tools |
+| `/api/dca-strategies`, `/api/subscriptions.js` | Scheduled on-chain actions |
+| `/api/cz/claim` | CZ claim flow |
+| `/api/chat`, `/api/tts/*`, `/api/animations/*` | Chat, TTS, animation services |
+| `/a/<chain>/<id>`, `/a/<chain>/<id>/embed`, `/api/a/<chain>/<id>/og` | Attestation pages + OG |
### Cron jobs
Scheduled in `vercel.json` → `crons`:
-| Schedule | Handler |
-| :-------------- | :---------------------------------- |
-| `*/15 * * * *` | `/api/cron/erc8004-crawl` |
-| `*/5 * * * *` | `/api/cron/index-delegations` |
-| `0 * * * *` | `/api/cron/run-dca` |
-| `0 * * * *` | `/api/cron/run-subscriptions` |
+| Schedule | Handler |
+| :------------- | :---------------------------- |
+| `*/15 * * * *` | `/api/cron/erc8004-crawl` |
+| `*/5 * * * *` | `/api/cron/index-delegations` |
+| `0 * * * *` | `/api/cron/run-dca` |
+| `0 * * * *` | `/api/cron/run-subscriptions` |
<br/>
diff --git a/agent-edit.html b/agent-edit.html
index 19f4d09a9..047bccd35 100644
--- a/agent-edit.html
+++ b/agent-edit.html
@@ -400,45 +400,85 @@
</header>
<div class="edit-tabs" role="tablist" aria-label="Edit sections">
- <button class="edit-tab active" data-tab="persona" role="tab" aria-selected="true" aria-controls="panel-persona" id="tab-persona">Persona</button>
- <button class="edit-tab" data-tab="outfit" role="tab" aria-selected="false" aria-controls="panel-outfit" id="tab-outfit">Outfit</button>
+ <button
+ class="edit-tab active"
+ data-tab="persona"
+ role="tab"
+ aria-selected="true"
+ aria-controls="panel-persona"
+ id="tab-persona"
+ >
+ Persona
+ </button>
+ <button
+ class="edit-tab"
+ data-tab="outfit"
+ role="tab"
+ aria-selected="false"
+ aria-controls="panel-outfit"
+ id="tab-outfit"
+ >
+ Outfit
+ </button>
</div>
<main id="main">
- <div id="loading" class="loading-msg" role="status" aria-live="polite">Loading…</div>
- <div id="error" class="error-msg" style="display: none" role="alert"></div>
-
- <!-- Persona tab -->
- <section class="edit-panel persona-panel" id="panel-persona" role="tabpanel" aria-labelledby="tab-persona">
- <div class="form-group">
- <label class="form-label" for="f-name">Name</label>
- <input class="form-input" id="f-name" type="text" maxlength="100" />
- </div>
- <div class="form-group">
- <label class="form-label" for="f-desc">Description</label>
- <textarea class="form-textarea" id="f-desc" rows="4" maxlength="500"></textarea>
- </div>
- <div class="form-actions">
- <button class="btn-primary" id="persona-save">Save</button>
- <span class="form-status" id="persona-status" role="status" aria-live="polite"></span>
- </div>
- </section>
-
- <!-- Outfit tab -->
- <section class="edit-panel outfit-panel" id="panel-outfit" role="tabpanel" aria-labelledby="tab-outfit" hidden>
- <div class="outfit-preview" id="outfit-preview" aria-label="Avatar preview">
- <!-- agent-3d inserted here once avatar is confirmed -->
- </div>
- <div class="outfit-controls" id="outfit-controls">
- <div class="outfit-header">
- <h2 class="outfit-title">Materials</h2>
- <button class="btn-reset-all" id="btn-reset-all" aria-label="Reset all materials">Reset all</button>
+ <div id="loading" class="loading-msg" role="status" aria-live="polite">Loading…</div>
+ <div id="error" class="error-msg" style="display: none" role="alert"></div>
+
+ <!-- Persona tab -->
+ <section
+ class="edit-panel persona-panel"
+ id="panel-persona"
+ role="tabpanel"
+ aria-labelledby="tab-persona"
+ >
+ <div class="form-group">
+ <label class="form-label" for="f-name">Name</label>
+ <input class="form-input" id="f-name" type="text" maxlength="100" />
</div>
- <div id="mat-list">
- <div class="no-named-mats">Loading preview…</div>
+ <div class="form-group">
+ <label class="form-label" for="f-desc">Description</label>
+ <textarea class="form-textarea" id="f-desc" rows="4" maxlength="500"></textarea>
</div>
- </div>
- </section>
+ <div class="form-actions">
+ <button class="btn-primary" id="persona-save">Save</button>
+ <span
+ class="form-status"
+ id="persona-status"
+ role="status"
+ aria-live="polite"
+ ></span>
+ </div>
+ </section>
+
+ <!-- Outfit tab -->
+ <section
+ class="edit-panel outfit-panel"
+ id="panel-outfit"
+ role="tabpanel"
+ aria-labelledby="tab-outfit"
+ hidden
+ >
+ <div class="outfit-preview" id="outfit-preview" aria-label="Avatar preview">
+ <!-- agent-3d inserted here once avatar is confirmed -->
+ </div>
+ <div class="outfit-controls" id="outfit-controls">
+ <div class="outfit-header">
+ <h2 class="outfit-title">Materials</h2>
+ <button
+ class="btn-reset-all"
+ id="btn-reset-all"
+ aria-label="Reset all materials"
+ >
+ Reset all
+ </button>
+ </div>
+ <div id="mat-list">
+ <div class="no-named-mats">Loading preview…</div>
+ </div>
+ </div>
+ </section>
</main>
<div class="outfit-status" id="outfit-status" role="status" aria-live="polite"></div>
@@ -510,9 +550,10 @@
e.preventDefault();
const arr = Array.from(editTabs);
const i = arr.indexOf(btn);
- const next = e.key === 'ArrowRight'
- ? arr[(i + 1) % arr.length]
- : arr[(i - 1 + arr.length) % arr.length];
+ const next =
+ e.key === 'ArrowRight'
+ ? arr[(i + 1) % arr.length]
+ : arr[(i - 1 + arr.length) % arr.length];
activateTab(next.dataset.tab);
next.focus();
});
diff --git a/agent-embed.html b/agent-embed.html
index 2c0643b8f..86a811434 100644
--- a/agent-embed.html
+++ b/agent-embed.html
@@ -240,27 +240,72 @@
const clouds = new Clouds({ limit: 350 });
// Deep background sweep — wide, slow, anchors the scene
- const back = new Cloud({ seed: 1, segments: 40, bounds: [14, 5, 4], volume: 4, color: '#7a9ad8', fade: 32, opacity: 0.9, speed: 0.012 });
+ const back = new Cloud({
+ seed: 1,
+ segments: 40,
+ bounds: [14, 5, 4],
+ volume: 4,
+ color: '#7a9ad8',
+ fade: 32,
+ opacity: 0.9,
+ speed: 0.012,
+ });
back.position.set(0, 1.5, -9);
clouds.add(back);
// Mid left — cool blue wisps
- const left = new Cloud({ seed: 7, segments: 25, bounds: [6, 2.5, 2], volume: 3, color: '#b8ccff', fade: 20, opacity: 0.65, speed: 0.038 });
+ const left = new Cloud({
+ seed: 7,
+ segments: 25,
+ bounds: [6, 2.5, 2],
+ volume: 3,
+ color: '#b8ccff',
+ fade: 20,
+ opacity: 0.65,
+ speed: 0.038,
+ });
left.position.set(-3.5, 0.8, -5);
clouds.add(left);
// Mid right — slightly warmer, offset depth
- const right = new Cloud({ seed: 13, segments: 25, bounds: [6, 2, 2], volume: 3, color: '#ccd8ff', fade: 22, opacity: 0.6, speed: 0.05 });
+ const right = new Cloud({
+ seed: 13,
+ segments: 25,
+ bounds: [6, 2, 2],
+ volume: 3,
+ color: '#ccd8ff',
+ fade: 22,
+ opacity: 0.6,
+ speed: 0.05,
+ });
right.position.set(3.2, 1.2, -6);
clouds.add(right);
// Foreground haze — etheral and close, fades fast
- const fore = new Cloud({ seed: 42, segments: 15, bounds: [4, 1.5, 1], volume: 2, color: 'white', fade: 7, opacity: 0.28, speed: 0.07 });
+ const fore = new Cloud({
+ seed: 42,
+ segments: 15,
+ bounds: [4, 1.5, 1],
+ volume: 2,
+ color: 'white',
+ fade: 7,
+ opacity: 0.28,
+ speed: 0.07,
+ });
fore.position.set(0, -0.8, -2);
clouds.add(fore);
// Upper accent — gives vertical depth
- const top = new Cloud({ seed: 99, segments: 18, bounds: [8, 2, 2], volume: 3.5, color: '#a0b8f0', fade: 25, opacity: 0.5, speed: 0.025 });
+ const top = new Cloud({
+ seed: 99,
+ segments: 18,
+ bounds: [8, 2, 2],
+ volume: 3.5,
+ color: '#a0b8f0',
+ fade: 25,
+ opacity: 0.5,
+ speed: 0.025,
+ });
top.position.set(-1, 4, -7);
clouds.add(top);
diff --git a/agent-home.html b/agent-home.html
index 4cb9c39e9..eb56467c7 100644
--- a/agent-home.html
+++ b/agent-home.html
@@ -338,49 +338,100 @@
</header>
<main id="main">
- <div class="agent-page-hero">
- <h1 class="agent-page-title" id="page-agent-name">Agent</h1>
- <p class="agent-page-subtitle" id="page-agent-desc">Embodied. Present. Persistent.</p>
- </div>
-
- <div class="agent-page-card-wrap">
- <div id="agent-home-container" aria-live="polite" aria-busy="true">
- <div class="loading-placeholder">Loading agent…</div>
+ <div class="agent-page-hero">
+ <h1 class="agent-page-title" id="page-agent-name">Agent</h1>
+ <p class="agent-page-subtitle" id="page-agent-desc">
+ Embodied. Present. Persistent.
+ </p>
</div>
- </div>
-
- <section class="agent-skills-full" id="agent-skills-section" style="display: none" aria-labelledby="agent-skills-heading">
- <h2 class="agent-skills-title" id="agent-skills-heading">Skills</h2>
- <div class="agent-skills-grid" id="agent-skills-grid"></div>
- </section>
-
- <section class="agent-embed-hint" id="agent-embed-section" style="display: none" aria-labelledby="agent-embed-heading">
- <h2 class="agent-embed-label" id="agent-embed-heading">Share &amp; embed</h2>
- <div class="agent-embed-tabs" role="tablist" aria-label="Embed format">
- <button class="agent-embed-tab active" data-tab="iframe" role="tab" aria-selected="true" aria-controls="agent-embed-code" id="embed-tab-iframe">iframe</button>
- <button class="agent-embed-tab" data-tab="link" role="tab" aria-selected="false" aria-controls="agent-embed-code" id="embed-tab-link">link</button>
- <button class="agent-embed-tab" data-tab="webcomponent" role="tab" aria-selected="false" aria-controls="agent-embed-code" id="embed-tab-webcomponent">&lt;agent-3d&gt;</button>
- </div>
- <div class="agent-embed-code-wrap">
- <div class="agent-embed-code" id="agent-embed-code" role="tabpanel" aria-labelledby="embed-tab-iframe" aria-live="polite"></div>
- <button class="agent-embed-copy" id="agent-embed-copy" aria-label="Copy embed code">copy</button>
+
+ <div class="agent-page-card-wrap">
+ <div id="agent-home-container" aria-live="polite" aria-busy="true">
+ <div class="loading-placeholder">Loading agent…</div>
+ </div>
</div>
- <a
- class="agent-embed-preview-link"
- id="agent-embed-preview"
- target="_blank"
- rel="noopener"
- >preview embed →</a
+
+ <section
+ class="agent-skills-full"
+ id="agent-skills-section"
+ style="display: none"
+ aria-labelledby="agent-skills-heading"
>
- <a
- class="agent-embed-preview-link"
- id="agent-embed-settings"
- href=""
- target="_blank"
- rel="noopener"
- >embed settings →</a
+ <h2 class="agent-skills-title" id="agent-skills-heading">Skills</h2>
+ <div class="agent-skills-grid" id="agent-skills-grid"></div>
+ </section>
+
+ <section
+ class="agent-embed-hint"
+ id="agent-embed-section"
+ style="display: none"
+ aria-labelledby="agent-embed-heading"
>
- </section>
+ <h2 class="agent-embed-label" id="agent-embed-heading">Share &amp; embed</h2>
+ <div class="agent-embed-tabs" role="tablist" aria-label="Embed format">
+ <button
+ class="agent-embed-tab active"
+ data-tab="iframe"
+ role="tab"
+ aria-selected="true"
+ aria-controls="agent-embed-code"
+ id="embed-tab-iframe"
+ >
+ iframe
+ </button>
+ <button
+ class="agent-embed-tab"
+ data-tab="link"
+ role="tab"
+ aria-selected="false"
+ aria-controls="agent-embed-code"
+ id="embed-tab-link"
+ >
+ link
+ </button>
+ <button
+ class="agent-embed-tab"
+ data-tab="webcomponent"
+ role="tab"
+ aria-selected="false"
+ aria-controls="agent-embed-code"
+ id="embed-tab-webcomponent"
+ >
+ &lt;agent-3d&gt;
+ </button>
+ </div>
+ <div class="agent-embed-code-wrap">
+ <div
+ class="agent-embed-code"
+ id="agent-embed-code"
+ role="tabpanel"
+ aria-labelledby="embed-tab-iframe"
+ aria-live="polite"
+ ></div>
+ <button
+ class="agent-embed-copy"
+ id="agent-embed-copy"
+ aria-label="Copy embed code"
+ >
+ copy
+ </button>
+ </div>
+ <a
+ class="agent-embed-preview-link"
+ id="agent-embed-preview"
+ target="_blank"
+ rel="noopener"
+ >preview embed →</a
+ >
+ <a
+ class="agent-embed-preview-link"
+ id="agent-embed-settings"
+ href=""
+ target="_blank"
+ rel="noopener"
+ >embed settings →</a
+ >
+ </section>
</main>
<script type="module">
@@ -472,9 +523,10 @@
e.preventDefault();
const arr = Array.from(embedTabs);
const i = arr.indexOf(btn);
- const next = e.key === 'ArrowRight'
- ? arr[(i + 1) % arr.length]
- : arr[(i - 1 + arr.length) % arr.length];
+ const next =
+ e.key === 'ArrowRight'
+ ? arr[(i + 1) % arr.length]
+ : arr[(i - 1 + arr.length) % arr.length];
selectTab(next);
next.focus();
});
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 5aa4c62d2..6787096e3 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -42,6 +42,9 @@ export async function mintAccessToken({ userId, clientId, scope, resource, token
}
export async function verifyAccessToken(token, { audience } = {}) {
+ // Passing `issuer` to jose.jwtVerify enforces the `iss` claim equals
+ // env.ISSUER and throws otherwise — no separate check needed in
+ // authenticateBearer(), which treats any throw here as auth failure.
const { payload } = await jwtVerify(token, jwtKey(), {
issuer: env.ISSUER,
audience: audience || env.MCP_RESOURCE,
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index fe681095d..9a3b818a0 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -94,7 +94,8 @@ export const limits = {
window: '1 m',
}).limit(agentId),
// Gas-spending endpoints: 10 redeems per 5 minutes per IP
- strict: (key) => getLimiter('permissions:redeem:strict', { limit: 10, window: '5 m' }).limit(key),
+ strict: (key) =>
+ getLimiter('permissions:redeem:strict', { limit: 10, window: '5 m' }).limit(key),
pinUser: (userId) => getLimiter('pin:user', { limit: 30, window: '1 h' }).limit(userId),
pinStatusIp: (ip) => getLimiter('pin:status:ip', { limit: 60, window: '1 m' }).limit(ip),
agentByAddress: (ip) =>
diff --git a/api/agents/ens/[name].js b/api/agents/ens/[name].js
index a16392123..1e1147126 100644
--- a/api/agents/ens/[name].js
+++ b/api/agents/ens/[name].js
@@ -42,7 +42,11 @@ async function resolveEns(name) {
}
async function agentsByAddress(address) {
- // TODO: dedupe with /api/agents/by-address once that endpoint exists (prompt 19)
+ // Note: /api/agents/by-address/[addr].js exists but returns a minimal NFT-style
+ // shape ({id, chainId, agentURI, manifestUrl, onChain, source}) with chain
+ // enumeration fallback. This endpoint returns the full agent profile for ENS
+ // → identity resolution. The two queries differ enough that extracting a
+ // shared helper would add abstraction without removing real duplication.
const rows = await sql`
SELECT id, name, description, avatar_id, home_url,
erc8004_agent_id, erc8004_registry, chain_id,
diff --git a/api/api-keys.js b/api/api-keys.js
index ea7a29e22..0b1c4fcf6 100644
--- a/api/api-keys.js
+++ b/api/api-keys.js
@@ -6,12 +6,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { parse } from './_lib/validate.js';
import { z } from 'zod';
-const ALLOWED_SCOPES = new Set([
- 'avatars:read',
- 'avatars:write',
- 'avatars:delete',
- 'profile',
-]);
+const ALLOWED_SCOPES = new Set(['avatars:read', 'avatars:write', 'avatars:delete', 'profile']);
const createSchema = z.object({
name: z.string().trim().min(1).max(80),
diff --git a/api/auth/register.js b/api/auth/register.js
index 7b3c6093c..7d0795271 100644
--- a/api/auth/register.js
+++ b/api/auth/register.js
@@ -25,7 +25,7 @@ export default wrap(async (req, res) => {
const existing =
await sql`select id from users where display_name ilike ${body.username} and deleted_at is null limit 1`;
- if (existing[0]) return error(res, 409, 'username_taken', 'that username is already taken');
+ if (existing[0]) return error(res, 409, 'conflict', 'email or username already in use');
} else {
const body = parse(registerBody, raw);
email = body.email;
@@ -34,8 +34,7 @@ export default wrap(async (req, res) => {
const existing =
await sql`select id from users where email = ${email} and deleted_at is null limit 1`;
- if (existing[0])
- return error(res, 409, 'email_taken', 'an account with this email already exists');
+ if (existing[0]) return error(res, 409, 'conflict', 'email or username already in use');
}
const hash = await hashPassword(password);
diff --git a/api/auth/sessions/[id].js b/api/auth/sessions/[id].js
index e1fd2b11c..c16190744 100644
--- a/api/auth/sessions/[id].js
+++ b/api/auth/sessions/[id].js
@@ -24,7 +24,12 @@ export default wrap(async (req, res) => {
if (!rows[0]) return error(res, 404, 'not_found', 'session not found');
if (sessionId === user.sid)
- return error(res, 409, 'cannot_revoke_current', 'use POST /api/auth/logout to end the current session');
+ return error(
+ res,
+ 409,
+ 'cannot_revoke_current',
+ 'use POST /api/auth/logout to end the current session',
+ );
await sql`update sessions set revoked_at = now() where id = ${sessionId}`;
return json(res, 200, { revoked: 1 });
diff --git a/api/auth/siwe/nonce.js b/api/auth/siwe/nonce.js
index 1d1f85136..cdc5b9291 100644
--- a/api/auth/siwe/nonce.js
+++ b/api/auth/siwe/nonce.js
@@ -37,7 +37,7 @@ export default wrap(async (req, res) => {
const csrf = await hmacSha256(env.JWT_SECRET, `csrf-siwe:${csrfRaw}`);
res.setHeader(
'set-cookie',
- `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${NONCE_TTL_SEC}`,
+ `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${NONCE_TTL_SEC}`,
);
const issuedAt = new Date().toISOString();
diff --git a/api/auth/siwe/verify.js b/api/auth/siwe/verify.js
index af891c68b..bc10d9e8e 100644
--- a/api/auth/siwe/verify.js
+++ b/api/auth/siwe/verify.js
@@ -53,12 +53,13 @@ export default wrap(async (req, res) => {
const appOrigin = env.APP_ORIGIN;
const appHost = new URL(appOrigin).host;
const vercelHost = process.env.VERCEL_URL || null;
- const isLocalDev = process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
+ const isLocalDev =
+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
// In local dev, accept any localhost domain so vercel dev works without
// overriding PUBLIC_APP_ORIGIN.
- const domainOk = allowedHosts.has(fields.domain) ||
- (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));
+ const domainOk =
+ allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));
if (!domainOk) {
return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);
}
@@ -67,10 +68,10 @@ export default wrap(async (req, res) => {
const allowedOrigins = new Set(
[appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean),
);
- const originOk = allowedOrigins.has(u.origin) ||
+ const originOk =
+ allowedOrigins.has(u.origin) ||
(isLocalDev && /^https?:\/\/localhost(:\d+)?$/.test(u.origin));
- if (!originOk)
- return error(res, 400, 'invalid_uri', 'uri origin mismatch');
+ if (!originOk) return error(res, 400, 'invalid_uri', 'uri origin mismatch');
} catch {
return error(res, 400, 'invalid_uri', 'uri not a valid URL');
}
diff --git a/api/auth/wallets/_link-nonces.js b/api/auth/wallets/_link-nonces.js
index 2f3ecbf6e..9ad210d39 100644
--- a/api/auth/wallets/_link-nonces.js
+++ b/api/auth/wallets/_link-nonces.js
@@ -1,7 +1,7 @@
// In-memory nonce store for wallet linking. Separate from login nonces.
// Used by nonce.js (issuer) and index.js (validator).
-import { randomToken } from '../_lib/crypto.js';
+import { randomToken } from '../../_lib/crypto.js';
export const NONCE_TTL_SEC = 5 * 60;
const nonceStore = new Map();
diff --git a/api/cron/index-delegations.js b/api/cron/index-delegations.js
index 1434fc1f9..23b6c7be9 100644
--- a/api/cron/index-delegations.js
+++ b/api/cron/index-delegations.js
@@ -97,7 +97,9 @@ export default wrap(async (req, res) => {
INSERT INTO usage_events (kind, tool, status, latency_ms)
VALUES ('permissions.indexer.tick', 'index-delegations', 'ok', ${Date.now() - started})
`;
- } catch { /* non-fatal */ }
+ } catch {
+ /* non-fatal */
+ }
return json(res, 200, report);
});
@@ -203,7 +205,9 @@ async function rpc(url, method, params) {
if (!res.ok) throw new Error(`RPC HTTP ${res.status} from ${url}`);
const data = await res.json();
if (data.error) {
- throw new Error(`RPC ${method} error: ${data.error.message ?? JSON.stringify(data.error)}`);
+ throw new Error(
+ `RPC ${method} error: ${data.error.message ?? JSON.stringify(data.error)}`,
+ );
}
return data.result;
} finally {
diff --git a/api/cron/run-dca.js b/api/cron/run-dca.js
index 1655ee1fd..8448039a8 100644
--- a/api/cron/run-dca.js
+++ b/api/cron/run-dca.js
@@ -71,7 +71,14 @@ function isTransient(err) {
const name = err?.name;
const status = err?.status;
if (name === 'AbortError' || name === 'TimeoutError') return true;
- if (code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EAI_AGAIN') return true;
+ if (
+ code === 'ETIMEDOUT' ||
+ code === 'ECONNRESET' ||
+ code === 'ECONNREFUSED' ||
+ code === 'ENOTFOUND' ||
+ code === 'EAI_AGAIN'
+ )
+ return true;
if (typeof status === 'number' && status >= 500 && status < 600) return true;
// viem transport errors
const msg = String(err?.message || '');
@@ -89,7 +96,13 @@ async function withRetry(fn, { retries, backoffMs = 500, label }) {
attempt++;
if (attempt > retries || !isTransient(err)) throw err;
const delay = backoffMs * 2 ** (attempt - 1);
- log('warn', 'retry', { label, attempt, delay_ms: delay, message: err?.message, code: err?.code });
+ log('warn', 'retry', {
+ label,
+ attempt,
+ delay_ms: delay,
+ message: err?.message,
+ code: err?.code,
+ });
await new Promise((r) => setTimeout(r, delay));
}
}
@@ -147,8 +160,7 @@ async function getVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amount
});
// Divergence in basis points: |q2-q1| / q1 * 10000
- const divergenceBps =
- q1 === 0n ? 0 : Number(((q2 > q1 ? q2 - q1 : q1 - q2) * 10000n) / q1);
+ const divergenceBps = q1 === 0n ? 0 : Number(((q2 > q1 ? q2 - q1 : q1 - q2) * 10000n) / q1);
if (divergenceBps > 50) {
throw Object.assign(
@@ -237,7 +249,10 @@ async function onPeriod(strategy) {
} = strategy;
const cfg = CHAIN_CONFIG[chainId];
- if (!cfg) throw Object.assign(new Error(`No config for chainId ${chainId}`), { code: 'unsupported_chain' });
+ if (!cfg)
+ throw Object.assign(new Error(`No config for chainId ${chainId}`), {
+ code: 'unsupported_chain',
+ });
const client = getViemClient(chainId);
const logCtx = { strategy_id: strategyId, chain_id: chainId };
@@ -262,7 +277,9 @@ async function onPeriod(strategy) {
LIMIT 1
`;
if (!delegationRow) {
- throw Object.assign(new Error('Delegation not found or no longer active'), { code: 'delegation_gone' });
+ throw Object.assign(new Error('Delegation not found or no longer active'), {
+ code: 'delegation_gone',
+ });
}
const recipient = delegationRow.delegator_address;
@@ -298,7 +315,7 @@ export default wrap(async (req, res) => {
}
}
- const runId = (globalThis.crypto?.randomUUID?.() ?? `run_${Date.now()}`);
+ const runId = globalThis.crypto?.randomUUID?.() ?? `run_${Date.now()}`;
log('info', 'tick_start', { run_id: runId });
// Fetch all due active strategies
@@ -403,7 +420,11 @@ export default wrap(async (req, res) => {
WHERE id = ${strategy.id}
`;
- log('info', 'execute_success', { ...logCtx, tx_hash: txHash, divergence_bps: divergenceBps });
+ log('info', 'execute_success', {
+ ...logCtx,
+ tx_hash: txHash,
+ divergence_bps: divergenceBps,
+ });
results.push({ id: strategy.id, txHash, quoteAmountOut });
} catch (err) {
execRow.status = err.code === 'quote_divergence' ? 'aborted' : 'failed';
@@ -423,9 +444,7 @@ export default wrap(async (req, res) => {
UPDATE dca_strategies
SET next_execution_at = ${nowIso}
WHERE id = ${strategy.id}
- `.catch((e) =>
- log('error', 'claim_release_failed', { ...logCtx, message: e?.message }),
- );
+ `.catch((e) => log('error', 'claim_release_failed', { ...logCtx, message: e?.message }));
}
log('error', 'execute_failed', {
diff --git a/api/cron/run-subscriptions.js b/api/cron/run-subscriptions.js
index dcfbe638b..5e7af244c 100644
--- a/api/cron/run-subscriptions.js
+++ b/api/cron/run-subscriptions.js
@@ -27,10 +27,7 @@ const USDC_BY_CHAIN = {
// Max time we'll wait for the skill's onPeriod (which fetches the relayer).
// Override via SUBSCRIPTION_CHARGE_TIMEOUT_MS.
-const ONPERIOD_TIMEOUT_MS = parseInt(
- process.env.SUBSCRIPTION_CHARGE_TIMEOUT_MS ?? '30000',
- 10,
-);
+const ONPERIOD_TIMEOUT_MS = parseInt(process.env.SUBSCRIPTION_CHARGE_TIMEOUT_MS ?? '30000', 10);
// Structured log helper — single-line JSON so Vercel log drains can parse it.
function log(event, fields = {}) {
@@ -222,7 +219,8 @@ export default wrap(async (req, res) => {
'onPeriod',
);
} catch (err) {
- const reason = (err.code === 'timeout' ? 'timeout: ' : '') + (err.message ?? 'unknown');
+ const reason =
+ (err.code === 'timeout' ? 'timeout: ' : '') + (err.message ?? 'unknown');
await _safePause(row.id, reason, ctx);
report.paused++;
report.errors.push({ id: row.id, reason });
@@ -256,7 +254,11 @@ export default wrap(async (req, res) => {
message: err.message,
txHash: result.txHash,
});
- report.errors.push({ id: row.id, reason: 'advance_failed', message: err.message });
+ report.errors.push({
+ id: row.id,
+ reason: 'advance_failed',
+ message: err.message,
+ });
continue;
}
diff --git a/api/dca-strategies.js b/api/dca-strategies.js
index 391f7fad5..2207ad04b 100644
--- a/api/dca-strategies.js
+++ b/api/dca-strategies.js
@@ -27,9 +27,12 @@ const createSchema = z.object({
token_out: ethAddress,
token_out_symbol: z.string().min(1).max(10),
amount_per_execution: weiString,
- period_seconds: z.number().int().refine((v) => v === 86400 || v === 604800, {
- message: 'period_seconds must be 86400 (daily) or 604800 (weekly)',
- }),
+ period_seconds: z
+ .number()
+ .int()
+ .refine((v) => v === 86400 || v === 604800, {
+ message: 'period_seconds must be 86400 (daily) or 604800 (weekly)',
+ }),
slippage_bps: z.number().int().min(1).max(MAX_SLIPPAGE_BPS).default(50),
});
@@ -135,7 +138,12 @@ export default wrap(async (req, res) => {
}
if (!ALLOWED_TOKEN_OUT_SYMBOLS.has(body.token_out_symbol)) {
- return error(res, 400, 'validation_error', `token_out_symbol must be one of: ${[...ALLOWED_TOKEN_OUT_SYMBOLS].join(', ')}`);
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ `token_out_symbol must be one of: ${[...ALLOWED_TOKEN_OUT_SYMBOLS].join(', ')}`,
+ );
}
// Confirm session user owns the agent
@@ -172,7 +180,12 @@ export default wrap(async (req, res) => {
LIMIT 1
`;
if (existing) {
- return error(res, 409, 'conflict', 'an active strategy already exists for this token pair — cancel it first');
+ return error(
+ res,
+ 409,
+ 'conflict',
+ 'an active strategy already exists for this token pair — cancel it first',
+ );
}
const nextExecAt = new Date(Date.now() + body.period_seconds * 1000).toISOString();
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 272f595bd..8f8f2d728 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -4,12 +4,14 @@
import { z } from 'zod';
import { Redis } from '@upstash/redis';
import { env } from '../_lib/env.js';
-import { cors, error, method, wrap, readJson } from '../_lib/http.js';
+import { cors, error, method, wrap, readJson, json } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { recordEvent } from '../_lib/usage.js';
+import { recordEvent, logger } from '../_lib/usage.js';
import { readEmbedPolicy } from '../_lib/embed-policy.js';
+const log = logger('llm.anthropic');
+
// ── Redis client (for monthly quota counters) ────────────────────────────────
let _redis = null;
@@ -35,6 +37,25 @@ const MODEL_ALLOWLIST = new Set([
// First-party hostnames always pass origin checks (same as element.js).
const FIRST_PARTY = ['3dagent.vercel.app', 'localhost'];
+// Default per-agent monthly token budget when policy.brain.cost_limit_cents is unset.
+const DEFAULT_MONTHLY_TOKEN_BUDGET = 1_000_000;
+// Rough cents-per-token conversion when a cost budget is provided. Conservative
+// blended estimate across input+output for the allowlisted models.
+const CENTS_PER_1K_TOKENS = 1.5;
+
+function tokenBudgetFromPolicy(policy) {
+ const cents = policy?.brain?.cost_limit_cents;
+ if (typeof cents === 'number' && cents > 0) {
+ return Math.floor((cents / CENTS_PER_1K_TOKENS) * 1000);
+ }
+ return DEFAULT_MONTHLY_TOKEN_BUDGET;
+}
+
+function monthKey() {
+ const now = new Date();
+ return `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`;
+}
+
function originAllowed(originHeader, policy) {
if (!originHeader) return true; // server-to-server / curl — allow
let host;
@@ -54,17 +75,62 @@ function originAllowed(originHeader, policy) {
return mode === 'allowlist' ? matches : !matches;
}
+// Build the strict CORS allowlist: first-party origins + any origin the agent's
+// embed policy declares. Returns an array of exact-match origin strings.
+function buildCorsAllowlist(policy) {
+ const out = new Set();
+ if (env.APP_ORIGIN) out.add(env.APP_ORIGIN);
+ try {
+ if (env.ISSUER) out.add(env.ISSUER);
+ } catch {
+ // ISSUER derives from APP_ORIGIN; ignore if unset.
+ }
+ // Localhost for dev parity with the same-origin check above.
+ const hosts = policy?.origins?.hosts ?? [];
+ for (const h of hosts) {
+ const lower = String(h).toLowerCase();
+ if (lower.startsWith('*.')) {
+ // Wildcard — convert to a regex matching https://<sub>.<base>.
+ const base = lower.slice(2).replace(/[.+?^${}()|[\]\\]/g, '\\$&');
+ out.add(new RegExp(`^https?://([a-z0-9-]+\\.)+${base}$`));
+ } else {
+ out.add(`https://${lower}`);
+ out.add(`http://${lower}`);
+ }
+ }
+ // Always allow localhost in dev for the proxy (matches isAllowedOrigin default).
+ out.add(/^https?:\/\/localhost(:\d+)?$/);
+ return Array.from(out);
+}
+
async function incrementMonthlyQuota(agentId) {
const r = getRedis();
if (!r) return 0; // no Redis → quota not enforced
- const now = new Date();
- const ym = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, '0')}`;
- const key = `llm:quota:${agentId}:${ym}`;
+ const key = `llm:quota:${agentId}:${monthKey()}`;
const count = await r.incr(key);
if (count === 1) await r.expire(key, 40 * 24 * 3600); // expire after 40 days
return count;
}
+// Peek at the current month's token total without incrementing. Returns 0 when
+// Redis is unavailable (quota not enforced).
+async function getMonthlyTokens(agentId) {
+ const r = getRedis();
+ if (!r) return 0;
+ const key = `llm:tokens:${agentId}:${monthKey()}`;
+ const v = await r.get(key);
+ return typeof v === 'number' ? v : parseInt(v || '0', 10) || 0;
+}
+
+async function addMonthlyTokens(agentId, delta) {
+ const r = getRedis();
+ if (!r || !delta) return 0;
+ const key = `llm:tokens:${agentId}:${monthKey()}`;
+ const total = await r.incrby(key, delta);
+ if (total === delta) await r.expire(key, 40 * 24 * 3600);
+ return total;
+}
+
// ── Request schema ────────────────────────────────────────────────────────────
const messageContentSchema = z.union([
@@ -93,16 +159,22 @@ const bodySchema = z.object({
// ── Handler ───────────────────────────────────────────────────────────────────
export default wrap(async (req, res) => {
- // Allow all HTTP origins for CORS — policy is enforced server-side below.
- if (cors(req, res, { origins: [/^https?:\/\/.+/], methods: 'POST,OPTIONS' })) return;
- if (!method(req, res, ['POST'])) return;
-
+ // Resolve the agent up front so CORS can use the agent's embed policy.
const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('agent');
- if (!agentId) return error(res, 400, 'validation_error', 'agent query param required');
- // 1. Read embed policy
- const policy = await readEmbedPolicy(agentId);
+ // Load policy first (when possible) so CORS allowlist can include the
+ // agent-declared origins. If no agent is supplied or not found, fall back
+ // to first-party only — the preflight will then be rejected for unknown
+ // third-party origins, which is the desired hardening.
+ let policy = null;
+ if (agentId) policy = await readEmbedPolicy(agentId);
+
+ const corsOrigins = buildCorsAllowlist(policy);
+ if (cors(req, res, { origins: corsOrigins, methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ if (!agentId) return error(res, 400, 'validation_error', 'agent query param required');
if (!policy) return error(res, 404, 'not_found', 'agent not found');
if (policy.brain?.mode !== 'we-pay') {
@@ -140,7 +212,7 @@ export default wrap(async (req, res) => {
if (!agentRl.success) return error(res, 429, 'rate_limited', 'agent rate limit exceeded');
}
- // 5. Monthly quota check
+ // 5a. Monthly call-count quota (existing)
const quota = policy.brain?.monthly_quota;
if (typeof quota === 'number' && quota !== null) {
const used = await incrementMonthlyQuota(agentId);
@@ -149,6 +221,15 @@ export default wrap(async (req, res) => {
}
}
+ // 5b. Monthly token budget (input+output). Check before forwarding; debit
+ // the actual usage after the upstream response so we never under-count but
+ // may serve one request that tips over — acceptable for a soft budget.
+ const tokenBudget = tokenBudgetFromPolicy(policy);
+ const tokensUsedSoFar = await getMonthlyTokens(agentId);
+ if (tokensUsedSoFar >= tokenBudget) {
+ return error(res, 429, 'quota_exceeded', `monthly token budget of ${tokenBudget} reached`);
+ }
+
// 6. Validate + normalize request body
const rawBody = await readJson(req);
const body = parse(bodySchema, rawBody);
@@ -171,7 +252,26 @@ export default wrap(async (req, res) => {
const upstreamText = await upstream.text();
const latencyMs = Date.now() - t0;
- // 8. Record usage (fire-and-forget)
+ // 8. Parse upstream JSON once — extract token usage and detect errors.
+ let upstreamJson = null;
+ try {
+ upstreamJson = JSON.parse(upstreamText);
+ } catch {
+ // Non-JSON body — treated as an opaque upstream failure below.
+ }
+ const inputTokens = upstreamJson?.usage?.input_tokens ?? 0;
+ const outputTokens = upstreamJson?.usage?.output_tokens ?? 0;
+
+ // Debit the per-agent token counter when we got a successful response.
+ if (upstream.ok && (inputTokens || outputTokens)) {
+ try {
+ await addMonthlyTokens(agentId, inputTokens + outputTokens);
+ } catch (err) {
+ log.warn('token_counter_write_failed', { agentId, msg: err?.message });
+ }
+ }
+
+ // 9. Record usage (fire-and-forget)
recordEvent({
kind: 'llm',
tool: 'anthropic.messages',
@@ -179,10 +279,26 @@ export default wrap(async (req, res) => {
bytes: upstreamText.length,
latencyMs,
status: upstream.ok ? 'ok' : 'error',
- meta: { model },
+ meta: {
+ model,
+ input_tokens: inputTokens,
+ output_tokens: outputTokens,
+ upstream_status: upstream.status,
+ },
});
- // 9. Proxy Anthropic's response faithfully
+ // 10a. Sanitize upstream errors — do not forward Anthropic's error JSON.
+ if (upstream.status >= 400) {
+ log.error('upstream_error', {
+ agentId,
+ model,
+ status: upstream.status,
+ body: upstreamText.slice(0, 2000),
+ });
+ return json(res, 502, { error: 'upstream_error', status: upstream.status });
+ }
+
+ // 10b. Proxy Anthropic's successful response faithfully (unchanged shape).
res.statusCode = upstream.status;
res.setHeader('content-type', upstream.headers.get('content-type') || 'application/json');
return res.end(upstreamText);
diff --git a/api/mcp.js b/api/mcp.js
index b43587647..e5c928182 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -688,12 +688,16 @@ async function handleTerminate(_req, res) {
}
// ── error helpers ────────────────────────────────────────────────────────────
+function quoteString(s) {
+ return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
+}
+
function send401(res, msg) {
const resource = env.MCP_RESOURCE;
res.statusCode = 401;
res.setHeader(
'www-authenticate',
- `Bearer resource_metadata="${env.APP_ORIGIN}/.well-known/oauth-protected-resource", resource="${resource}"`,
+ `Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,
);
res.setHeader('content-type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: 'unauthorized', error_description: msg }));
diff --git a/api/oauth/authorize.js b/api/oauth/authorize.js
index 8b420addd..19ca5b1d3 100644
--- a/api/oauth/authorize.js
+++ b/api/oauth/authorize.js
@@ -12,6 +12,33 @@ import { env } from '../_lib/env.js';
const CODE_TTL_SEC = 60;
+// OAuth 2.1 §3.1.2.2 — exact match on protocol/host/port/pathname.
+// Request URI must carry no extra query params or fragment.
+function redirectUriMatches(requested, registered) {
+ let reqUrl;
+ try {
+ reqUrl = new URL(requested);
+ } catch {
+ return false;
+ }
+ if (reqUrl.hash) return false;
+ if (reqUrl.search) return false;
+ return registered.some((entry) => {
+ let regUrl;
+ try {
+ regUrl = new URL(entry);
+ } catch {
+ return false;
+ }
+ return (
+ reqUrl.protocol === regUrl.protocol &&
+ reqUrl.host === regUrl.host &&
+ reqUrl.port === regUrl.port &&
+ reqUrl.pathname === regUrl.pathname
+ );
+ });
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -34,13 +61,15 @@ export default wrap(async (req, res) => {
if (!redirect_uri) return error(res, 400, 'invalid_request', 'redirect_uri required');
if (!code_challenge)
return error(res, 400, 'invalid_request', 'code_challenge required (PKCE)');
- if ((code_challenge_method ?? 'S256') !== 'S256')
+ if (!code_challenge_method)
+ return error(res, 400, 'invalid_request', 'code_challenge_method required (must be S256)');
+ if (code_challenge_method !== 'S256')
return error(res, 400, 'invalid_request', 'code_challenge_method must be S256');
const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;
const client = rows[0];
if (!client) return error(res, 400, 'invalid_client', 'unknown client');
- if (!client.redirect_uris.includes(redirect_uri)) {
+ if (!redirectUriMatches(redirect_uri, client.redirect_uris)) {
return error(res, 400, 'invalid_redirect_uri', 'redirect_uri not registered');
}
diff --git a/api/oauth/introspect.js b/api/oauth/introspect.js
index 438e2d949..585db2651 100644
--- a/api/oauth/introspect.js
+++ b/api/oauth/introspect.js
@@ -32,6 +32,9 @@ export default wrap(async (req, res) => {
// any registered client from probing arbitrary tokens for user identity
// or scope (especially relevant given open dynamic registration).
if (payload.client_id && payload.client_id !== client_id) {
+ // RFC 7662 §2.2: response for "not issued to this client" must be
+ // indistinguishable from "token not found" so clients can't probe
+ // token ownership. Both return identical {active: false} at 200.
return json(res, 200, { active: false });
}
return json(res, 200, {
diff --git a/api/oauth/token.js b/api/oauth/token.js
index 4c67a19ac..8718f267d 100644
--- a/api/oauth/token.js
+++ b/api/oauth/token.js
@@ -107,8 +107,20 @@ async function handleRefresh(res, client, form) {
oldSecret: refresh_token,
clientId: client.client_id,
// Narrow the rotated refresh token to the requested subset so a caller
- // can't re-widen back to the full grant on a later refresh.
- narrowScope: (stored) => (scope ? intersect(scope, stored) : stored),
+ // can't re-widen back to the full grant on a later refresh. When no
+ // scope is sent, preserve the stored scope. When scope is sent, it
+ // must be a strict subset of the stored scope — reject otherwise so
+ // the intersect fallback never silently upgrades to stored.
+ narrowScope: (stored) => {
+ if (!scope) return stored;
+ if (!isSubsetScope(scope, stored)) {
+ throw Object.assign(new Error('requested scope exceeds granted scope'), {
+ status: 400,
+ code: 'invalid_scope',
+ });
+ }
+ return scope.split(/\s+/).filter(Boolean).join(' ');
+ },
});
} catch (err) {
return error(res, err.status || 400, err.code || 'invalid_grant', err.message);
@@ -130,14 +142,11 @@ async function handleRefresh(res, client, form) {
});
}
-function intersect(a, b) {
- const set = new Set(b.split(/\s+/).filter(Boolean));
- return (
- a
- .split(/\s+/)
- .filter((s) => set.has(s))
- .join(' ') || b
- );
+function isSubsetScope(requested, stored) {
+ const allowed = new Set(stored.split(/\s+/).filter(Boolean));
+ const asked = requested.split(/\s+/).filter(Boolean);
+ if (asked.length === 0) return false;
+ return asked.every((s) => allowed.has(s));
}
function basicAuthUser(req) {
diff --git a/api/permissions/grant.js b/api/permissions/grant.js
index 93c1915a5..db066878e 100644
--- a/api/permissions/grant.js
+++ b/api/permissions/grant.js
@@ -16,8 +16,7 @@ import {
} from '../../src/erc7710/abi.js';
import { isDelegationValid, PermissionError } from '../../src/permissions/toolkit.js';
-const ROOT_AUTHORITY =
- '0x0000000000000000000000000000000000000000000000000000000000000000';
+const ROOT_AUTHORITY = '0x0000000000000000000000000000000000000000000000000000000000000000';
const hexAddr = z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address');
const hexBytes = z.string().regex(/^0x([0-9a-fA-F]{2})*$/, 'must be 0x-prefixed hex bytes');
@@ -35,7 +34,9 @@ const delegationSchema = z.object({
authority: hexBytes32.optional(),
caveats: z.array(caveatSchema).default([]),
salt: z.union([
- z.string().regex(/^(0x[0-9a-fA-F]+|\d+)$/, 'salt must be a decimal or 0x-prefixed hex integer'),
+ z
+ .string()
+ .regex(/^(0x[0-9a-fA-F]+|\d+)$/, 'salt must be a decimal or 0x-prefixed hex integer'),
z.number().int().nonnegative(),
]),
signature: hexBytes,
@@ -99,7 +100,12 @@ export default wrap(async (req, res) => {
limit 1
`;
if (!linkedWallet) {
- return error(res, 409, 'wallet_not_linked', 'delegation.delegator is not linked to your account');
+ return error(
+ res,
+ 409,
+ 'wallet_not_linked',
+ 'delegation.delegator is not linked to your account',
+ );
}
// Signature verification — two steps:
@@ -125,7 +131,12 @@ export default wrap(async (req, res) => {
derivedHash = ethers.TypedDataEncoder.hash(eip712Domain, DELEGATION_TYPES, structValue);
if (derivedHash.toLowerCase() !== delegation.hash.toLowerCase()) {
- return error(res, 400, 'hash_mismatch', 'delegation.hash does not match the delegation fields');
+ return error(
+ res,
+ 400,
+ 'hash_mismatch',
+ 'delegation.hash does not match the delegation fields',
+ );
}
const recovered = ethers.verifyTypedData(
@@ -135,7 +146,12 @@ export default wrap(async (req, res) => {
delegation.signature,
);
if (recovered.toLowerCase() !== delegatorLower) {
- return error(res, 400, 'signature_invalid', 'signature does not match delegation.delegator');
+ return error(
+ res,
+ 400,
+ 'signature_invalid',
+ 'signature does not match delegation.delegator',
+ );
}
} catch (err) {
if (err instanceof PermissionError) {
@@ -154,13 +170,23 @@ export default wrap(async (req, res) => {
},
);
if (!validity.valid) {
- return error(res, 400, validity.reason || 'signature_invalid', 'delegation is not valid on-chain');
+ return error(
+ res,
+ 400,
+ validity.reason || 'signature_invalid',
+ 'delegation is not valid on-chain',
+ );
}
// Scope sanity checks
const nowSec = Math.floor(Date.now() / 1000);
if (scope.expiry <= nowSec + 60) {
- return error(res, 400, 'validation_error', 'scope.expiry must be at least 60 seconds in the future');
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ 'scope.expiry must be at least 60 seconds in the future',
+ );
}
if (scope.expiry > nowSec + 365 * 24 * 3600) {
return error(res, 400, 'validation_error', 'scope.expiry must be within 365 days');
diff --git a/api/permissions/list.js b/api/permissions/list.js
index 76eba9570..90b524fe1 100644
--- a/api/permissions/list.js
+++ b/api/permissions/list.js
@@ -28,7 +28,12 @@ export default wrap(async (req, res) => {
const statusParam = url.searchParams.get('status') || 'active';
if (!VALID_STATUSES.has(statusParam)) {
- return error(res, 400, 'validation_error', 'status must be active, revoked, expired, or all');
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ 'status must be active, revoked, expired, or all',
+ );
}
const chainIdParam = url.searchParams.get('chainId');
@@ -37,7 +42,10 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'chainId must be a positive integer');
}
- const limitParam = Math.min(200, Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10)));
+ const limitParam = Math.min(
+ 200,
+ Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10)),
+ );
const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10));
// agentId-only path: public, no auth required
@@ -79,7 +87,12 @@ export default wrap(async (req, res) => {
LIMIT 1
`;
if (!wallet) {
- return error(res, 403, 'forbidden', 'delegator address does not belong to your account');
+ return error(
+ res,
+ 403,
+ 'forbidden',
+ 'delegator address does not belong to your account',
+ );
}
}
diff --git a/api/permissions/metadata.js b/api/permissions/metadata.js
index 78ad4adc8..75e259b70 100644
--- a/api/permissions/metadata.js
+++ b/api/permissions/metadata.js
@@ -80,7 +80,7 @@ export default wrap(async (req, res) => {
}));
// delegationManager: use the filtered chain if provided, otherwise first delegation's chain
- const resolveChain = chainId ?? (rows[0]?.chain_id ?? null);
+ const resolveChain = chainId ?? rows[0]?.chain_id ?? null;
const delegationManager = resolveChain
? (DELEGATION_MANAGER_DEPLOYMENTS[resolveChain] ?? null)
: null;
diff --git a/api/permissions/redeem.js b/api/permissions/redeem.js
index 728cd6fcd..86ca737e8 100644
--- a/api/permissions/redeem.js
+++ b/api/permissions/redeem.js
@@ -127,7 +127,12 @@ export default wrap(async (req, res) => {
const bearer = await authenticateBearer(token);
if (!bearer) return error(res, 401, 'unauthorized', 'valid bearer token required');
if (!hasScope(bearer.scope, 'permissions:redeem')) {
- return error(res, 403, 'insufficient_scope', "token must include 'permissions:redeem' scope");
+ return error(
+ res,
+ 403,
+ 'insufficient_scope',
+ "token must include 'permissions:redeem' scope",
+ );
}
// Idempotency-Key check (before parsing body — key is in header)
@@ -184,7 +189,12 @@ export default wrap(async (req, res) => {
const allowedTargets = new Set((scope.targets || []).map((t) => t.toLowerCase()));
for (const call of calls) {
if (!allowedTargets.has(call.to.toLowerCase())) {
- return error(res, 403, 'target_not_allowed', `call target ${call.to} is not in scope.targets`);
+ return error(
+ res,
+ 403,
+ 'target_not_allowed',
+ `call target ${call.to} is not in scope.targets`,
+ );
}
}
@@ -222,11 +232,17 @@ export default wrap(async (req, res) => {
const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
if (requestAmount + historicalSpend > maxAmount) {
- return error(res, 403, 'scope_exceeded', 'ETH spend would exceed scope.maxAmount for this period', {
- maxAmount: scope.maxAmount,
- periodSpent: historicalSpend.toString(),
- requested: requestAmount.toString(),
- });
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ 'ETH spend would exceed scope.maxAmount for this period',
+ {
+ maxAmount: scope.maxAmount,
+ periodSpent: historicalSpend.toString(),
+ requested: requestAmount.toString(),
+ },
+ );
}
} else {
// ERC-20: decode transfer amounts from call data
@@ -254,18 +270,29 @@ export default wrap(async (req, res) => {
const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
if (requestAmount + historicalSpend > maxAmount) {
- return error(res, 403, 'scope_exceeded', 'token spend would exceed scope.maxAmount for this period', {
- maxAmount: scope.maxAmount,
- periodSpent: historicalSpend.toString(),
- requested: requestAmount.toString(),
- });
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ 'token spend would exceed scope.maxAmount for this period',
+ {
+ maxAmount: scope.maxAmount,
+ periodSpent: historicalSpend.toString(),
+ requested: requestAmount.toString(),
+ },
+ );
}
}
// ── Build signer ───────────────────────────────────────────────────────
const rpcUrl = getRpcUrl(chainId);
if (!rpcUrl) {
- return error(res, 502, 'rpc_error', `no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`);
+ return error(
+ res,
+ 502,
+ 'rpc_error',
+ `no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`,
+ );
}
let signer;
@@ -309,10 +336,12 @@ export default wrap(async (req, res) => {
// Compute amount redeemed for usage tracking
const redeemAmount = isNative
? calls.reduce((s, c) => s + BigInt(c.value), 0n).toString()
- : calls.reduce((s, c) => {
- const a = decodeErc20AmountFixed(c.data);
- return s + (a ?? 0n);
- }, 0n).toString();
+ : calls
+ .reduce((s, c) => {
+ const a = decodeErc20AmountFixed(c.data);
+ return s + (a ?? 0n);
+ }, 0n)
+ .toString();
recordEvent({
userId: bearer.userId,
diff --git a/api/permissions/revoke.js b/api/permissions/revoke.js
index 8442f3d96..9d9bb1681 100644
--- a/api/permissions/revoke.js
+++ b/api/permissions/revoke.js
@@ -7,10 +7,7 @@ import { cors, method, readJson, wrap, error, json } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { recordEvent } from '../_lib/usage.js';
import { SERVER_CHAIN_META } from '../_lib/onchain.js';
-import {
- DELEGATION_MANAGER_ABI,
- DELEGATION_MANAGER_DEPLOYMENTS,
-} from '../../src/erc7710/abi.js';
+import { DELEGATION_MANAGER_ABI, DELEGATION_MANAGER_DEPLOYMENTS } from '../../src/erc7710/abi.js';
import { z } from 'zod';
import { JsonRpcProvider, Contract, Interface } from 'ethers';
@@ -28,8 +25,14 @@ function withTimeout(promise, ms) {
return new Promise((resolve, reject) => {
const t = setTimeout(() => reject(new Error(`rpc timeout after ${ms}ms`)), ms);
Promise.resolve(promise).then(
- (v) => { clearTimeout(t); resolve(v); },
- (e) => { clearTimeout(t); reject(e); },
+ (v) => {
+ clearTimeout(t);
+ resolve(v);
+ },
+ (e) => {
+ clearTimeout(t);
+ reject(e);
+ },
);
});
}
@@ -86,7 +89,12 @@ export default wrap(async (req, res) => {
}
const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[row.chain_id];
if (!managerAddr) {
- return error(res, 400, 'chain_not_supported', `no DelegationManager for chainId ${row.chain_id}`);
+ return error(
+ res,
+ 400,
+ 'chain_not_supported',
+ `no DelegationManager for chainId ${row.chain_id}`,
+ );
}
const provider = new JsonRpcProvider(chainMeta.rpc, row.chain_id, { staticNetwork: true });
@@ -95,7 +103,9 @@ export default wrap(async (req, res) => {
let receipt = null;
for (let attempt = 0; attempt < 3 && !receipt; attempt++) {
if (attempt > 0) await new Promise((r) => setTimeout(r, 800));
- receipt = await withTimeout(provider.getTransactionReceipt(txHash), RPC_TIMEOUT_MS).catch(() => null);
+ receipt = await withTimeout(provider.getTransactionReceipt(txHash), RPC_TIMEOUT_MS).catch(
+ () => null,
+ );
}
if (!receipt) return error(res, 400, 'tx_not_found', 'transaction receipt not found');
@@ -117,9 +127,17 @@ export default wrap(async (req, res) => {
// Second confirmation: call disabledDelegations(hash) on-chain
const manager = new Contract(managerAddr, DELEGATION_MANAGER_ABI, provider);
- const isDisabled = await withTimeout(manager.disabledDelegations(row.delegation_hash), RPC_TIMEOUT_MS).catch(() => null);
+ const isDisabled = await withTimeout(
+ manager.disabledDelegations(row.delegation_hash),
+ RPC_TIMEOUT_MS,
+ ).catch(() => null);
if (!isDisabled) {
- return error(res, 400, 'not_yet_disabled', 'delegation is not yet marked disabled on-chain');
+ return error(
+ res,
+ 400,
+ 'not_yet_disabled',
+ 'delegation is not yet marked disabled on-chain',
+ );
}
// Flip status active → revoked; 0 rows = already revoked / never active
@@ -132,7 +150,12 @@ export default wrap(async (req, res) => {
if (!updated || updated.length === 0) {
const [current] = await sql`SELECT status FROM agent_delegations WHERE id = ${id} LIMIT 1`;
const currentStatus = current?.status ?? 'unknown';
- return error(res, 409, 'already_revoked', `delegation cannot be revoked (current status: ${currentStatus})`);
+ return error(
+ res,
+ 409,
+ 'already_revoked',
+ `delegation cannot be revoked (current status: ${currentStatus})`,
+ );
}
const revokedAt = updated[0].revoked_at;
diff --git a/api/permissions/verify.js b/api/permissions/verify.js
index 2943710c5..5770b3538 100644
--- a/api/permissions/verify.js
+++ b/api/permissions/verify.js
@@ -3,10 +3,7 @@ import { Contract, JsonRpcProvider } from 'ethers';
import { sql } from '../_lib/db.js';
import { error, wrap } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import {
- DELEGATION_MANAGER_DEPLOYMENTS,
- DELEGATION_MANAGER_ABI,
-} from '../../src/erc7710/abi.js';
+import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../../src/erc7710/abi.js';
const HASH_RE = /^0x[0-9a-fA-F]{64}$/;
const CACHE_VALID = 'public, max-age=30, s-maxage=60';
@@ -56,11 +53,19 @@ export default wrap(async (req, res) => {
`;
if (row?.status === 'revoked') {
- return respond(res, { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash }, CACHE_INVALID);
+ return respond(
+ res,
+ { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash },
+ CACHE_INVALID,
+ );
}
if (row?.status === 'expired' || (row?.expires_at && new Date(row.expires_at) <= new Date())) {
- return respond(res, { ok: true, valid: false, reason: 'delegation_expired', checkedAt, chainId, hash }, CACHE_INVALID);
+ return respond(
+ res,
+ { ok: true, valid: false, reason: 'delegation_expired', checkedAt, chainId, hash },
+ CACHE_INVALID,
+ );
}
// On-chain check — 5 s timeout
@@ -88,7 +93,11 @@ export default wrap(async (req, res) => {
`.catch((e) => console.error('[verify] self-heal failed', e));
});
}
- return respond(res, { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash }, CACHE_INVALID);
+ return respond(
+ res,
+ { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash },
+ CACHE_INVALID,
+ );
}
const body = { ok: true, valid: true, checkedAt, chainId, hash };
diff --git a/api/subscriptions.js b/api/subscriptions.js
index 6f1efdecf..0bf4f139b 100644
--- a/api/subscriptions.js
+++ b/api/subscriptions.js
@@ -17,7 +17,9 @@ const postSchema = z.object({
agentId: z.string().uuid(),
delegationId: z.string().uuid(),
periodSeconds: z.number().int().positive(),
- amountPerPeriod: z.string().regex(/^\d+$/, 'amountPerPeriod must be a base-unit integer string'),
+ amountPerPeriod: z
+ .string()
+ .regex(/^\d+$/, 'amountPerPeriod must be a base-unit integer string'),
});
export default wrap(async (req, res) => {
@@ -55,7 +57,8 @@ export default wrap(async (req, res) => {
SELECT id FROM agent_delegations
WHERE id = ${delegationId} AND agent_id = ${agentId} AND status = 'active'
`;
- if (!delegation) return error(res, 400, 'validation_error', 'delegation not found or not active');
+ if (!delegation)
+ return error(res, 400, 'validation_error', 'delegation not found or not active');
// Idempotency: return existing active subscription rather than duplicating.
const [existing] = await sql`
diff --git a/create.html b/create.html
index 4eed67703..5d5ff8e6f 100644
--- a/create.html
+++ b/create.html
@@ -410,14 +410,14 @@
}
}
</style>
- <script>
- fetch('/api/auth/me', { credentials: 'include' }).then(function(r) {
- if (!r.ok) {
- sessionStorage.setItem('login_redirect', '/create');
- location.replace('/login');
- }
- });
- </script>
+ <script>
+ fetch('/api/auth/me', { credentials: 'include' }).then(function (r) {
+ if (!r.ok) {
+ sessionStorage.setItem('login_redirect', '/create');
+ location.replace('/login');
+ }
+ });
+ </script>
</head>
<body>
<header class="topbar">
@@ -545,7 +545,14 @@
</div>
<!-- Card 3: From selfie (disabled) -->
- <div class="create-card" id="card-selfie" role="button" aria-disabled="true" aria-label="From a selfie (coming soon)" tabindex="-1">
+ <div
+ class="create-card"
+ id="card-selfie"
+ role="button"
+ aria-disabled="true"
+ aria-label="From a selfie (coming soon)"
+ tabindex="-1"
+ >
<span class="coming-soon-badge" aria-hidden="true">Coming Soon</span>
<div
class="card-icon"
@@ -591,10 +598,38 @@
</div>
</main>
- <label for="glb-input" class="visually-hidden" style="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0">Upload GLB file</label>
- <input type="file" id="glb-input" accept=".glb,model/gltf-binary" style="display: none" aria-describedby="glb-input-desc" />
+ <label
+ for="glb-input"
+ class="visually-hidden"
+ style="
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+ "
+ >Upload GLB file</label
+ >
+ <input
+ type="file"
+ id="glb-input"
+ accept=".glb,model/gltf-binary"
+ style="display: none"
+ aria-describedby="glb-input-desc"
+ />
<span id="glb-input-desc" hidden>Select a .glb or glTF 2.0 binary model file</span>
- <div class="status-toast" id="status-toast" role="status" aria-live="polite" aria-atomic="true" hidden></div>
+ <div
+ class="status-toast"
+ id="status-toast"
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ hidden
+ ></div>
<script type="module" src="/src/create.js"></script>
</body>
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 0f2329b73..2b3c0807a 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -23,7 +23,7 @@ Everything you need to know to work on 3D Agent locally.
```bash
git clone https://github.com/nirholas/3d-agent.git
-cd 3D
+cd 3D-Agent
npm install
```
diff --git a/docs/api-inventory.md b/docs/api-inventory.md
index 180e8bfa6..186289b23 100644
--- a/docs/api-inventory.md
+++ b/docs/api-inventory.md
@@ -4,196 +4,196 @@ Generated reference of every HTTP endpoint under `/api/`. Paths reflect the exte
## Agents
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/agents` | GET, POST | session or bearer | List caller's agents / create new agent identity | GET: `?limit&cursor`; POST: `{name,description,avatarId,...,animations[]}` | `{agents}` / `{agent}` |
-| `/api/agents/me` | GET | session or bearer | Get or auto-create caller's default agent | — | `{agent}` |
-| `/api/agents/:id` | GET, PUT, PATCH, DELETE | public GET; session PUT/DELETE | Fetch (public fields if not owner), update, soft-delete | PATCH body: partial agent | `{agent}` |
-| `/api/agents/:id/wallet` | POST, DELETE | session | Link/update or unlink agent wallet | `{address,signature?}` | `{wallet}` |
-| `/api/agents/:id/actions` | GET | session or bearer (owner or public agent) | Paginated signed action log (EIP-191 verified) | `?limit&cursor` | `{actions[]}` |
-| `/api/agents/:id/sign` | POST | session or bearer (owner) | Sign arbitrary EIP-191 message with agent's server wallet | `{message,kind?}` | `{address,signature}` |
-| `/api/agents/:id/embed-policy` | GET, PUT, DELETE | public GET; session owner PUT/DELETE | Read/write/clear embed policy (origins, surfaces, brain) | PUT: policy object | `{policy}` |
-| `/api/agents/:id/usage` | GET | session (owner) | LLM proxy usage stats (monthly + 30-day daily) | — | `{month,quota,daily[]}` |
-| `/api/agents/by-address/:addr` | GET | public (rate-limited) | DB-first agent lookup by owner address; RPC fallback via ERC-721 enumerable | `?chainId` | `{agents[]}` |
-| `/api/agents/by-wallet` | GET | public (rate-limited) | DB lookup by agent wallet address | `?address&chain_id` | `{agents[]}` |
-| `/api/agents/check-name` | GET | session or bearer | Validate agent name availability (denylist + regex) | `?name&agent_id?` | `{available,reason?}` |
-| `/api/agents/ens/:name` | GET | public (rate-limited) | Resolve ENS name then look up agents owned by that address | — | `{address,agents[]}` |
-| `/api/agents/suggest` | GET | public (rate-limited) | @-mention autocomplete ranked search | `?q&limit` | `{agents[]}` |
-| `/api/agents/register-prep` | POST | session | Build canonical registration JSON + pin IPFS, return CID for signing | `{name,description,avatarId,brain?}` | `{cid,metadataURI,prepId}` |
-| `/api/agents/register-confirm` | POST | session | Verify on-chain registration tx, upsert agent_identities row | `{prepId,chainId,agentId,txHash}` | `{agentId}` |
-| `/api/agent-actions` | GET, POST | session or bearer | Append-only global action log (provenance trail) | GET: `?agent_id&limit&cursor`; POST: action body | `{actions[]}` / `{action}` |
-| `/api/agent-memory` | GET, POST | session or bearer | Backup for LLM agent memories | GET: `?agentId&type&since&limit`; POST: memory upsert | `{memories[]}` |
-| `/api/agent-memory/:id` | DELETE | session or bearer | Forget a memory entry | — | `{ok}` |
-| `/api/agent/:id/og` | GET | public | Open Graph image: 302 to avatar thumbnail or SVG card | — | image/svg+xml or 302 |
-| `/api/oembed` | GET | public | oEmbed rich payload for agent URLs (Notion/Discord/etc.) | `?url&format` | oEmbed JSON |
-| `/api/a/:chain/:id/og` | GET | public | On-chain agent OG image (302 to manifest image or SVG) | `?format=json?` | image/svg+xml or JSON |
-| `/a/:chain/:id` | GET | public | Server-rendered HTML with OG/Twitter/oEmbed/Frame tags | — | text/html |
+| Path | Methods | Auth | Description | Input | Response |
+| ------------------------------ | ----------------------- | ----------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------- |
+| `/api/agents` | GET, POST | session or bearer | List caller's agents / create new agent identity | GET: `?limit&cursor`; POST: `{name,description,avatarId,...,animations[]}` | `{agents}` / `{agent}` |
+| `/api/agents/me` | GET | session or bearer | Get or auto-create caller's default agent | — | `{agent}` |
+| `/api/agents/:id` | GET, PUT, PATCH, DELETE | public GET; session PUT/DELETE | Fetch (public fields if not owner), update, soft-delete | PATCH body: partial agent | `{agent}` |
+| `/api/agents/:id/wallet` | POST, DELETE | session | Link/update or unlink agent wallet | `{address,signature?}` | `{wallet}` |
+| `/api/agents/:id/actions` | GET | session or bearer (owner or public agent) | Paginated signed action log (EIP-191 verified) | `?limit&cursor` | `{actions[]}` |
+| `/api/agents/:id/sign` | POST | session or bearer (owner) | Sign arbitrary EIP-191 message with agent's server wallet | `{message,kind?}` | `{address,signature}` |
+| `/api/agents/:id/embed-policy` | GET, PUT, DELETE | public GET; session owner PUT/DELETE | Read/write/clear embed policy (origins, surfaces, brain) | PUT: policy object | `{policy}` |
+| `/api/agents/:id/usage` | GET | session (owner) | LLM proxy usage stats (monthly + 30-day daily) | — | `{month,quota,daily[]}` |
+| `/api/agents/by-address/:addr` | GET | public (rate-limited) | DB-first agent lookup by owner address; RPC fallback via ERC-721 enumerable | `?chainId` | `{agents[]}` |
+| `/api/agents/by-wallet` | GET | public (rate-limited) | DB lookup by agent wallet address | `?address&chain_id` | `{agents[]}` |
+| `/api/agents/check-name` | GET | session or bearer | Validate agent name availability (denylist + regex) | `?name&agent_id?` | `{available,reason?}` |
+| `/api/agents/ens/:name` | GET | public (rate-limited) | Resolve ENS name then look up agents owned by that address | — | `{address,agents[]}` |
+| `/api/agents/suggest` | GET | public (rate-limited) | @-mention autocomplete ranked search | `?q&limit` | `{agents[]}` |
+| `/api/agents/register-prep` | POST | session | Build canonical registration JSON + pin IPFS, return CID for signing | `{name,description,avatarId,brain?}` | `{cid,metadataURI,prepId}` |
+| `/api/agents/register-confirm` | POST | session | Verify on-chain registration tx, upsert agent_identities row | `{prepId,chainId,agentId,txHash}` | `{agentId}` |
+| `/api/agent-actions` | GET, POST | session or bearer | Append-only global action log (provenance trail) | GET: `?agent_id&limit&cursor`; POST: action body | `{actions[]}` / `{action}` |
+| `/api/agent-memory` | GET, POST | session or bearer | Backup for LLM agent memories | GET: `?agentId&type&since&limit`; POST: memory upsert | `{memories[]}` |
+| `/api/agent-memory/:id` | DELETE | session or bearer | Forget a memory entry | — | `{ok}` |
+| `/api/agent/:id/og` | GET | public | Open Graph image: 302 to avatar thumbnail or SVG card | — | image/svg+xml or 302 |
+| `/api/oembed` | GET | public | oEmbed rich payload for agent URLs (Notion/Discord/etc.) | `?url&format` | oEmbed JSON |
+| `/api/a/:chain/:id/og` | GET | public | On-chain agent OG image (302 to manifest image or SVG) | `?format=json?` | image/svg+xml or JSON |
+| `/a/:chain/:id` | GET | public | Server-rendered HTML with OG/Twitter/oEmbed/Frame tags | — | text/html |
## Avatars
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/avatars` | GET, POST | bearer `avatars:read`/`:write` or session | List caller avatars / register metadata after R2 upload | GET: `?limit&cursor&visibility&include_public`; POST: `{storage_key,size_bytes,...}` | `{avatars[]}` / `{avatar}` |
-| `/api/avatars/public` | GET | public | Public gallery search | `?q&tag&limit&cursor` | `{avatars[]}` |
-| `/api/avatars/presign` | POST | bearer `avatars:write` or session | Short-lived R2 presigned PUT URL for direct upload | `{size_bytes,content_type,slug?}` | `{storage_key,upload_url,...}` |
-| `/api/avatars/:id` | GET, PATCH, DELETE | public if visible; session/bearer owner for write | Fetch/update metadata/soft-delete; PATCH with `glbUrl` saves version | PATCH: `{name?,description?,visibility?,tags?,glbUrl?}` | `{avatar}` |
-| `/api/avatars/:id/versions` | GET | optional auth | Ancestor+descendant chain via `parent_avatar_id` | — | `{versions[]}` |
-| `/api/avatars/:id/glb-versions` | GET | session or bearer (owner) | Explicit GLB save-back snapshots | — | `{versions[]}` |
-| `/api/avatars/:id/rollback` | POST | session or bearer (owner) | Restore `storage_key` from a saved version (10/h) | `{versionId}` | `{avatar}` |
-| `/api/avatars/:id/session` | POST | session or bearer (owner) | Avaturn edit session for existing avatar | — | `{session_url,expires_at?}` |
-| `/api/avatars/:id/storage-mode` | GET, PUT | owner (PUT) / session for private GET | Read/write `storage_mode` JSONB (ipfs/attestation) | PUT: storage-mode schema | `{storage_mode}` |
-| `/api/avatars/:id/pin-ipfs` | POST | session (owner) | STUB pin to IPFS; flips pinned flag | — | `{storage_mode,stub:true}` |
-| `/api/avatars/regenerate` | POST | session or bearer `avatars:write` | Enqueue remesh/retex/rerig/restyle job (501 until provider set) | `{sourceAvatarId,mode,params?}` | `{jobId}` |
-| `/api/avatars/regenerate-status` | GET | session or bearer `avatars:read` | Poll regen job | `?jobId` | `{status,resultAvatarId?,error?}` |
-| `/api/animations/presign` | POST | session or bearer `avatars:write` | Presigned PUT for animation .glb clips (100 MB cap) | `{size_bytes,content_type,slug?,checksum_sha256?}` | `{storage_key,upload_url,...}` |
+| Path | Methods | Auth | Description | Input | Response |
+| -------------------------------- | ------------------ | ------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------- |
+| `/api/avatars` | GET, POST | bearer `avatars:read`/`:write` or session | List caller avatars / register metadata after R2 upload | GET: `?limit&cursor&visibility&include_public`; POST: `{storage_key,size_bytes,...}` | `{avatars[]}` / `{avatar}` |
+| `/api/avatars/public` | GET | public | Public gallery search | `?q&tag&limit&cursor` | `{avatars[]}` |
+| `/api/avatars/presign` | POST | bearer `avatars:write` or session | Short-lived R2 presigned PUT URL for direct upload | `{size_bytes,content_type,slug?}` | `{storage_key,upload_url,...}` |
+| `/api/avatars/:id` | GET, PATCH, DELETE | public if visible; session/bearer owner for write | Fetch/update metadata/soft-delete; PATCH with `glbUrl` saves version | PATCH: `{name?,description?,visibility?,tags?,glbUrl?}` | `{avatar}` |
+| `/api/avatars/:id/versions` | GET | optional auth | Ancestor+descendant chain via `parent_avatar_id` | — | `{versions[]}` |
+| `/api/avatars/:id/glb-versions` | GET | session or bearer (owner) | Explicit GLB save-back snapshots | — | `{versions[]}` |
+| `/api/avatars/:id/rollback` | POST | session or bearer (owner) | Restore `storage_key` from a saved version (10/h) | `{versionId}` | `{avatar}` |
+| `/api/avatars/:id/session` | POST | session or bearer (owner) | Avaturn edit session for existing avatar | — | `{session_url,expires_at?}` |
+| `/api/avatars/:id/storage-mode` | GET, PUT | owner (PUT) / session for private GET | Read/write `storage_mode` JSONB (ipfs/attestation) | PUT: storage-mode schema | `{storage_mode}` |
+| `/api/avatars/:id/pin-ipfs` | POST | session (owner) | STUB pin to IPFS; flips pinned flag | — | `{storage_mode,stub:true}` |
+| `/api/avatars/regenerate` | POST | session or bearer `avatars:write` | Enqueue remesh/retex/rerig/restyle job (501 until provider set) | `{sourceAvatarId,mode,params?}` | `{jobId}` |
+| `/api/avatars/regenerate-status` | GET | session or bearer `avatars:read` | Poll regen job | `?jobId` | `{status,resultAvatarId?,error?}` |
+| `/api/animations/presign` | POST | session or bearer `avatars:write` | Presigned PUT for animation .glb clips (100 MB cap) | `{size_bytes,content_type,slug?,checksum_sha256?}` | `{storage_key,upload_url,...}` |
## Auth
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/auth/register` | POST | public (rate-limited) | Email or username signup; creates session | `{email|username,password,display_name?}` | `{user}` + Set-Cookie |
-| `/api/auth/login` | POST | public (rate-limited) | Verify password, mint session | `{email,password}` | `{user}` + Set-Cookie |
-| `/api/auth/logout` | POST | session | Destroy current session | — | `{ok}` |
-| `/api/auth/logout-everywhere` | POST | session | Revoke all sessions for caller | — | `{revoked}` |
-| `/api/auth/me` | GET | session | Who am I | — | `{user}` |
-| `/api/auth/sessions` | GET, DELETE | session | List active sessions / revoke all except current | — | `{sessions[]}` |
-| `/api/auth/sessions/:id` | DELETE | session | Revoke one session (not current) | — | `{revoked}` |
-| `/api/auth/session/list` | GET | session | List sessions with ipHash + current flag | — | `{sessions[]}` |
-| `/api/auth/session/refresh` | POST | session | Rotate session cookie | — | `{user}` + Set-Cookie |
-| `/api/auth/session/revoke` | POST | session | Revoke by `{sessionId}` or `{all:true}` | `{sessionId?,all?}` | `{ok,revoked}` |
-| `/api/auth/siwe/nonce` | GET | public (rate-limited) | EIP-4361 nonce + CSRF cookie | — | `{nonce}` |
-| `/api/auth/siwe/verify` | POST | CSRF + signature | Verify SIWE; create/link user + session | `{message,signature}` | `{user}` + Set-Cookie |
-| `/api/auth/privy/verify` | POST | public (rate-limited) | Exchange Privy idToken for session | `{idToken}` | `{user,wallet}` + Set-Cookie |
-| `/api/auth/wallet/link` | POST | session | Link wallet via SIWE to logged-in account | `{message,signature}` | `{wallet}` |
-| `/api/auth/wallet/unlink` | POST | session | Unlink one wallet | `{address}` | `{ok}` |
-| `/api/auth/wallets` | GET, POST | session | List linked wallets / link new (nonce-based) | POST: `{address,message,signature,nonce}` | `{wallets[]}` / `{wallet}` |
-| `/api/auth/wallets/:address` | DELETE | session | Unlink by address (blocks last wallet if no password) | — | `{ok}` |
-| `/api/auth/wallets/nonce` | POST | session | Issue SIWE-like nonce for wallet link | — | `{nonce,message}` |
+| Path | Methods | Auth | Description | Input | Response |
+| ----------------------------- | ----------- | --------------------- | ----------------------------------------------------- | ----------------------------------------- | --------------------------------- | --------------------- |
+| `/api/auth/register` | POST | public (rate-limited) | Email or username signup; creates session | `{email | username,password,display_name?}` | `{user}` + Set-Cookie |
+| `/api/auth/login` | POST | public (rate-limited) | Verify password, mint session | `{email,password}` | `{user}` + Set-Cookie |
+| `/api/auth/logout` | POST | session | Destroy current session | — | `{ok}` |
+| `/api/auth/logout-everywhere` | POST | session | Revoke all sessions for caller | — | `{revoked}` |
+| `/api/auth/me` | GET | session | Who am I | — | `{user}` |
+| `/api/auth/sessions` | GET, DELETE | session | List active sessions / revoke all except current | — | `{sessions[]}` |
+| `/api/auth/sessions/:id` | DELETE | session | Revoke one session (not current) | — | `{revoked}` |
+| `/api/auth/session/list` | GET | session | List sessions with ipHash + current flag | — | `{sessions[]}` |
+| `/api/auth/session/refresh` | POST | session | Rotate session cookie | — | `{user}` + Set-Cookie |
+| `/api/auth/session/revoke` | POST | session | Revoke by `{sessionId}` or `{all:true}` | `{sessionId?,all?}` | `{ok,revoked}` |
+| `/api/auth/siwe/nonce` | GET | public (rate-limited) | EIP-4361 nonce + CSRF cookie | — | `{nonce}` |
+| `/api/auth/siwe/verify` | POST | CSRF + signature | Verify SIWE; create/link user + session | `{message,signature}` | `{user}` + Set-Cookie |
+| `/api/auth/privy/verify` | POST | public (rate-limited) | Exchange Privy idToken for session | `{idToken}` | `{user,wallet}` + Set-Cookie |
+| `/api/auth/wallet/link` | POST | session | Link wallet via SIWE to logged-in account | `{message,signature}` | `{wallet}` |
+| `/api/auth/wallet/unlink` | POST | session | Unlink one wallet | `{address}` | `{ok}` |
+| `/api/auth/wallets` | GET, POST | session | List linked wallets / link new (nonce-based) | POST: `{address,message,signature,nonce}` | `{wallets[]}` / `{wallet}` |
+| `/api/auth/wallets/:address` | DELETE | session | Unlink by address (blocks last wallet if no password) | — | `{ok}` |
+| `/api/auth/wallets/nonce` | POST | session | Issue SIWE-like nonce for wallet link | — | `{nonce,message}` |
## OAuth (MCP clients)
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/oauth/authorize` | GET, POST | session (POST consent) | OAuth 2.1 authorization endpoint (PKCE S256 required) | query or form | 302 redirect with code |
-| `/oauth/consent` | GET, POST | session | Alias of `/oauth/authorize` (consent form) | — | — |
-| `/oauth/token` | POST | client creds (if confidential) | Exchange auth code or refresh token | form-encoded | `{access_token,refresh_token?}` |
-| `/oauth/register` | POST | public (rate-limited) | RFC 7591 dynamic client registration | `{redirect_uris,client_name?,...}` | `{client_id,client_secret?,...}` |
-| `/oauth/revoke` | POST | client creds | RFC 7009 refresh token revocation | form `{token,client_id,client_secret?}` | 200 |
-| `/oauth/introspect` | POST | client creds | RFC 7662 token introspection (own tokens only) | form `{token,client_id,client_secret?}` | `{active,...}` |
-| `/.well-known/oauth-authorization-server` | GET | public | RFC 8414 AS metadata | — | metadata JSON |
-| `/.well-known/oauth-protected-resource` | GET | public | RFC 9728 protected-resource metadata | — | metadata JSON |
-| `/api/mcp/.well-known/oauth-protected-resource` | GET | public | Same as above under MCP base | — | metadata JSON |
+| Path | Methods | Auth | Description | Input | Response |
+| ----------------------------------------------- | --------- | ------------------------------ | ----------------------------------------------------- | --------------------------------------- | -------------------------------- |
+| `/oauth/authorize` | GET, POST | session (POST consent) | OAuth 2.1 authorization endpoint (PKCE S256 required) | query or form | 302 redirect with code |
+| `/oauth/consent` | GET, POST | session | Alias of `/oauth/authorize` (consent form) | — | — |
+| `/oauth/token` | POST | client creds (if confidential) | Exchange auth code or refresh token | form-encoded | `{access_token,refresh_token?}` |
+| `/oauth/register` | POST | public (rate-limited) | RFC 7591 dynamic client registration | `{redirect_uris,client_name?,...}` | `{client_id,client_secret?,...}` |
+| `/oauth/revoke` | POST | client creds | RFC 7009 refresh token revocation | form `{token,client_id,client_secret?}` | 200 |
+| `/oauth/introspect` | POST | client creds | RFC 7662 token introspection (own tokens only) | form `{token,client_id,client_secret?}` | `{active,...}` |
+| `/.well-known/oauth-authorization-server` | GET | public | RFC 8414 AS metadata | — | metadata JSON |
+| `/.well-known/oauth-protected-resource` | GET | public | RFC 9728 protected-resource metadata | — | metadata JSON |
+| `/api/mcp/.well-known/oauth-protected-resource` | GET | public | Same as above under MCP base | — | metadata JSON |
## API Keys
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/api-keys` | GET, POST | session or bearer `profile` | List keys / mint new `sk_live_…` (plaintext once) | POST: `{name,scope?,expires_at?}` | `{data[]}` / `{key,plaintext}` |
-| `/api/api-keys/:id` | DELETE | session or bearer `profile` | Revoke key | — | `{id,revoked}` |
-| `/api/keys` | GET, POST | session | Alt developer key mgmt (`sk_live_`/`sk_test_`) | POST: `{name,scope?,expires_in_days?,environment}` | `{keys[]}` |
-| `/api/keys/:id` | DELETE | session | Revoke key | — | `{ok}` |
+| Path | Methods | Auth | Description | Input | Response |
+| ------------------- | --------- | --------------------------- | ------------------------------------------------- | -------------------------------------------------- | ------------------------------ |
+| `/api/api-keys` | GET, POST | session or bearer `profile` | List keys / mint new `sk_live_…` (plaintext once) | POST: `{name,scope?,expires_at?}` | `{data[]}` / `{key,plaintext}` |
+| `/api/api-keys/:id` | DELETE | session or bearer `profile` | Revoke key | — | `{id,revoked}` |
+| `/api/keys` | GET, POST | session | Alt developer key mgmt (`sk_live_`/`sk_test_`) | POST: `{name,scope?,expires_in_days?,environment}` | `{keys[]}` |
+| `/api/keys/:id` | DELETE | session | Revoke key | — | `{ok}` |
## Widgets
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/widgets` | GET, POST | session or bearer (`avatars:read`/`:write`) | List/create caller's widgets | POST: `{type,name,avatar_id?,config,is_public}` | `{widgets[]}` / `{widget}` |
-| `/api/widgets/:id` | GET, PATCH, DELETE | public GET (if `is_public`); owner PATCH/DELETE | Widget detail with avatar join; increments view_count for non-owners | PATCH: `{name?,config?,is_public?,avatar_id?,type?}` | `{widget}` |
-| `/api/widgets/:id/chat` | POST | public (per-widget brain config) | Visitor SSE chat for Talking Agent widgets | `{message,history?}` | SSE stream |
-| `/api/widgets/:id/duplicate` | POST | session owner (+`avatars:write`) | Clone widget | — | `{widget}` |
-| `/api/widgets/:id/stats` | GET | session owner (+`avatars:read`) | Aggregate view/referer/country stats | — | `{view_count,recent_views_7d,...}` |
-| `/api/widgets/:id/view` | POST | public | Anonymous view logger (country + referer host) | — | 204 |
-| `/api/widgets/:id/og` | GET | public | 302 to avatar thumbnail or 1200x630 SVG card | — | image/svg+xml |
-| `/api/widgets/oembed` | GET | public | oEmbed rich payload | `?url&format&maxwidth?&maxheight?` | oEmbed JSON |
-| `/api/widgets/page` (`/w/:id`) | GET | public | SSR HTML with OG/oEmbed discovery | `?id` | text/html |
+| Path | Methods | Auth | Description | Input | Response |
+| ------------------------------ | ------------------ | ----------------------------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------- | ---------------------------------- |
+| `/api/widgets` | GET, POST | session or bearer (`avatars:read`/`:write`) | List/create caller's widgets | POST: `{type,name,avatar_id?,config,is_public}` | `{widgets[]}` / `{widget}` |
+| `/api/widgets/:id` | GET, PATCH, DELETE | public GET (if `is_public`); owner PATCH/DELETE | Widget detail with avatar join; increments view_count for non-owners | PATCH: `{name?,config?,is_public?,avatar_id?,type?}` | `{widget}` |
+| `/api/widgets/:id/chat` | POST | public (per-widget brain config) | Visitor SSE chat for Talking Agent widgets | `{message,history?}` | SSE stream |
+| `/api/widgets/:id/duplicate` | POST | session owner (+`avatars:write`) | Clone widget | — | `{widget}` |
+| `/api/widgets/:id/stats` | GET | session owner (+`avatars:read`) | Aggregate view/referer/country stats | — | `{view_count,recent_views_7d,...}` |
+| `/api/widgets/:id/view` | POST | public | Anonymous view logger (country + referer host) | — | 204 |
+| `/api/widgets/:id/og` | GET | public | 302 to avatar thumbnail or 1200x630 SVG card | — | image/svg+xml |
+| `/api/widgets/oembed` | GET | public | oEmbed rich payload | `?url&format&maxwidth?&maxheight?` | oEmbed JSON |
+| `/api/widgets/page` (`/w/:id`) | GET | public | SSR HTML with OG/oEmbed discovery | `?id` | text/html |
## ERC-8004 / On-chain
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/erc8004/hydrate` | GET | session | Agents owned by user's linked wallets (from crawler index) | — | `{agents[]}` |
-| `/api/erc8004/import` | POST | session | Import on-chain agent into local `agent_identities` | `{chainId,agentId}` | `{agent}` |
-| `/api/erc8004/pin` | POST | session | Pin raw GLB/JSON/image bytes (IPFS + R2 fallback) | raw body | `{cid,url}` |
-| `/api/explore` | GET | public | Paginated indexed ERC-8004 directory | `?only3d&chain&q&cursor&limit` | `{agents[],next_cursor}` |
-| `/api/showcase` | GET | public (rate-limited) | Public directory, 3D agents only, keyset pagination | `?chainIds&sort&limit&cursor` | `{agents[],next_cursor}` |
+| Path | Methods | Auth | Description | Input | Response |
+| ---------------------- | ------- | --------------------- | ---------------------------------------------------------- | ------------------------------ | ------------------------ |
+| `/api/erc8004/hydrate` | GET | session | Agents owned by user's linked wallets (from crawler index) | — | `{agents[]}` |
+| `/api/erc8004/import` | POST | session | Import on-chain agent into local `agent_identities` | `{chainId,agentId}` | `{agent}` |
+| `/api/erc8004/pin` | POST | session | Pin raw GLB/JSON/image bytes (IPFS + R2 fallback) | raw body | `{cid,url}` |
+| `/api/explore` | GET | public | Paginated indexed ERC-8004 directory | `?only3d&chain&q&cursor&limit` | `{agents[],next_cursor}` |
+| `/api/showcase` | GET | public (rate-limited) | Public directory, 3D agents only, keyset pagination | `?chainIds&sort&limit&cursor` | `{agents[],next_cursor}` |
## Permissions (ERC-7710 delegations)
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/permissions/grant` | POST | session | Persist signed delegation after verification | delegation + signature | `{id,hash}` |
-| `/api/permissions/list` | GET | public (rate-limited) | List delegations filtered by agent or delegator | `?agentId|delegator&status&chainId&limit` | `{delegations[]}` |
-| `/api/permissions/verify` | GET | public (rate-limited, CORS any) | On-chain delegation validity check | `?hash&chainId` | `{valid,reason?}` |
-| `/api/permissions/metadata` | GET | public (rate-limited, CORS any) | Chain + DelegationManager addresses | `?chainId?` | `{chains[]}` |
-| `/api/permissions/revoke` | POST | session | Mirror on-chain `disableDelegation` into DB | `{id,txHash}` | `{revoked}` |
-| `/api/permissions/redeem` | POST | bearer `permissions:redeem` | Server-side gas-paying relayer (feature-flagged, idempotent) | `{delegation,...}` | `{txHash}` |
+| Path | Methods | Auth | Description | Input | Response |
+| --------------------------- | ------- | ------------------------------- | ------------------------------------------------------------ | ---------------------- | ------------------------------- | ----------------- |
+| `/api/permissions/grant` | POST | session | Persist signed delegation after verification | delegation + signature | `{id,hash}` |
+| `/api/permissions/list` | GET | public (rate-limited) | List delegations filtered by agent or delegator | `?agentId | delegator&status&chainId&limit` | `{delegations[]}` |
+| `/api/permissions/verify` | GET | public (rate-limited, CORS any) | On-chain delegation validity check | `?hash&chainId` | `{valid,reason?}` |
+| `/api/permissions/metadata` | GET | public (rate-limited, CORS any) | Chain + DelegationManager addresses | `?chainId?` | `{chains[]}` |
+| `/api/permissions/revoke` | POST | session | Mirror on-chain `disableDelegation` into DB | `{id,txHash}` | `{revoked}` |
+| `/api/permissions/redeem` | POST | bearer `permissions:redeem` | Server-side gas-paying relayer (feature-flagged, idempotent) | `{delegation,...}` | `{txHash}` |
## DCA / Subscriptions
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/dca-strategies` | GET, POST, DELETE | session | Manage Uniswap-V3 DCA strategies | POST: `{agent_id,delegation_id,chain_id,token_in,token_out,...,period_seconds,slippage_bps}` | `{strategy}` |
-| `/api/dca-strategies/:id` | GET, DELETE | session | Fetch/soft-delete one | — | `{strategy}` |
-| `/api/subscriptions` | GET, POST, DELETE | session or bearer | Recurring subscription records | POST: `{agentId,delegationId,periodSeconds,amountPerPeriod}` | `{subscription}` |
+| Path | Methods | Auth | Description | Input | Response |
+| ------------------------- | ----------------- | ----------------- | -------------------------------- | -------------------------------------------------------------------------------------------- | ---------------- |
+| `/api/dca-strategies` | GET, POST, DELETE | session | Manage Uniswap-V3 DCA strategies | POST: `{agent_id,delegation_id,chain_id,token_in,token_out,...,period_seconds,slippage_bps}` | `{strategy}` |
+| `/api/dca-strategies/:id` | GET, DELETE | session | Fetch/soft-delete one | — | `{strategy}` |
+| `/api/subscriptions` | GET, POST, DELETE | session or bearer | Recurring subscription records | POST: `{agentId,delegationId,periodSeconds,amountPerPeriod}` | `{subscription}` |
## Cron
-| Path | Methods | Auth | Description | Schedule |
-| --- | --- | --- | --- | --- |
-| `/api/cron/erc8004-crawl` | GET, POST | `x-vercel-cron` or `Bearer $CRON_SECRET` | Etherscan V2 log crawl → `erc8004_agents_index` + metadata enrichment | `*/15 * * * *` |
-| `/api/cron/index-delegations` | GET, POST | cron | Index `DelegationDisabled`/`Redeemed` events; expiry sweep | `*/5 * * * *` |
-| `/api/cron/run-dca` | GET, POST | cron | Execute pending DCA strategies via Uniswap V3 SwapRouter | `0 * * * *` |
-| `/api/cron/run-subscriptions` | GET, POST | cron | Process due subscription charges via skill handler | `0 * * * *` |
+| Path | Methods | Auth | Description | Schedule |
+| ----------------------------- | --------- | ---------------------------------------- | --------------------------------------------------------------------- | -------------- |
+| `/api/cron/erc8004-crawl` | GET, POST | `x-vercel-cron` or `Bearer $CRON_SECRET` | Etherscan V2 log crawl → `erc8004_agents_index` + metadata enrichment | `*/15 * * * *` |
+| `/api/cron/index-delegations` | GET, POST | cron | Index `DelegationDisabled`/`Redeemed` events; expiry sweep | `*/5 * * * *` |
+| `/api/cron/run-dca` | GET, POST | cron | Execute pending DCA strategies via Uniswap V3 SwapRouter | `0 * * * *` |
+| `/api/cron/run-subscriptions` | GET, POST | cron | Process due subscription charges via skill handler | `0 * * * *` |
## LLM / Chat / MCP
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/chat` | POST | session or bearer | Stateless Anthropic chat with viewer control tools | `{message,context?,history?,model?,maxTokens?}` | `{reply,actions[]}` |
-| `/api/llm/anthropic` | POST | embed-policy + quota | "We-pay" LLM proxy with per-agent origin/quota enforcement | Anthropic messages body + `?agentId` | Anthropic response |
-| `/api/mcp` | GET, POST, DELETE | bearer OAuth or API key | MCP Streamable HTTP (JSON-RPC); SSE notifications; session termination | JSON-RPC | JSON or SSE |
+| Path | Methods | Auth | Description | Input | Response |
+| -------------------- | ----------------- | ----------------------- | ---------------------------------------------------------------------- | ----------------------------------------------- | ------------------- |
+| `/api/chat` | POST | session or bearer | Stateless Anthropic chat with viewer control tools | `{message,context?,history?,model?,maxTokens?}` | `{reply,actions[]}` |
+| `/api/llm/anthropic` | POST | embed-policy + quota | "We-pay" LLM proxy with per-agent origin/quota enforcement | Anthropic messages body + `?agentId` | Anthropic response |
+| `/api/mcp` | GET, POST, DELETE | bearer OAuth or API key | MCP Streamable HTTP (JSON-RPC); SSE notifications; session termination | JSON-RPC | JSON or SSE |
## Onboarding / Avaturn / TTS
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/onboarding/avaturn-session` | POST | session or bearer `avatars:write` | Trade 3 selfies for Avaturn session URL | `{photos:{frontal,left,right},body_type,avatar_type}` | `{session_url,expires_at?}` |
-| `/api/onboarding/link-avatar` | POST | session or bearer | Link avatar to user's primary agent | `{avatarId,force?}` | `{agentId}` |
-| `/api/tts/eleven` | POST | session or bearer | ElevenLabs TTS proxy with R2 cache (1000 chars/h) | `{voiceId,text,modelId?}` | audio/mpeg |
-| `/api/tts/eleven/voices` | GET | session or bearer | List ElevenLabs voices (safe fields) | — | `{enabled,voices[]}` |
+| Path | Methods | Auth | Description | Input | Response |
+| --------------------------------- | ------- | --------------------------------- | ------------------------------------------------- | ----------------------------------------------------- | --------------------------- |
+| `/api/onboarding/avaturn-session` | POST | session or bearer `avatars:write` | Trade 3 selfies for Avaturn session URL | `{photos:{frontal,left,right},body_type,avatar_type}` | `{session_url,expires_at?}` |
+| `/api/onboarding/link-avatar` | POST | session or bearer | Link avatar to user's primary agent | `{avatarId,force?}` | `{agentId}` |
+| `/api/tts/eleven` | POST | session or bearer | ElevenLabs TTS proxy with R2 cache (1000 chars/h) | `{voiceId,text,modelId?}` | audio/mpeg |
+| `/api/tts/eleven/voices` | GET | session or bearer | List ElevenLabs voices (safe fields) | — | `{enabled,voices[]}` |
## LobeHub
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/lobehub/config` | GET | public (open CORS) | LobeHub plugin manifest (from `/.well-known/lobehub-plugin.json`) | — | manifest JSON |
-| `/api/lobehub/manifest` | GET | public | LobeHub plugin manifest (from `public/lobehub/plugin.json`) | — | manifest JSON |
-| `/api/lobehub/handshake` | POST | public (rate-limited) | Return iframe URL + embed policy for a LobeHub host | `{agentId,hostOrigin?}` | `{iframeUrl,embedPolicy}` |
+| Path | Methods | Auth | Description | Input | Response |
+| ------------------------ | ------- | --------------------- | ----------------------------------------------------------------- | ----------------------- | ------------------------- |
+| `/api/lobehub/config` | GET | public (open CORS) | LobeHub plugin manifest (from `/.well-known/lobehub-plugin.json`) | — | manifest JSON |
+| `/api/lobehub/manifest` | GET | public | LobeHub plugin manifest (from `public/lobehub/plugin.json`) | — | manifest JSON |
+| `/api/lobehub/handshake` | POST | public (rate-limited) | Return iframe URL + embed policy for a LobeHub host | `{agentId,hostOrigin?}` | `{iframeUrl,embedPolicy}` |
## Pinning
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/pinning/pin` | POST | session or bearer | Pin manifest or GLB to IPFS via Pinata/Web3.Storage | multipart or data URL | `{cid,provider}` |
-| `/api/pinning/status` | GET | public (rate-limited) | Cross-provider pin status | `?cid` | `{pinned,providers[]}` |
+| Path | Methods | Auth | Description | Input | Response |
+| --------------------- | ------- | --------------------- | --------------------------------------------------- | --------------------- | ---------------------- |
+| `/api/pinning/pin` | POST | session or bearer | Pin manifest or GLB to IPFS via Pinata/Web3.Storage | multipart or data URL | `{cid,provider}` |
+| `/api/pinning/status` | GET | public (rate-limited) | Cross-provider pin status | `?cid` | `{pinned,providers[]}` |
## Usage / Config / Artifact / CZ
-| Path | Methods | Auth | Description | Input | Response |
-| --- | --- | --- | --- | --- | --- |
-| `/api/usage/summary` | GET | session or bearer `profile` | Dashboard usage counters + plan quota | — | `{plan,counts}` |
-| `/api/config` | GET | public | Non-secret client config (walletconnect id) | — | `{walletConnectProjectId}` |
-| `/api/artifact` | GET | public | Self-contained HTML for Claude.ai artifacts (viewer or agent) | `?agent=<id>|?model=<glbUrl>` | text/html |
-| `/api/cz/claim` | GET, POST | public (ECDSA signature) | CZ agent claim: issue nonce / verify sig → on-chain tx payload | GET: `?address`; POST: `{address,signature,nonce}` | `{nonce}` / `{tx}` |
+| Path | Methods | Auth | Description | Input | Response |
+| -------------------- | --------- | --------------------------- | -------------------------------------------------------------- | -------------------------------------------------- | -------------------------- | --------- |
+| `/api/usage/summary` | GET | session or bearer `profile` | Dashboard usage counters + plan quota | — | `{plan,counts}` |
+| `/api/config` | GET | public | Non-secret client config (walletconnect id) | — | `{walletConnectProjectId}` |
+| `/api/artifact` | GET | public | Self-contained HTML for Claude.ai artifacts (viewer or agent) | `?agent=<id> | ?model=<glbUrl>` | text/html |
+| `/api/cz/claim` | GET, POST | public (ECDSA signature) | CZ agent claim: issue nonce / verify sig → on-chain tx payload | GET: `?address`; POST: `{address,signature,nonce}` | `{nonce}` / `{tx}` |
## Notes & Gaps
- **Route quirks**: `/api/agents/me` is rewritten to `/api/agents` (handler detects `/me` from pathname). `/api/agents/:id` delegates to handlers re-exported from `api/agents.js`.
- **Duplicate key surfaces**: `/api/api-keys` and `/api/keys` are two parallel key-management endpoints with different token formats and schemas — likely candidates for consolidation.
- **Unfinished / stub**:
- - `/api/avatars/:id/pin-ipfs` returns a stub CID (`stub:sha256-…`) — real Pinata/Web3.Storage pinning not wired.
- - `/api/avatars/regenerate` returns 501 until `AVATAR_REGEN_PROVIDER` is set.
- - `/api/permissions/metadata` dynamically imports `src/erc7710/abi.js` with a try/catch — legacy shim for pre-task-03 state.
+ - `/api/avatars/:id/pin-ipfs` returns a stub CID (`stub:sha256-…`) — real Pinata/Web3.Storage pinning not wired.
+ - `/api/avatars/regenerate` returns 501 until `AVATAR_REGEN_PROVIDER` is set.
+ - `/api/permissions/metadata` dynamically imports `src/erc7710/abi.js` with a try/catch — legacy shim for pre-task-03 state.
- **Open CORS on auth surfaces**: `/api/permissions/verify` and `/api/permissions/metadata` set `access-control-allow-origin: *` explicitly (by design, for cross-origin delegation viewers).
- **SSE**: `/api/widgets/:id/chat` and `/api/mcp` (GET) both declare SSE, but `/api/widgets/:id/chat` currently does a single-shot Anthropic call framed as SSE for forward-compat.
- **vercel.json catch-all**: `{"src": "/api/(.*)", "dest": "/api/$1"}` after explicit rewrites means every `api/**/*.js` file is reachable even without an explicit route entry. Endpoints like `/api/agents/check-name`, `/api/agents/register-prep`, `/api/agents/register-confirm`, `/api/permissions/*`, `/api/subscriptions`, `/api/avatars/*`, `/api/auth/*`, `/api/usage/summary`, `/api/tts/*`, `/api/lobehub/*`, `/api/pinning/*`, `/api/onboarding/*`, `/api/config`, `/api/chat`, `/api/api-keys`, `/api/keys`, `/api/cron/*`, `/api/erc8004/pin` are served via this catch-all.
diff --git a/embed-test.html b/embed-test.html
index 5769eb774..2ecade8fd 100644
--- a/embed-test.html
+++ b/embed-test.html
@@ -1,29 +1,34 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>3D Agent Embed Test</title>
- <style>
- body {
- margin: 0;
- padding: 40px;
- background: #111;
- color: #fff;
- font-family: sans-serif;
- }
- h1 { margin-bottom: 8px; }
- p { color: #aaa; margin-bottom: 24px; }
- </style>
-</head>
-<body>
- <h1>3D Agent Web Component Test</h1>
- <p>Testing the <code>&lt;agent-3d&gt;</code> web component embed.</p>
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>3D Agent Embed Test</title>
+ <style>
+ body {
+ margin: 0;
+ padding: 40px;
+ background: #111;
+ color: #fff;
+ font-family: sans-serif;
+ }
+ h1 {
+ margin-bottom: 8px;
+ }
+ p {
+ color: #aaa;
+ margin-bottom: 24px;
+ }
+ </style>
+ </head>
+ <body>
+ <h1>3D Agent Web Component Test</h1>
+ <p>Testing the <code>&lt;agent-3d&gt;</code> web component embed.</p>
- <script type="module" src="https://3dagent.vercel.app/dist-lib/agent-3d.js"></script>
- <agent-3d
- src="https://3dagent.vercel.app/api/avatars/bdef4d68-710e-4fa6-8a8d-d5c00857b85c"
- style="width:600px;height:600px"
- ></agent-3d>
-</body>
+ <script type="module" src="https://3dagent.vercel.app/dist-lib/agent-3d.js"></script>
+ <agent-3d
+ src="https://3dagent.vercel.app/api/avatars/bdef4d68-710e-4fa6-8a8d-d5c00857b85c"
+ style="width: 600px; height: 600px"
+ ></agent-3d>
+ </body>
</html>
diff --git a/home.html b/home.html
index 9cab62eb7..d2b09ec29 100644
--- a/home.html
+++ b/home.html
@@ -40,7 +40,9 @@
<a href="#main-content" class="h-skip-link">Skip to main content</a>
<header>
<h1>
- <a href="/" aria-label="3D Agent home"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
+ <a href="/" aria-label="3D Agent home"
+ ><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a
+ >
</h1>
<nav class="home-nav" aria-label="Primary">
<a href="/app">Viewer</a>
diff --git a/index.html b/index.html
index 5f2b01083..d7c290f5b 100644
--- a/index.html
+++ b/index.html
@@ -540,7 +540,10 @@
>Try the viewer →</a
>
</div>
- <p class="hero-signin-hint scroll-reveal" id="hero-signin-hint">Already have an account? <a href="/login" class="hero-signin-link">Sign in →</a></p>
+ <p class="hero-signin-hint scroll-reveal" id="hero-signin-hint">
+ Already have an account?
+ <a href="/login" class="hero-signin-link">Sign in →</a>
+ </p>
<ul
class="hero-proof scroll-reveal"
aria-label="Supported formats and standards"
diff --git a/lobehub-plugin/dev/index.html b/lobehub-plugin/dev/index.html
index 075281e91..2f77e3bf6 100644
--- a/lobehub-plugin/dev/index.html
+++ b/lobehub-plugin/dev/index.html
@@ -175,7 +175,11 @@
</div>
<div class="row">
<label style="width: 80px">GLB URL</label>
- <input type="text" id="src-input" placeholder="optional — bypasses agent API (e.g. /avatars/cz.glb)" />
+ <input
+ type="text"
+ id="src-input"
+ placeholder="optional — bypasses agent API (e.g. /avatars/cz.glb)"
+ />
</div>
<div class="row">
<label style="width: 80px">API Origin</label>
diff --git a/package-lock.json b/package-lock.json
index 9c2560e79..ab3e1fcdd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -22,18 +22,17 @@
"bcryptjs": "^2.4.3",
"dat.gui": "^0.7.9",
"ethers": "^6.16.0",
- "fbx-parser": "^2.1.3",
"gltf-validator": "^2.0.0-dev.3.10",
"jose": "^5.9.6",
"query-string": "^8.1.0",
"simple-dropzone": "^0.8.3",
"three": "^0.176.0",
- "tweakpane": "^4.0.5",
"vhtml": "^2.2.0",
"viem": "^2.18.0",
"zod": "^3.23.8"
},
"devDependencies": {
+ "playwright": "^1.59.1",
"prettier": "^3.2.5",
"sharp": "^0.34.5",
"vite": "^7.3.2",
@@ -3571,12 +3570,6 @@
"url": "https://paulmillr.com/funding/"
}
},
- "node_modules/@picode/binary-reader": {
- "version": "0.0.4",
- "resolved": "https://registry.npmjs.org/@picode/binary-reader/-/binary-reader-0.0.4.tgz",
- "integrity": "sha512-ae1+S0EH+K6uuE8aCQs+lpjDMBy54Gimz0j/LyTUx3H090nzyiyRKUsPx3SmZvgUqzJIZnw+sfIB8Us/iPbvPA==",
- "license": "MIT"
- },
"node_modules/@privy-io/api-base": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/@privy-io/api-base/-/api-base-1.8.3.tgz",
@@ -6084,16 +6077,6 @@
"fxparser": "src/cli/cli.js"
}
},
- "node_modules/fbx-parser": {
- "version": "2.1.3",
- "resolved": "https://registry.npmjs.org/fbx-parser/-/fbx-parser-2.1.3.tgz",
- "integrity": "sha512-2Yp/A4WHD0dc2A1lheX5243HiOObQY+Do8dd12v2ppFnG6T2Ic24I2PaeDau0vp/hKuqqA1LHjAG54sQWVY62w==",
- "license": "MIT",
- "dependencies": {
- "@picode/binary-reader": "^0.0.4",
- "pako": "^2.0.3"
- }
- },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -7362,12 +7345,6 @@
"dev": true,
"license": "BlueOak-1.0.0"
},
- "node_modules/pako": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
- "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
- "license": "(MIT AND Zlib)"
- },
"node_modules/path-expression-matcher": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",
@@ -7496,6 +7473,53 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/playwright": {
+ "version": "1.59.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",
+ "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.59.1"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "fsevents": "2.3.2"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.59.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",
+ "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/playwright/node_modules/fsevents": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
@@ -8489,15 +8513,6 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
- "node_modules/tweakpane": {
- "version": "4.0.5",
- "resolved": "https://registry.npmjs.org/tweakpane/-/tweakpane-4.0.5.tgz",
- "integrity": "sha512-rxEXdSI+ArlG1RyO6FghC4ZUX8JkEfz8F3v1JuteXSV0pEtHJzyo07fcDG+NsJfN5L39kSbCYbB9cBGHyuI/tQ==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/cocopon"
- }
- },
"node_modules/type-fest": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz",
diff --git a/package.json b/package.json
index 848d4c6c3..72698c50e 100644
--- a/package.json
+++ b/package.json
@@ -63,18 +63,17 @@
"bcryptjs": "^2.4.3",
"dat.gui": "^0.7.9",
"ethers": "^6.16.0",
- "fbx-parser": "^2.1.3",
"gltf-validator": "^2.0.0-dev.3.10",
"jose": "^5.9.6",
"query-string": "^8.1.0",
"simple-dropzone": "^0.8.3",
"three": "^0.176.0",
- "tweakpane": "^4.0.5",
"vhtml": "^2.2.0",
"viem": "^2.18.0",
"zod": "^3.23.8"
},
"devDependencies": {
+ "playwright": "^1.59.1",
"prettier": "^3.2.5",
"sharp": "^0.34.5",
"vite": "^7.3.2",
diff --git a/prompts/permissions/00-README.md b/prompts/permissions/00-README.md
index 0e86ce123..5416811fe 100644
--- a/prompts/permissions/00-README.md
+++ b/prompts/permissions/00-README.md
@@ -47,14 +47,14 @@ CREATE INDEX idx_delegations_delegator ON agent_delegations(delegator_address);
### API — endpoints under `/api/permissions/`
-| Method | Path | Body / Query | Response |
-| ------ | ---------------------------------- | -------------------------------------------------------------- | ----------------------------------- |
-| POST | `/api/permissions/grant` | `{ agentId, chainId, delegation, scope }` | `{ ok, id, delegationHash }` |
-| GET | `/api/permissions/list` | `?agentId=X` or `?delegator=0x...` | `{ ok, delegations: [...] }` |
-| POST | `/api/permissions/revoke` | `{ id, txHash }` | `{ ok, status: 'revoked' }` |
-| POST | `/api/permissions/redeem` | `{ id, calls: [{to,value,data}] }` (auth: agent bearer token) | `{ ok, txHash, receipt }` |
-| GET | `/api/permissions/metadata` | `?agentId=X` (public, cached) | `{ ok, delegations: [public view] }`|
-| GET | `/api/permissions/verify` | `?hash=0x...&chainId=N` | `{ ok, valid, reason? }` |
+| Method | Path | Body / Query | Response |
+| ------ | --------------------------- | ------------------------------------------------------------- | ------------------------------------ |
+| POST | `/api/permissions/grant` | `{ agentId, chainId, delegation, scope }` | `{ ok, id, delegationHash }` |
+| GET | `/api/permissions/list` | `?agentId=X` or `?delegator=0x...` | `{ ok, delegations: [...] }` |
+| POST | `/api/permissions/revoke` | `{ id, txHash }` | `{ ok, status: 'revoked' }` |
+| POST | `/api/permissions/redeem` | `{ id, calls: [{to,value,data}] }` (auth: agent bearer token) | `{ ok, txHash, receipt }` |
+| GET | `/api/permissions/metadata` | `?agentId=X` (public, cached) | `{ ok, delegations: [public view] }` |
+| GET | `/api/permissions/verify` | `?hash=0x...&chainId=N` | `{ ok, valid, reason? }` |
All responses follow `{ ok: true, ... }` / `{ ok: false, error: 'code', message: '...' }` per [api/CLAUDE.md](../../api/CLAUDE.md).
@@ -125,28 +125,28 @@ export async function getActiveDelegation({ agentId, chainId }) { /* */ }
## Tasks (independent — run in any order)
-| # | File | Area |
-| --- | --------------------------------------------------------------------- | ------------------------------ |
-| 01 | [01-permissions-spec.md](./01-permissions-spec.md) | specs (new doc) |
-| 02 | [02-manifest-permissions-field.md](./02-manifest-permissions-field.md)| specs (append) |
-| 03 | [03-erc7710-abi.md](./03-erc7710-abi.md) | src/erc7710/ |
-| 04 | [04-delegation-toolkit.md](./04-delegation-toolkit.md) | src/permissions/toolkit.js |
-| 05 | [05-db-schema.md](./05-db-schema.md) | schema + migration |
-| 06 | [06-api-grant.md](./06-api-grant.md) | api/permissions/grant.js |
-| 07 | [07-api-list.md](./07-api-list.md) | api/permissions/list.js |
-| 08 | [08-api-revoke.md](./08-api-revoke.md) | api/permissions/revoke.js |
-| 09 | [09-api-redeem.md](./09-api-redeem.md) | api/permissions/redeem.js |
-| 10 | [10-grant-ui.md](./10-grant-ui.md) | src/permissions/grant-modal.js |
-| 11 | [11-manage-ui.md](./11-manage-ui.md) | src/permissions/manage-panel.js|
-| 12 | [12-api-metadata.md](./12-api-metadata.md) | api/permissions/metadata.js |
-| 13 | [13-runtime-redeem-hook.md](./13-runtime-redeem-hook.md) | src/runtime/ |
-| 14 | [14-skill-tip-jar.md](./14-skill-tip-jar.md) | public/skills/tip-jar/ |
-| 15 | [15-skill-subscription.md](./15-skill-subscription.md) | public/skills/subscription/ |
-| 16 | [16-skill-dca.md](./16-skill-dca.md) | public/skills/dca/ |
-| 17 | [17-embed-spec-delegation.md](./17-embed-spec-delegation.md) | specs (append) |
-| 18 | [18-sdk-permissions.md](./18-sdk-permissions.md) | sdk/ |
-| 19 | [19-indexer-cron.md](./19-indexer-cron.md) | api/cron/ |
-| 20 | [20-verify-endpoint.md](./20-verify-endpoint.md) | api/permissions/verify.js |
+| # | File | Area |
+| --- | ---------------------------------------------------------------------- | ------------------------------- |
+| 01 | [01-permissions-spec.md](./01-permissions-spec.md) | specs (new doc) |
+| 02 | [02-manifest-permissions-field.md](./02-manifest-permissions-field.md) | specs (append) |
+| 03 | [03-erc7710-abi.md](./03-erc7710-abi.md) | src/erc7710/ |
+| 04 | [04-delegation-toolkit.md](./04-delegation-toolkit.md) | src/permissions/toolkit.js |
+| 05 | [05-db-schema.md](./05-db-schema.md) | schema + migration |
+| 06 | [06-api-grant.md](./06-api-grant.md) | api/permissions/grant.js |
+| 07 | [07-api-list.md](./07-api-list.md) | api/permissions/list.js |
+| 08 | [08-api-revoke.md](./08-api-revoke.md) | api/permissions/revoke.js |
+| 09 | [09-api-redeem.md](./09-api-redeem.md) | api/permissions/redeem.js |
+| 10 | [10-grant-ui.md](./10-grant-ui.md) | src/permissions/grant-modal.js |
+| 11 | [11-manage-ui.md](./11-manage-ui.md) | src/permissions/manage-panel.js |
+| 12 | [12-api-metadata.md](./12-api-metadata.md) | api/permissions/metadata.js |
+| 13 | [13-runtime-redeem-hook.md](./13-runtime-redeem-hook.md) | src/runtime/ |
+| 14 | [14-skill-tip-jar.md](./14-skill-tip-jar.md) | public/skills/tip-jar/ |
+| 15 | [15-skill-subscription.md](./15-skill-subscription.md) | public/skills/subscription/ |
+| 16 | [16-skill-dca.md](./16-skill-dca.md) | public/skills/dca/ |
+| 17 | [17-embed-spec-delegation.md](./17-embed-spec-delegation.md) | specs (append) |
+| 18 | [18-sdk-permissions.md](./18-sdk-permissions.md) | sdk/ |
+| 19 | [19-indexer-cron.md](./19-indexer-cron.md) | api/cron/ |
+| 20 | [20-verify-endpoint.md](./20-verify-endpoint.md) | api/permissions/verify.js |
All tasks reference the Canonical Shapes section above. None depend on another task being done first — each ships its own slice. Collisions on existing files are limited to `specs/AGENT_MANIFEST.md` (task 02) and `specs/EMBED_SPEC.md` (task 17), which are different files.
diff --git a/prompts/permissions/04-delegation-toolkit.md b/prompts/permissions/04-delegation-toolkit.md
index 44fa959e5..2d44b9ae1 100644
--- a/prompts/permissions/04-delegation-toolkit.md
+++ b/prompts/permissions/04-delegation-toolkit.md
@@ -26,10 +26,10 @@ Every UI + runtime path needs a single, well-typed (JSDoc) facade over the MetaM
```js
export class PermissionError extends Error {
- constructor(code, message) {
- super(message);
- this.code = code;
- }
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
}
```
diff --git a/prompts/permissions/07-api-list.md b/prompts/permissions/07-api-list.md
index e6d65aa82..745438fa2 100644
--- a/prompts/permissions/07-api-list.md
+++ b/prompts/permissions/07-api-list.md
@@ -29,19 +29,19 @@ Create `api/permissions/list.js` (GET only):
6. **Public view shape** (when agentId-only, no auth):
```jsonc
{
- "id": "...",
- "chainId": 84532,
- "delegator": "0x...",
- "delegate": "0x...",
- "delegationHash": "0x...",
- "scope": {
- /* from column */
- },
- "status": "active",
- "expiresAt": "...",
- "createdAt": "...",
- "lastRedeemedAt": "...",
- "redemptionCount": 3
+ "id": "...",
+ "chainId": 84532,
+ "delegator": "0x...",
+ "delegate": "0x...",
+ "delegationHash": "0x...",
+ "scope": {
+ /* from column */
+ },
+ "status": "active",
+ "expiresAt": "...",
+ "createdAt": "...",
+ "lastRedeemedAt": "...",
+ "redemptionCount": 3,
}
```
Never return `delegation_json` in the public view.
diff --git a/prompts/permissions/09-api-redeem.md b/prompts/permissions/09-api-redeem.md
index 3475a9991..1a197075b 100644
--- a/prompts/permissions/09-api-redeem.md
+++ b/prompts/permissions/09-api-redeem.md
@@ -15,12 +15,14 @@ Skills running inside a host iframe (Claude artifact, LobeHub) may not have acce
## Build this
1. **Env**: add these to `.env.example` and read them via `process.env`:
+
- `AGENT_RELAYER_KEY` — hex private key of a relayer EOA (server-held) that submits `redeemDelegations` on behalf of agents. One key per environment; rotate via Vercel env.
- `AGENT_RELAYER_ADDRESS` — derived; used as the `delegate` for any delegation the relayer can redeem.
- `RPC_URL_<CHAINID>` — per-chain RPC (e.g. `RPC_URL_84532`). Reuse existing RPC env vars if already defined in the project; grep first.
- A feature flag `PERMISSIONS_RELAYER_ENABLED=true|false`. Default false. Endpoint 503s if false.
2. **Create `api/permissions/redeem.js`** (POST only):
+
- Method/CORS/rate-limit (`limits.strict` — this one costs gas).
- Auth: `authenticateBearer(req)` against `api_keys` table (agent-scope bearer; scope must include `permissions:redeem`). No user sessions here — this is a machine endpoint.
- Body: `{ id: uuid, calls: [{ to, value, data }] }`, max 4 calls. Validate each call: `to` checksummed, `value` stringified wei, `data` hex.
@@ -38,6 +40,7 @@ Skills running inside a host iframe (Claude artifact, LobeHub) may not have acce
- Respond `{ ok: true, txHash, receipt }` (trim receipt to `{ status, blockNumber, gasUsed }`).
3. **Failure modes**:
+
- Toolkit throws `PermissionError` with code `delegation_revoked` → 409.
- RPC error → 502 `rpc_error`.
- Scope exceeded (our own check) → 403 `scope_exceeded`.
diff --git a/prompts/permissions/12-api-metadata.md b/prompts/permissions/12-api-metadata.md
index 2309e8041..7e8e85e67 100644
--- a/prompts/permissions/12-api-metadata.md
+++ b/prompts/permissions/12-api-metadata.md
@@ -21,26 +21,26 @@ Create `api/permissions/metadata.js` (GET only):
4. **Shape** (must match `specs/AGENT_MANIFEST.md` `permissions.delegations[]`):
```jsonc
{
- "ok": true,
- "agentId": "...",
- "spec": "erc-7715/0.1",
- "delegationManager": "0x...", // resolved from abi.js per chainId
- "delegations": [
- {
- "chainId": 84532,
- "delegator": "0x...",
- "delegate": "0x...",
- "hash": "0x...",
- "scope": {
- /* from column, redacted signatures */
- },
- "expiresAt": "...",
- "createdAt": "...",
- "envelope": {
- /* full signed envelope INCLUDING signature — it's on-chain verifiable, not secret */
- }
- }
- ]
+ "ok": true,
+ "agentId": "...",
+ "spec": "erc-7715/0.1",
+ "delegationManager": "0x...", // resolved from abi.js per chainId
+ "delegations": [
+ {
+ "chainId": 84532,
+ "delegator": "0x...",
+ "delegate": "0x...",
+ "hash": "0x...",
+ "scope": {
+ /* from column, redacted signatures */
+ },
+ "expiresAt": "...",
+ "createdAt": "...",
+ "envelope": {
+ /* full signed envelope INCLUDING signature — it's on-chain verifiable, not secret */
+ },
+ },
+ ],
}
```
Signatures are NOT secret — they're meant to be on-chain-verifiable. Including the envelope is what lets an embed redeem without a round-trip. This is the intentional difference from `/list`'s public view.
diff --git a/prompts/permissions/13-runtime-redeem-hook.md b/prompts/permissions/13-runtime-redeem-hook.md
index 598238fb0..ab87fb23f 100644
--- a/prompts/permissions/13-runtime-redeem-hook.md
+++ b/prompts/permissions/13-runtime-redeem-hook.md
@@ -17,12 +17,14 @@ Skills are the primary consumer of delegations. A skill ("tip the creator", "sub
Create `src/runtime/delegation-redeem.js` exporting:
1. **`async getActiveDelegation({ agentId, chainId, scopeHint? })`**
+
- Fetches `/api/permissions/metadata?agentId=...&chainId=...`.
- Filters to the delegation whose `scope` best matches `scopeHint` (if provided: prefer a scope with the right `token` and enough remaining `maxAmount`).
- Returns the envelope or `null` if none match.
- Caches the response in-memory for 60 seconds keyed by `{agentId, chainId}`. Cache is invalidated on a successful revoke event via the protocol bus.
2. **`async redeemFromSkill({ agentId, chainId, calls, skillId, mode? })`**
+
- `mode` is `'client' | 'relayer' | 'auto'` (default `'auto'`).
- `'client'`: get a signer from the host page's wallet helper (same one task 10 uses) and call `redeemDelegation` from the toolkit directly.
- `'relayer'`: `POST /api/permissions/redeem` with a bearer token pulled from the agent's runtime config (the host is responsible for providing the bearer; if missing, throw `no_relayer_token`).
diff --git a/prompts/permissions/14-skill-tip-jar.md b/prompts/permissions/14-skill-tip-jar.md
index 6d4c72b00..2baea85c6 100644
--- a/prompts/permissions/14-skill-tip-jar.md
+++ b/prompts/permissions/14-skill-tip-jar.md
@@ -24,11 +24,11 @@ Create `public/skills/tip-jar/` with:
- `default_scope_preset`:
```jsonc
{
- "token": "<USDC address per chain>",
- "maxAmount": "10000000", // 10 USDC (6 decimals)
- "period": "daily",
- "targets": ["<this skill's executor contract>"],
- "expiry_days": 30
+ "token": "<USDC address per chain>",
+ "maxAmount": "10000000", // 10 USDC (6 decimals)
+ "period": "daily",
+ "targets": ["<this skill's executor contract>"],
+ "expiry_days": 30,
}
```
- Body: short human description of what it does.
diff --git a/prompts/permissions/15-skill-subscription.md b/prompts/permissions/15-skill-subscription.md
index 030496ffa..b6888de67 100644
--- a/prompts/permissions/15-skill-subscription.md
+++ b/prompts/permissions/15-skill-subscription.md
@@ -25,11 +25,11 @@ Create `public/skills/subscription/` with:
- `default_scope_preset`:
```jsonc
{
- "token": "<USDC>",
- "maxAmount": "5000000", // 5 USDC
- "period": "weekly",
- "targets": ["<subscription executor contract>"],
- "expiry_days": 90
+ "token": "<USDC>",
+ "maxAmount": "5000000", // 5 USDC
+ "period": "weekly",
+ "targets": ["<subscription executor contract>"],
+ "expiry_days": 90,
}
```
2. **`skill.js`** — ESM exporting:
diff --git a/prompts/permissions/16-skill-dca.md b/prompts/permissions/16-skill-dca.md
index 0c78edd62..dde85c70d 100644
--- a/prompts/permissions/16-skill-dca.md
+++ b/prompts/permissions/16-skill-dca.md
@@ -24,12 +24,12 @@ Create `public/skills/dca/`:
- `default_scope_preset`:
```jsonc
{
- "token": "<USDC>",
- "maxAmount": "100000000", // 100 USDC per day cap
- "period": "daily",
- "targets": ["<Uniswap V3 SwapRouter address>"],
- "selectors": ["0x04e45aaf"], // exactInputSingle selector — verify from Uniswap ABI
- "expiry_days": 30
+ "token": "<USDC>",
+ "maxAmount": "100000000", // 100 USDC per day cap
+ "period": "daily",
+ "targets": ["<Uniswap V3 SwapRouter address>"],
+ "selectors": ["0x04e45aaf"], // exactInputSingle selector — verify from Uniswap ABI
+ "expiry_days": 30,
}
```
2. **`skill.js`**:
diff --git a/prompts/permissions/17-embed-spec-delegation.md b/prompts/permissions/17-embed-spec-delegation.md
index df68d6dce..4ec53677f 100644
--- a/prompts/permissions/17-embed-spec-delegation.md
+++ b/prompts/permissions/17-embed-spec-delegation.md
@@ -26,12 +26,14 @@ Append a new section to `specs/EMBED_SPEC.md` titled **Delegations (optional, v0
- `relayer` — embed may call `/api/permissions/redeem` with a bearer token the host has provisioned
- `permissions-bearer` — when `permissions="relayer"`, the bearer token scoped to `permissions:redeem` (per task 09). Opaque string, host is responsible for rotation.
3. **Host → embed messages** (post-message protocol):
+
- `permissions.query` (host→embed): request a list of active delegations matching a filter
- `permissions.redeem` (host→embed): ask the embed to initiate a redemption on the host's behalf
- `permissions.redeemed` (embed→host): announce a successful redemption with tx hash
- `permissions.error` (embed→host): announce a failed redemption with code + message
Shapes documented inline, copy the error codes verbatim from the canonical shapes.
+
4. **Claude artifact profile**:
- Default `permissions="readonly"`. Claude artifacts can render tipping UIs and show status, but a skill that needs to actually transact must request `permissions="relayer"` and the agent owner must provision a bearer token at embed time.
- Document that the artifact has no persistent wallet connection — `interactive` is not supported in the Claude profile.
diff --git a/prompts/permissions/18-sdk-permissions.md b/prompts/permissions/18-sdk-permissions.md
index 6700563cc..aad98ca16 100644
--- a/prompts/permissions/18-sdk-permissions.md
+++ b/prompts/permissions/18-sdk-permissions.md
@@ -19,37 +19,47 @@ Third-party developers integrating agents into their own apps need a typed SDK e
```ts
export interface DelegationPublic {
- /* ... matches metadata endpoint shape ... */
+ /* ... matches metadata endpoint shape ... */
}
export interface ScopePreset {
- token: string;
- maxAmount: string;
- period: 'once' | 'daily' | 'weekly';
- targets: string[];
- expiryDays: number;
+ token: string;
+ maxAmount: string;
+ period: 'once' | 'daily' | 'weekly';
+ targets: string[];
+ expiryDays: number;
}
export class PermissionsClient {
- constructor(opts: { baseUrl?: string; bearer?: string });
-
- listDelegations(params: { agentId?: string; delegator?: string; status?: string }): Promise<DelegationPublic[]>;
-
- getMetadata(agentId: string): Promise<{ spec: string; delegations: DelegationPublic[] }>;
-
- // Browser only — throws in Node
- async grant(params: {
- agentId: string;
- chainId: number;
- preset: ScopePreset;
- signer: ethers.Signer;
- }): Promise<{ id: string; delegationHash: string }>;
-
- async redeem(params: { id: string; calls: Array<{ to: string; value?: string; data: string }> }): Promise<{
- txHash: string;
- }>;
-
- async revoke(params: { id: string; signer: ethers.Signer }): Promise<{ status: 'revoked'; txHash: string }>;
-
- async verify(hash: string, chainId: number): Promise<{ valid: boolean; reason?: string }>;
+ constructor(opts: { baseUrl?: string; bearer?: string });
+
+ listDelegations(params: {
+ agentId?: string;
+ delegator?: string;
+ status?: string;
+ }): Promise<DelegationPublic[]>;
+
+ getMetadata(agentId: string): Promise<{ spec: string; delegations: DelegationPublic[] }>;
+
+ // Browser only — throws in Node
+ async grant(params: {
+ agentId: string;
+ chainId: number;
+ preset: ScopePreset;
+ signer: ethers.Signer;
+ }): Promise<{ id: string; delegationHash: string }>;
+
+ async redeem(params: {
+ id: string;
+ calls: Array<{ to: string; value?: string; data: string }>;
+ }): Promise<{
+ txHash: string;
+ }>;
+
+ async revoke(params: {
+ id: string;
+ signer: ethers.Signer;
+ }): Promise<{ status: 'revoked'; txHash: string }>;
+
+ async verify(hash: string, chainId: number): Promise<{ valid: boolean; reason?: string }>;
}
```
@@ -71,6 +81,7 @@ Third-party developers integrating agents into their own apps need a typed SDK e
```
6. **Tests**: add `sdk/test/permissions.test.ts` (or `.js` matching convention) covering:
+
- URL construction for each method
- Bearer header is sent when set
- Error surface: a 403 from the server becomes a thrown `PermissionError` with the right code
diff --git a/public/agent/index.html b/public/agent/index.html
index e0e1009bb..7c1647a6d 100644
--- a/public/agent/index.html
+++ b/public/agent/index.html
@@ -471,15 +471,20 @@
transition: color 0.15s;
}
- .mp-refresh-btn:hover { color: rgba(255, 255, 255, 0.7); }
+ .mp-refresh-btn:hover {
+ color: rgba(255, 255, 255, 0.7);
+ }
- .mp-loading, .mp-error {
+ .mp-loading,
+ .mp-error {
font-size: 0.764rem;
color: rgba(255, 255, 255, 0.3);
padding: 1rem 0;
}
- .mp-error { color: #fca5a5; }
+ .mp-error {
+ color: #fca5a5;
+ }
.mp-empty {
font-size: 0.764rem;
@@ -488,7 +493,9 @@
text-align: center;
}
- .mp-empty p { margin: 0 0 0.618rem; }
+ .mp-empty p {
+ margin: 0 0 0.618rem;
+ }
.mp-grant-btn {
background: rgba(255, 255, 255, 0.06);
@@ -499,7 +506,9 @@
padding: 0.382rem 0.75rem;
border-radius: 999px;
cursor: pointer;
- transition: background 0.15s, color 0.15s;
+ transition:
+ background 0.15s,
+ color 0.15s;
}
.mp-grant-btn:hover {
@@ -516,9 +525,15 @@
transition: border-color 0.2s;
}
- .mp-card--active { border-color: rgba(134, 239, 172, 0.15); }
- .mp-card--revoked { opacity: 0.5; }
- .mp-card--expired { border-color: rgba(251, 191, 36, 0.15); }
+ .mp-card--active {
+ border-color: rgba(134, 239, 172, 0.15);
+ }
+ .mp-card--revoked {
+ opacity: 0.5;
+ }
+ .mp-card--expired {
+ border-color: rgba(251, 191, 36, 0.15);
+ }
.mp-card-top {
display: flex;
@@ -534,14 +549,23 @@
font-weight: 500;
}
- .mp-badge--active { background: rgba(134, 239, 172, 0.15); color: #86efac; }
- .mp-badge--revoked { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.4); }
- .mp-badge--expired { background: rgba(251, 191, 36, 0.12); color: #fbbf24; }
+ .mp-badge--active {
+ background: rgba(134, 239, 172, 0.15);
+ color: #86efac;
+ }
+ .mp-badge--revoked {
+ background: rgba(255, 255, 255, 0.07);
+ color: rgba(255, 255, 255, 0.4);
+ }
+ .mp-badge--expired {
+ background: rgba(251, 191, 36, 0.12);
+ color: #fbbf24;
+ }
.mp-chain-chip {
font-size: 0.618rem;
- background: rgba(255,255,255,0.07);
- color: rgba(255,255,255,0.5);
+ background: rgba(255, 255, 255, 0.07);
+ color: rgba(255, 255, 255, 0.5);
padding: 0.1rem 0.45rem;
border-radius: 999px;
}
@@ -586,14 +610,19 @@
text-decoration: none;
}
- .mp-addr-link:hover { color: rgba(255, 255, 255, 0.8); }
+ .mp-addr-link:hover {
+ color: rgba(255, 255, 255, 0.8);
+ }
.mp-addr-arrow {
font-size: 0.618rem;
color: rgba(255, 255, 255, 0.2);
}
- .mp-card-actions { display: flex; gap: 0.5rem; }
+ .mp-card-actions {
+ display: flex;
+ gap: 0.5rem;
+ }
.mp-revoke-btn {
background: rgba(239, 68, 68, 0.1);
@@ -627,27 +656,31 @@
align-items: center;
gap: 0.382rem;
font-size: 0.618rem;
- color: rgba(255,255,255,0.5);
+ color: rgba(255, 255, 255, 0.5);
margin-top: 0.382rem;
}
.mp-tx-link {
- color: rgba(255,255,255,0.4);
+ color: rgba(255, 255, 255, 0.4);
text-decoration: none;
}
- .mp-tx-link:hover { color: rgba(255,255,255,0.8); }
+ .mp-tx-link:hover {
+ color: rgba(255, 255, 255, 0.8);
+ }
@keyframes mp-spin {
- to { transform: rotate(360deg); }
+ to {
+ transform: rotate(360deg);
+ }
}
.mp-spinner {
display: inline-block;
width: 10px;
height: 10px;
- border: 1.5px solid rgba(255,255,255,0.15);
- border-top-color: rgba(255,255,255,0.6);
+ border: 1.5px solid rgba(255, 255, 255, 0.15);
+ border-top-color: rgba(255, 255, 255, 0.6);
border-radius: 50%;
animation: mp-spin 0.7s linear infinite;
}
diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.html
index e9985f065..1ae89bd0a 100644
--- a/public/dashboard/embed-policy.html
+++ b/public/dashboard/embed-policy.html
@@ -5,6 +5,11 @@
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Embed policy · 3D Agent</title>
<link rel="icon" href="/favicon.ico" />
+ <style>
+ body[data-auth-pending] {
+ visibility: hidden;
+ }
+ </style>
<style>
:root {
color-scheme: dark;
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index f3344ae7b..977148a1e 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -645,6 +645,8 @@
<script
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"
+ crossorigin="anonymous"
></script>
<script type="module" src="/session-client.js"></script>
</head>
diff --git a/public/lobehub/iframe/index.html b/public/lobehub/iframe/index.html
index 5a777d6de..0eb601e84 100644
--- a/public/lobehub/iframe/index.html
+++ b/public/lobehub/iframe/index.html
@@ -41,7 +41,11 @@
<script type="module">
const CDN = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';
const h = location.hostname;
- const isLocal = h === 'localhost' || h === '127.0.0.1' || h.endsWith('.github.dev') || h.endsWith('.local');
+ const isLocal =
+ h === 'localhost' ||
+ h === '127.0.0.1' ||
+ h.endsWith('.github.dev') ||
+ h.endsWith('.local');
if (isLocal) {
const { defineElement } = await import('/src/lib.js');
defineElement();
diff --git a/public/login.html b/public/login.html
index 738a98564..9cc993a5c 100644
--- a/public/login.html
+++ b/public/login.html
@@ -154,7 +154,8 @@
<script type="module" src="/wallet-login.js"></script>
<script>
const params = new URLSearchParams(location.search);
- const next = params.get('next') || sessionStorage.getItem('login_redirect') || '/create';
+ const next =
+ params.get('next') || sessionStorage.getItem('login_redirect') || '/create';
sessionStorage.removeItem('login_redirect');
// If already signed in, skip the login form entirely.
diff --git a/public/register.html b/public/register.html
index 6087aa1bb..423c65fab 100644
--- a/public/register.html
+++ b/public/register.html
@@ -150,7 +150,8 @@
</form>
<script>
const params = new URLSearchParams(location.search);
- const next = params.get('next') || sessionStorage.getItem('login_redirect') || '/create';
+ const next =
+ params.get('next') || sessionStorage.getItem('login_redirect') || '/create';
sessionStorage.removeItem('login_redirect');
const form = document.getElementById('f');
const err = document.getElementById('err');
diff --git a/public/skills/dca/SKILL.md b/public/skills/dca/SKILL.md
index fc93b0d4d..92af7692e 100644
--- a/public/skills/dca/SKILL.md
+++ b/public/skills/dca/SKILL.md
@@ -5,16 +5,16 @@ description: Dollar-cost average a fixed USDC amount into WETH on a recurring sc
trust: owned-only
permissions_required: true
default_scope_preset:
- token: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
- maxAmount: "100000000"
- period: "daily"
- targets:
- - "0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4"
- - "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
- selectors:
- - "0x04e45aaf"
- - "0x095ea7b3"
- expiry_days: 30
+ token: '0x036CbD53842c5426634e7929541eC2318f3dCF7e'
+ maxAmount: '100000000'
+ period: 'daily'
+ targets:
+ - '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4'
+ - '0x036CbD53842c5426634e7929541eC2318f3dCF7e'
+ selectors:
+ - '0x04e45aaf'
+ - '0x095ea7b3'
+ expiry_days: 30
---
# DCA (Dollar-Cost Averaging)
@@ -30,6 +30,7 @@ a fixed USDC amount into WETH using Uniswap V3 on Base Sepolia.
## Actions
Call `start_dca` when the owner wants to configure a new strategy. It will:
+
1. Prompt for amount (USDC), token out (default WETH), and frequency.
2. Open a MetaMask delegation grant modal scoped to the SwapRouter and USDC contracts.
3. Store the strategy once the delegation is signed.
diff --git a/public/skills/dca/skill.js b/public/skills/dca/skill.js
index f6c10090b..e1880205e 100644
--- a/public/skills/dca/skill.js
+++ b/public/skills/dca/skill.js
@@ -93,7 +93,8 @@ export async function execute({ agent, host, args = {} }) {
}
const cfg = CHAIN_CONFIG[chain_id];
- if (!cfg) return { ok: false, code: 'unsupported_chain', message: `Chain ${chain_id} not supported` };
+ if (!cfg)
+ return { ok: false, code: 'unsupported_chain', message: `Chain ${chain_id} not supported` };
const tokenOutAddress = cfg.tokens[token_out];
if (!tokenOutAddress) {
@@ -108,9 +109,7 @@ export async function execute({ agent, host, args = {} }) {
const slippage = Math.min(500, Math.max(10, Number(slippage_bps)));
// Convert USDC amount to 6-decimal wei
- const amountPerExecution = String(
- Math.round(parseFloat(amount_usdc) * 10 ** USDC_DECIMALS),
- );
+ const amountPerExecution = String(Math.round(parseFloat(amount_usdc) * 10 ** USDC_DECIMALS));
const periodSeconds = frequency === 'weekly' ? 7 * 86400 : 86400;
diff --git a/public/skills/subscription/SKILL.md b/public/skills/subscription/SKILL.md
index e6366d970..7b8028b48 100644
--- a/public/skills/subscription/SKILL.md
+++ b/public/skills/subscription/SKILL.md
@@ -4,11 +4,11 @@ version: 0.1.0
trust: owned-only
permissions_required: true
default_scope_preset:
- token: "<USDC>"
- maxAmount: "5000000"
- period: "weekly"
- targets: ["<subscription executor contract>"]
- expiry_days: 90
+ token: '<USDC>'
+ maxAmount: '5000000'
+ period: 'weekly'
+ targets: ['<subscription executor contract>']
+ expiry_days: 90
---
# Subscription
diff --git a/public/skills/subscription/skill.js b/public/skills/subscription/skill.js
index 5f29ca91e..2211fb4e8 100644
--- a/public/skills/subscription/skill.js
+++ b/public/skills/subscription/skill.js
@@ -75,7 +75,7 @@ export async function execute({ agent, host, args }) {
let delegation;
try {
- const { openGrantModal } = await import('../../src/permissions/grant-modal.js');
+ const { openGrantModal } = await import('/src/permissions/grant-modal.js');
delegation = await openGrantModal({ agent, scopePreset });
} catch {
host.speak('Permission request is not available in this context.');
diff --git a/public/skills/tip-jar/README.md b/public/skills/tip-jar/README.md
index bc81e18c7..3523a2e74 100644
--- a/public/skills/tip-jar/README.md
+++ b/public/skills/tip-jar/README.md
@@ -6,13 +6,13 @@ initial grant.
## Scope requested
-| Field | Value |
-| ----------- | -------------------------------------------------- |
-| token | USDC on the active chain (6 decimals) |
-| maxAmount | 10 000 000 base units (10 USDC) per day |
-| period | daily |
-| targets | USDC contract on the active chain |
-| expiry_days | 30 |
+| Field | Value |
+| ----------- | --------------------------------------- |
+| token | USDC on the active chain (6 decimals) |
+| maxAmount | 10 000 000 base units (10 USDC) per day |
+| period | daily |
+| targets | USDC contract on the active chain |
+| expiry_days | 30 |
Base Sepolia USDC: `0x036CbD53842c5426634e7929541eC2318f3dCF7e`
@@ -76,12 +76,12 @@ Example — 5 USDC to 0x1234...5678:
## Files
-| File | Purpose |
-| ------------ | ------------------------------------------ |
-| `SKILL.md` | LLM instructions + scope declaration |
+| File | Purpose |
+| --------------- | ------------------------------------------ |
+| `SKILL.md` | LLM instructions + scope declaration |
| `manifest.json` | Skill metadata, sandboxPolicy, permissions |
-| `skill.js` | `setup` / `execute` exports + pure helpers |
-| `skill.css` | Tip-amount picker modal styles |
+| `skill.js` | `setup` / `execute` exports + pure helpers |
+| `skill.css` | Tip-amount picker modal styles |
## Dependencies (lazy-loaded at runtime)
diff --git a/public/skills/tip-jar/SKILL.md b/public/skills/tip-jar/SKILL.md
index 7481a9a79..963692429 100644
--- a/public/skills/tip-jar/SKILL.md
+++ b/public/skills/tip-jar/SKILL.md
@@ -6,8 +6,8 @@ trust: owned-only
permissions_required: true
cost: medium
triggers:
- - tip_request
- - viewer_appreciation
+ - tip_request
+ - viewer_appreciation
default_scope_preset: '{"token":"chain-specific-usdc","maxAmount":"10000000","period":"daily","targets":["usdc-contract"],"expiry_days":30}'
---
@@ -24,13 +24,13 @@ On success, thank the viewer warmly.
## Scope requested
-| Field | Value |
-| ----------- | ----------------------------------------------- |
-| token | USDC on the active chain (6 decimals) |
-| maxAmount | 10 000 000 base units (10 USDC) per day |
-| period | daily |
-| targets | USDC contract address on the active chain |
-| expiry_days | 30 |
+| Field | Value |
+| ----------- | ----------------------------------------- |
+| token | USDC on the active chain (6 decimals) |
+| maxAmount | 10 000 000 base units (10 USDC) per day |
+| period | daily |
+| targets | USDC contract address on the active chain |
+| expiry_days | 30 |
## Error cases
diff --git a/public/skills/tip-jar/skill.css b/public/skills/tip-jar/skill.css
index f62add60a..ac3421520 100644
--- a/public/skills/tip-jar/skill.css
+++ b/public/skills/tip-jar/skill.css
@@ -44,7 +44,10 @@
color: #b0b8d8;
cursor: pointer;
font-size: 0.9rem;
- transition: background 0.15s, color 0.15s, border-color 0.15s;
+ transition:
+ background 0.15s,
+ color 0.15s,
+ border-color 0.15s;
}
.tip-jar-btn:hover {
diff --git a/public/skills/tip-jar/skill.js b/public/skills/tip-jar/skill.js
index 6bd03ac69..4d4be661e 100644
--- a/public/skills/tip-jar/skill.js
+++ b/public/skills/tip-jar/skill.js
@@ -18,7 +18,7 @@
/** USDC contract addresses indexed by EVM chainId. */
const USDC_BY_CHAIN = {
84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
- 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base mainnet
+ 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base mainnet
};
const TIP_OPTIONS = [1, 5, 10]; // USDC display amounts
@@ -45,11 +45,11 @@ const USDC_DECIMALS = 6;
*/
export function buildERC20Transfer(tokenAddr, recipient, amountBaseUnits) {
const addr = recipient.replace(/^0x/i, '').toLowerCase().padStart(64, '0');
- const amt = BigInt(amountBaseUnits).toString(16).padStart(64, '0');
+ const amt = BigInt(amountBaseUnits).toString(16).padStart(64, '0');
return {
- to: tokenAddr,
+ to: tokenAddr,
value: '0x0',
- data: '0xa9059cbb' + addr + amt,
+ data: '0xa9059cbb' + addr + amt,
};
}
@@ -63,9 +63,9 @@ export function buildERC20Transfer(tokenAddr, recipient, amountBaseUnits) {
*/
export async function setup({ agent, host }) {
host.attachAction({
- id: 'tip-jar:tip',
- label: 'Tip the creator',
- icon: '💝',
+ id: 'tip-jar:tip',
+ label: 'Tip the creator',
+ icon: '💝',
handler: () => execute({ agent, host, args: {} }),
});
}
@@ -76,7 +76,7 @@ export async function setup({ agent, host }) {
* @param {{ agent: Object, host: Object, args: Object }} ctx
*/
export async function execute({ agent, host, args: _args }) {
- const chainId = agent.chainId ?? 84532;
+ const chainId = agent.chainId ?? 84532;
const usdcAddr = USDC_BY_CHAIN[chainId];
if (!usdcAddr) {
@@ -103,16 +103,16 @@ export async function execute({ agent, host, args: _args }) {
// 3. Execute the delegated transfer
try {
const result = await redeemFromSkill({
- agentId: agent.id,
+ agentId: agent.id,
chainId,
- skillId: 'tip-jar',
- calls: [call],
- mode: 'auto',
+ skillId: 'tip-jar',
+ calls: [call],
+ mode: 'auto',
});
if (!result.ok) {
const err = new Error(result.error);
- err.code = result.error;
+ err.code = result.error;
throw err;
}
@@ -120,7 +120,6 @@ export async function execute({ agent, host, args: _args }) {
host.speak('Thank you for the tip!');
_emitTipReceived(agent, amount, result.txHash);
_notify(host, `Tip sent! Tx: ${result.txHash}`);
-
} catch (err) {
const code = err.code ?? err.message;
@@ -163,16 +162,16 @@ function _pickAmount() {
`;
document.body.appendChild(overlay);
- const sendBtn = overlay.querySelector('.tip-jar-send');
- const cancelBtn = overlay.querySelector('.tip-jar-cancel');
+ const sendBtn = overlay.querySelector('.tip-jar-send');
+ const cancelBtn = overlay.querySelector('.tip-jar-cancel');
const customInput = overlay.querySelector('.tip-jar-custom');
let selected = null;
const select = (val) => {
selected = val;
- overlay.querySelectorAll('.tip-jar-btn').forEach(
- (b) => b.classList.toggle('selected', Number(b.dataset.v) === val),
- );
+ overlay
+ .querySelectorAll('.tip-jar-btn')
+ .forEach((b) => b.classList.toggle('selected', Number(b.dataset.v) === val));
sendBtn.disabled = false;
};
@@ -186,7 +185,9 @@ function _pickAmount() {
customInput.addEventListener('input', () => {
const val = parseFloat(customInput.value);
if (val > 0 && val <= 10) {
- overlay.querySelectorAll('.tip-jar-btn').forEach((b) => b.classList.remove('selected'));
+ overlay
+ .querySelectorAll('.tip-jar-btn')
+ .forEach((b) => b.classList.remove('selected'));
select(val);
} else {
selected = null;
@@ -194,8 +195,11 @@ function _pickAmount() {
}
});
- const done = (val) => { document.body.removeChild(overlay); resolve(val); };
- sendBtn.addEventListener('click', () => done(selected));
+ const done = (val) => {
+ document.body.removeChild(overlay);
+ resolve(val);
+ };
+ sendBtn.addEventListener('click', () => done(selected));
cancelBtn.addEventListener('click', () => done(null));
});
}
@@ -223,19 +227,19 @@ async function _handleNoDelegation({ agent, host, chainId, usdcAddr }) {
}
host.attachAction({
- id: 'tip-jar:grant',
- label: 'Grant tipping',
- icon: '🔑',
+ id: 'tip-jar:grant',
+ label: 'Grant tipping',
+ icon: '🔑',
oneShot: true,
handler: () =>
openGrantModal({
agentId: agent.id,
chainId,
preset: {
- token: usdcAddr,
- maxAmount: '10000000',
- period: 'daily',
- targets: [usdcAddr],
+ token: usdcAddr,
+ maxAmount: '10000000',
+ period: 'daily',
+ targets: [usdcAddr],
expiry_days: 30,
},
}),
@@ -250,13 +254,15 @@ function _emitTipReceived(agent, amountUsdc, txHash) {
const bus = globalThis.__agentProtocol ?? globalThis.VIEWER?.agent_protocol;
if (bus) {
bus.emit({
- type: 'tip.received',
- payload: { agentId: agent.id, amountUsdc, txHash },
- agentId: agent.id,
+ type: 'tip.received',
+ payload: { agentId: agent.id, amountUsdc, txHash },
+ agentId: agent.id,
sourceSkill: 'tip-jar',
});
}
- } catch { /* protocol is optional */ }
+ } catch {
+ /* protocol is optional */
+ }
}
/** Surface a message via host.showMessage if available, otherwise log. */
diff --git a/public/wallet-connect-demo.html b/public/wallet-connect-demo.html
index ea3e2f7ff..392bbc1c7 100644
--- a/public/wallet-connect-demo.html
+++ b/public/wallet-connect-demo.html
@@ -6,9 +6,13 @@
<title>Wallet Connect — QA Demo</title>
<link rel="stylesheet" href="/wallet-connect.css" />
<style>
- :root { color-scheme: dark; }
+ :root {
+ color-scheme: dark;
+ }
body {
- font: 15px/1.5 system-ui, sans-serif;
+ font:
+ 15px/1.5 system-ui,
+ sans-serif;
background: #0b0b10;
color: #eee;
margin: 0;
@@ -20,7 +24,10 @@
gap: 32px;
padding: 32px;
}
- h1 { margin: 0; font-size: 20px; }
+ h1 {
+ margin: 0;
+ font-size: 20px;
+ }
.demo-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
@@ -37,7 +44,13 @@
flex-direction: column;
gap: 12px;
}
- .demo-card h2 { margin: 0; font-size: 14px; color: #aaa; text-transform: uppercase; letter-spacing: 0.06em; }
+ .demo-card h2 {
+ margin: 0;
+ font-size: 14px;
+ color: #aaa;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ }
.log {
font-size: 12px;
font-family: monospace;
@@ -49,7 +62,9 @@
</head>
<body>
<h1>Wallet Connect — QA Demo</h1>
- <p style="color:#666;margin:0;font-size:13px;">Manual test page — not linked from site nav.</p>
+ <p style="color: #666; margin: 0; font-size: 13px">
+ Manual test page — not linked from site nav.
+ </p>
<div class="demo-grid">
<div class="demo-card">
@@ -81,7 +96,7 @@
const ctrl = createConnectWalletButton(mountEl, opts);
ctrl.addEventListener('change', (e) => {
const { status, address, error } = e.detail;
- logEl.textContent = `State: ${status}${address ? ` · ${address.slice(0,6)}…${address.slice(-4)}` : ''}${error ? ` · ${error.message}` : ''}`;
+ logEl.textContent = `State: ${status}${address ? ` · ${address.slice(0, 6)}…${address.slice(-4)}` : ''}${error ? ` · ${error.message}` : ''}`;
});
return ctrl;
}
@@ -91,7 +106,7 @@
labels: { idle: 'Connect wallet', connected: null },
onSuccess: () => {
document.getElementById('log-signin').textContent = 'Success — redirecting…';
- setTimeout(() => location.href = next, 800);
+ setTimeout(() => (location.href = next), 800);
},
});
@@ -105,9 +120,14 @@
wire('mount-agent', 'log-agent', {
verifyUrl: '/api/auth/siwe/verify',
- labels: { idle: 'Connect for ERC-8004', signing: 'Sign to register…', success: 'Ready' },
+ labels: {
+ idle: 'Connect for ERC-8004',
+ signing: 'Sign to register…',
+ success: 'Ready',
+ },
onSuccess: () => {
- document.getElementById('log-agent').textContent = 'Connected — ready for on-chain registration.';
+ document.getElementById('log-agent').textContent =
+ 'Connected — ready for on-chain registration.';
},
});
</script>
diff --git a/public/wallet-connect.css b/public/wallet-connect.css
index 7787eb4ec..c33164ac9 100644
--- a/public/wallet-connect.css
+++ b/public/wallet-connect.css
@@ -15,7 +15,10 @@
background: #1c1c28;
color: #eee;
cursor: pointer;
- transition: background 0.15s, border-color 0.15s, opacity 0.15s;
+ transition:
+ background 0.15s,
+ border-color 0.15s,
+ opacity 0.15s;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@@ -32,43 +35,43 @@
}
/* State variants */
-.cwb-btn[data-state="connected"] {
+.cwb-btn[data-state='connected'] {
border-color: #2a5c2a;
background: #141c14;
color: #7ddf7d;
}
-.cwb-btn[data-state="wrong_chain"] {
+.cwb-btn[data-state='wrong_chain'] {
border-color: #7a5a00;
background: #1c1800;
color: #f0c040;
}
-.cwb-btn[data-state="error"] {
+.cwb-btn[data-state='error'] {
border-color: #5c2a2a;
background: #1c1414;
color: #df7d7d;
}
-.cwb-btn[data-state="success"] {
+.cwb-btn[data-state='success'] {
border-color: #2a5c2a;
background: #141c14;
color: #7ddf7d;
cursor: default;
}
-.cwb-btn[data-state="no_provider"] {
+.cwb-btn[data-state='no_provider'] {
border-color: #f6851b;
color: #f6851b;
}
-.cwb-btn[data-state="no_provider"]:hover {
+.cwb-btn[data-state='no_provider']:hover {
background: #1c1710;
border-color: #f6851b;
}
/* Async spinner — simple border animation */
-.cwb-btn[aria-busy="true"]::before {
+.cwb-btn[aria-busy='true']::before {
content: '';
display: inline-block;
width: 12px;
@@ -81,5 +84,7 @@
}
@keyframes cwb-spin {
- to { transform: rotate(360deg); }
+ to {
+ transform: rotate(360deg);
+ }
}
diff --git a/public/wallet/connect-button.js b/public/wallet/connect-button.js
index 7cb222b23..404b68075 100644
--- a/public/wallet/connect-button.js
+++ b/public/wallet/connect-button.js
@@ -59,7 +59,8 @@ export class ConnectWalletController extends EventTarget {
};
this.#s = initialState();
- this.#onAccountsChanged = (accounts) => this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });
+ this.#onAccountsChanged = (accounts) =>
+ this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });
this.#onChainChanged = (chainIdHex) => {
const chainId = parseInt(chainIdHex, 16);
this.#dispatch({ type: 'CHAIN_CHANGED', chainId });
@@ -76,10 +77,18 @@ export class ConnectWalletController extends EventTarget {
}
}
- get state() { return this.#s.status; }
- get address() { return this.#s.address; }
- get chainId() { return this.#s.chainId; }
- get error() { return this.#s.error; }
+ get state() {
+ return this.#s.status;
+ }
+ get address() {
+ return this.#s.address;
+ }
+ get chainId() {
+ return this.#s.chainId;
+ }
+ get error() {
+ return this.#s.error;
+ }
#dispatch(action) {
const next = reduce(this.#s, action);
@@ -125,10 +134,15 @@ export class ConnectWalletController extends EventTarget {
if (e?.code === 4902) {
this.#dispatch({
type: 'ERROR',
- error: new Error(`Chain ${CHAIN_NAMES[target] || target} not in wallet. Add it manually.`),
+ error: new Error(
+ `Chain ${CHAIN_NAMES[target] || target} not in wallet. Add it manually.`,
+ ),
});
} else if (e?.code !== 4001) {
- this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });
+ this.#dispatch({
+ type: 'ERROR',
+ error: e instanceof Error ? e : new Error(String(e)),
+ });
}
}
}
@@ -177,7 +191,9 @@ export class ConnectWalletController extends EventTarget {
}
}
- reset() { this.#dispatch({ type: 'RESET' }); }
+ reset() {
+ this.#dispatch({ type: 'RESET' });
+ }
dispose() {
if (window.ethereum) {
@@ -237,7 +253,10 @@ export function createConnectWalletButton(mountEl, opts = {}) {
} else if (status === STATES.WRONG_CHAIN) {
btn.onclick = () => ctrl.connect();
} else if (status === STATES.ERROR) {
- btn.onclick = () => { ctrl.reset(); ctrl.connect(); };
+ btn.onclick = () => {
+ ctrl.reset();
+ ctrl.connect();
+ };
} else if (status === STATES.IDLE) {
btn.onclick = () => ctrl.connect();
}
diff --git a/public/wallet/state.js b/public/wallet/state.js
index 63816be2c..4ee7a6049 100644
--- a/public/wallet/state.js
+++ b/public/wallet/state.js
@@ -28,13 +28,19 @@ export function reduce(state, action) {
case 'HAS_PROVIDER':
return { ...state, status: STATES.REQUESTING_ACCOUNTS };
case 'ACCOUNTS_RESOLVED':
- return { ...state, status: STATES.CONNECTED, address: action.address, chainId: action.chainId };
+ return {
+ ...state,
+ status: STATES.CONNECTED,
+ address: action.address,
+ chainId: action.chainId,
+ };
case 'WRONG_CHAIN':
return { ...state, status: STATES.WRONG_CHAIN };
case 'CHAIN_OK':
return { ...state, status: STATES.CONNECTED };
case 'SIGN':
- if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN) return state;
+ if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN)
+ return state;
return { ...state, status: STATES.SIGNING };
case 'SIGNATURE_OBTAINED':
return { ...state, status: STATES.VERIFYING };
@@ -46,7 +52,12 @@ export function reduce(state, action) {
return initialState();
case 'ACCOUNTS_CHANGED':
if (!action.accounts || action.accounts.length === 0) return initialState();
- return { ...state, address: action.accounts[0], chainId: state.chainId, status: STATES.CONNECTED };
+ return {
+ ...state,
+ address: action.accounts[0],
+ chainId: state.chainId,
+ status: STATES.CONNECTED,
+ };
case 'CHAIN_CHANGED':
return { ...state, chainId: action.chainId };
default:
diff --git a/scripts/apply-delegations-schema.js b/scripts/apply-delegations-schema.js
index 68775bab5..7ebf6b916 100644
--- a/scripts/apply-delegations-schema.js
+++ b/scripts/apply-delegations-schema.js
@@ -49,9 +49,7 @@ try {
await pool.query(schema);
console.log('✓ schema applied');
- const countResult = await pool.query(
- 'SELECT COUNT(*) AS count FROM agent_delegations'
- );
+ const countResult = await pool.query('SELECT COUNT(*) AS count FROM agent_delegations');
console.log(` agent_delegations row count: ${countResult.rows[0].count}`);
const indexResult = await pool.query(`
diff --git a/scripts/seed-agent.mjs b/scripts/seed-agent.mjs
index 00e0c6650..0706d5381 100644
--- a/scripts/seed-agent.mjs
+++ b/scripts/seed-agent.mjs
@@ -1,6 +1,8 @@
import { neon } from '@neondatabase/serverless';
-const sql = neon('postgresql://neondb_owner:npg_4nWXZhq2Hjse@ep-rapid-surf-ak9p7occ-pooler.c-3.us-west-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require');
+const sql = neon(
+ 'postgresql://neondb_owner:npg_4nWXZhq2Hjse@ep-rapid-surf-ak9p7occ-pooler.c-3.us-west-2.aws.neon.tech/neondb?channel_binding=require&sslmode=require',
+);
const [user] = await sql`
INSERT INTO users (email, display_name, email_verified)
diff --git a/scripts/smoke-permissions.js b/scripts/smoke-permissions.js
index 4df0740f3..b33680c99 100644
--- a/scripts/smoke-permissions.js
+++ b/scripts/smoke-permissions.js
@@ -42,27 +42,29 @@ import {
// ── Config ────────────────────────────────────────────────────────────────────
-const BASE_URL = process.env.SMOKE_BASE_URL?.replace(/\/$/, '');
-const AGENT_ID = process.env.SMOKE_AGENT_ID;
-const CHAIN_ID = Number(process.env.SMOKE_CHAIN_ID || 84532);
+const BASE_URL = process.env.SMOKE_BASE_URL?.replace(/\/$/, '');
+const AGENT_ID = process.env.SMOKE_AGENT_ID;
+const CHAIN_ID = Number(process.env.SMOKE_CHAIN_ID || 84532);
const DELEGATOR_KEY = process.env.SMOKE_DELEGATOR_KEY;
const SESSION_COOKIE = process.env.SMOKE_SESSION_COOKIE;
-const SKIP_REVOKE = process.env.SMOKE_SKIP_REVOKE === '1';
-const SKIP_DB = process.env.SMOKE_SKIP_DB === '1';
-const DATABASE_URL = process.env.DATABASE_URL;
+const SKIP_REVOKE = process.env.SMOKE_SKIP_REVOKE === '1';
+const SKIP_DB = process.env.SMOKE_SKIP_DB === '1';
+const DATABASE_URL = process.env.DATABASE_URL;
const RPC_URLS = {
- 1: 'https://ethereum-rpc.publicnode.com',
- 8453: 'https://mainnet.base.org',
+ 1: 'https://ethereum-rpc.publicnode.com',
+ 8453: 'https://mainnet.base.org',
11155111: 'https://ethereum-sepolia-rpc.publicnode.com',
- 84532: process.env.RPC_URL_84532 || 'https://sepolia.base.org',
- 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
+ 84532: process.env.RPC_URL_84532 || 'https://sepolia.base.org',
+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
11155420: 'https://sepolia.optimism.io',
};
// ── Result tracker ────────────────────────────────────────────────────────────
-let passed = 0, failed = 0, skipped = 0;
+let passed = 0,
+ failed = 0,
+ skipped = 0;
const failures = [];
function pass(label) {
@@ -112,12 +114,27 @@ function assertOk(res, body, label) {
section('1. Pre-flight');
-if (!BASE_URL) { console.error('\x1b[31mERROR: SMOKE_BASE_URL is required\x1b[0m\n'); process.exit(1); }
-if (!AGENT_ID) { console.error('\x1b[31mERROR: SMOKE_AGENT_ID is required\x1b[0m\n'); process.exit(1); }
-if (!DELEGATOR_KEY) { console.error('\x1b[31mERROR: SMOKE_DELEGATOR_KEY is required\x1b[0m\n'); process.exit(1); }
-if (!SESSION_COOKIE) { console.warn('\x1b[33mWARN: SMOKE_SESSION_COOKIE not set — authenticated tests will be skipped\x1b[0m'); }
+if (!BASE_URL) {
+ console.error('\x1b[31mERROR: SMOKE_BASE_URL is required\x1b[0m\n');
+ process.exit(1);
+}
+if (!AGENT_ID) {
+ console.error('\x1b[31mERROR: SMOKE_AGENT_ID is required\x1b[0m\n');
+ process.exit(1);
+}
+if (!DELEGATOR_KEY) {
+ console.error('\x1b[31mERROR: SMOKE_DELEGATOR_KEY is required\x1b[0m\n');
+ process.exit(1);
+}
+if (!SESSION_COOKIE) {
+ console.warn(
+ '\x1b[33mWARN: SMOKE_SESSION_COOKIE not set — authenticated tests will be skipped\x1b[0m',
+ );
+}
if (!(CHAIN_ID in DELEGATION_MANAGER_DEPLOYMENTS)) {
- console.error(`\x1b[31mERROR: CHAIN_ID ${CHAIN_ID} not in DELEGATION_MANAGER_DEPLOYMENTS\x1b[0m`);
+ console.error(
+ `\x1b[31mERROR: CHAIN_ID ${CHAIN_ID} not in DELEGATION_MANAGER_DEPLOYMENTS\x1b[0m`,
+ );
process.exit(1);
}
@@ -128,7 +145,7 @@ pass(`CHAIN_ID = ${CHAIN_ID}`);
// Create test wallet
const wallet = new Wallet(DELEGATOR_KEY);
const DELEGATOR_ADDRESS = wallet.address;
-const DELEGATE_ADDRESS = getAddress('0x70997970C51812dc3A010C7d01b50e0d17dc79C8'); // well-known test addr
+const DELEGATE_ADDRESS = getAddress('0x70997970C51812dc3A010C7d01b50e0d17dc79C8'); // well-known test addr
pass(`Delegator wallet = ${DELEGATOR_ADDRESS}`);
if (SKIP_DB || !DATABASE_URL) {
@@ -146,9 +163,21 @@ if (SKIP_DB || !DATABASE_URL) {
sql.end();
const cols = rows.map((r) => r.column_name);
const required = [
- 'id', 'agent_id', 'chain_id', 'delegator_address', 'delegate_address',
- 'delegation_hash', 'delegation_json', 'scope', 'status', 'expires_at',
- 'created_at', 'revoked_at', 'tx_hash_revoke', 'last_redeemed_at', 'redemption_count',
+ 'id',
+ 'agent_id',
+ 'chain_id',
+ 'delegator_address',
+ 'delegate_address',
+ 'delegation_hash',
+ 'delegation_json',
+ 'scope',
+ 'status',
+ 'expires_at',
+ 'created_at',
+ 'revoked_at',
+ 'tx_hash_revoke',
+ 'last_redeemed_at',
+ 'redemption_count',
];
const missing = required.filter((c) => !cols.includes(c));
assert.deepStrictEqual(missing, [], `Missing columns: ${missing.join(', ')}`);
@@ -169,12 +198,20 @@ section('2. Contract addresses (eth_getCode)');
const rpcUrl = RPC_URLS[CHAIN_ID];
for (const [chainId, addr] of Object.entries(DELEGATION_MANAGER_DEPLOYMENTS)) {
const url = RPC_URLS[chainId];
- if (!url) { skip(`chainId ${chainId}`, 'no RPC URL'); continue; }
- await check(`DelegationManager on chain ${chainId} (${addr.slice(0,10)}…)`, async () => {
+ if (!url) {
+ skip(`chainId ${chainId}`, 'no RPC URL');
+ continue;
+ }
+ await check(`DelegationManager on chain ${chainId} (${addr.slice(0, 10)}…)`, async () => {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getCode', params: [addr, 'latest'] }),
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'eth_getCode',
+ params: [addr, 'latest'],
+ }),
});
const { result } = await res.json();
assert.ok(result && result.length > 4, `No bytecode at ${addr} on chain ${chainId}`);
@@ -194,42 +231,68 @@ await check('encodeScopedDelegation — valid input', () => {
const caveats = [
{
enforcer: CAVEAT_ENFORCERS.AllowedTargetsEnforcer[CHAIN_ID],
- terms: '0x' + DELEGATE_ADDRESS.slice(2).toLowerCase().padStart(64, '0'),
- args: '0x',
+ terms: '0x' + DELEGATE_ADDRESS.slice(2).toLowerCase().padStart(64, '0'),
+ args: '0x',
},
{
- enforcer: CAVEAT_ENFORCERS.ERC20PeriodTransferEnforcer?.[CHAIN_ID] ||
- CAVEAT_ENFORCERS.ERC20TransferAmountEnforcer[CHAIN_ID],
- terms: AbiCoder.defaultAbiCoder().encode(['address', 'uint256'], [USDC_BASE_SEPOLIA, 10_000_000n]),
- args: '0x',
+ enforcer:
+ CAVEAT_ENFORCERS.ERC20PeriodTransferEnforcer?.[CHAIN_ID] ||
+ CAVEAT_ENFORCERS.ERC20TransferAmountEnforcer[CHAIN_ID],
+ terms: AbiCoder.defaultAbiCoder().encode(
+ ['address', 'uint256'],
+ [USDC_BASE_SEPOLIA, 10_000_000n],
+ ),
+ args: '0x',
},
];
delegation = encodeScopedDelegation({
delegator: DELEGATOR_ADDRESS,
- delegate: DELEGATE_ADDRESS,
+ delegate: DELEGATE_ADDRESS,
caveats,
- expiry: EXPIRY,
- chainId: CHAIN_ID,
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
});
- assert.strictEqual(delegation.delegate, DELEGATE_ADDRESS);
- assert.strictEqual(delegation.delegator, DELEGATOR_ADDRESS);
+ assert.strictEqual(delegation.delegate, DELEGATE_ADDRESS);
+ assert.strictEqual(delegation.delegator, DELEGATOR_ADDRESS);
assert.ok(delegation.caveats.length >= 1);
});
await check('encodeScopedDelegation — delegate === delegator throws', () => {
assert.throws(
- () => encodeScopedDelegation({ delegator: DELEGATOR_ADDRESS, delegate: DELEGATOR_ADDRESS,
- caveats: [{ enforcer: '0x1234567890123456789012345678901234567890', terms: '0x', args: '0x' }],
- expiry: EXPIRY, chainId: CHAIN_ID }),
+ () =>
+ encodeScopedDelegation({
+ delegator: DELEGATOR_ADDRESS,
+ delegate: DELEGATOR_ADDRESS,
+ caveats: [
+ {
+ enforcer: '0x1234567890123456789012345678901234567890',
+ terms: '0x',
+ args: '0x',
+ },
+ ],
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
+ }),
(e) => e instanceof PermissionError,
);
});
await check('encodeScopedDelegation — unsupported chain throws', () => {
assert.throws(
- () => encodeScopedDelegation({ delegator: DELEGATOR_ADDRESS, delegate: DELEGATE_ADDRESS,
- caveats: [{ enforcer: '0x1234567890123456789012345678901234567890', terms: '0x', args: '0x' }],
- expiry: EXPIRY, chainId: 999999 }),
+ () =>
+ encodeScopedDelegation({
+ delegator: DELEGATOR_ADDRESS,
+ delegate: DELEGATE_ADDRESS,
+ caveats: [
+ {
+ enforcer: '0x1234567890123456789012345678901234567890',
+ terms: '0x',
+ args: '0x',
+ },
+ ],
+ expiry: EXPIRY,
+ chainId: 999999,
+ }),
(e) => e instanceof PermissionError && e.code === 'chain_not_supported',
);
});
@@ -255,13 +318,16 @@ await check('signDelegation — produces valid signature', async () => {
await check('delegationToManifestEntry — correct shape', () => {
assert.ok(signedDelegation, 'signDelegation must have passed');
const scope = {
- token: USDC_BASE_SEPOLIA, maxAmount: '10000000', period: 'daily',
- targets: [DELEGATE_ADDRESS], expiry: EXPIRY,
+ token: USDC_BASE_SEPOLIA,
+ maxAmount: '10000000',
+ period: 'daily',
+ targets: [DELEGATE_ADDRESS],
+ expiry: EXPIRY,
};
const entry = delegationToManifestEntry({ ...signedDelegation, scope });
- assert.strictEqual(entry.chainId, CHAIN_ID);
+ assert.strictEqual(entry.chainId, CHAIN_ID);
assert.strictEqual(entry.delegator, DELEGATOR_ADDRESS);
- assert.strictEqual(entry.hash, signedDelegation.hash);
+ assert.strictEqual(entry.hash, signedDelegation.hash);
assert.ok(!('signature' in entry), 'signature must NOT appear in manifest entry');
assert.strictEqual(entry.scope.token, USDC_BASE_SEPOLIA);
});
@@ -300,7 +366,7 @@ await check('GET /api/permissions/verify — missing params returns 400', async
});
await check('GET /api/permissions/verify — invalid chainId returns 400', async () => {
- const hash = signedDelegation?.hash || ('0x' + 'ab'.repeat(32));
+ const hash = signedDelegation?.hash || '0x' + 'ab'.repeat(32);
const res = await api(`/api/permissions/verify?hash=${hash}&chainId=999999`);
assert.ok(res.status === 400 || res.status === 200);
if (res.status === 200) {
@@ -316,14 +382,17 @@ section('6. API — authenticated endpoints');
let grantedId, grantedHash;
if (!SESSION_COOKIE) {
- skip('POST /api/permissions/grant', 'no SMOKE_SESSION_COOKIE');
- skip('GET /api/permissions/list', 'no SMOKE_SESSION_COOKIE');
- skip('GET /api/permissions/verify (live)', 'no SMOKE_SESSION_COOKIE');
- skip('POST /api/permissions/revoke', 'no SMOKE_SESSION_COOKIE');
+ skip('POST /api/permissions/grant', 'no SMOKE_SESSION_COOKIE');
+ skip('GET /api/permissions/list', 'no SMOKE_SESSION_COOKIE');
+ skip('GET /api/permissions/verify (live)', 'no SMOKE_SESSION_COOKIE');
+ skip('POST /api/permissions/revoke', 'no SMOKE_SESSION_COOKIE');
} else {
const scope = {
- token: USDC_BASE_SEPOLIA, maxAmount: '10000000', period: 'daily',
- targets: [DELEGATE_ADDRESS], expiry: EXPIRY,
+ token: USDC_BASE_SEPOLIA,
+ maxAmount: '10000000',
+ period: 'daily',
+ targets: [DELEGATE_ADDRESS],
+ expiry: EXPIRY,
};
await check('POST /api/permissions/grant — happy path', async () => {
@@ -331,17 +400,17 @@ if (!SESSION_COOKIE) {
const res = await api('/api/permissions/grant', {
method: 'POST',
body: JSON.stringify({
- agentId: AGENT_ID,
- chainId: CHAIN_ID,
+ agentId: AGENT_ID,
+ chainId: CHAIN_ID,
delegation: signedDelegation,
scope,
}),
});
const body = await res.json();
assertOk(res, body, 'grant');
- assert.ok(body.id, 'id must be present');
- assert.ok(body.delegationHash, 'delegationHash must be present');
- grantedId = body.id;
+ assert.ok(body.id, 'id must be present');
+ assert.ok(body.delegationHash, 'delegationHash must be present');
+ grantedId = body.id;
grantedHash = body.delegationHash;
console.log(` id: ${grantedId}`);
console.log(` hash: ${grantedHash}`);
@@ -351,7 +420,12 @@ if (!SESSION_COOKIE) {
assert.ok(signedDelegation, 'need signed delegation');
const res = await api('/api/permissions/grant', {
method: 'POST',
- body: JSON.stringify({ agentId: AGENT_ID, chainId: CHAIN_ID, delegation: signedDelegation, scope }),
+ body: JSON.stringify({
+ agentId: AGENT_ID,
+ chainId: CHAIN_ID,
+ delegation: signedDelegation,
+ scope,
+ }),
});
assert.strictEqual(res.status, 409);
const body = await res.json();
@@ -366,8 +440,10 @@ if (!SESSION_COOKIE) {
const found = body.delegations.find((d) => d.delegationHash === grantedHash);
assert.ok(found, `Delegation ${grantedHash} not found in list`);
assert.strictEqual(found.status, 'active');
- assert.ok(!('delegationJson' in found) || typeof found.delegationJson === 'object',
- 'signature should only be in authenticated view');
+ assert.ok(
+ !('delegationJson' in found) || typeof found.delegationJson === 'object',
+ 'signature should only be in authenticated view',
+ );
console.log(` listed ${body.delegations.length} delegation(s)`);
});
@@ -386,54 +462,68 @@ if (!SESSION_COOKIE) {
if (SKIP_REVOKE) {
skip('POST /api/permissions/revoke — on-chain', 'SMOKE_SKIP_REVOKE=1');
} else {
- await check('POST /api/permissions/revoke — on-chain disableDelegation + server mirror', async () => {
- assert.ok(grantedId && grantedHash && signedDelegation, 'grant must have passed');
-
- // Submit the on-chain disableDelegation tx
- const provider = new JsonRpcProvider(rpcUrl);
- const signer = wallet.connect(provider);
- const balance = await provider.getBalance(DELEGATOR_ADDRESS);
- assert.ok(balance > 0n, `Delegator ${DELEGATOR_ADDRESS} has no ETH on chain ${CHAIN_ID} — fund it first`);
-
- const { Contract } = await import('ethers');
- const dm = new Contract(DELEGATION_MANAGER_DEPLOYMENTS[CHAIN_ID], DELEGATION_MANAGER_ABI, signer);
-
- // Build the delegation tuple the contract expects
- const delegationTuple = {
- delegate: signedDelegation.delegate,
- delegator: signedDelegation.delegator,
- authority: signedDelegation.authority,
- caveats: signedDelegation.caveats,
- salt: signedDelegation.salt,
- signature: signedDelegation.signature,
- };
-
- console.log(' submitting disableDelegation tx…');
- const tx = await dm.disableDelegation(delegationTuple);
- const receipt = await tx.wait();
- assert.ok(receipt.status === 1, `tx reverted: ${receipt.hash}`);
- console.log(` tx: ${receipt.hash}`);
- console.log(` block: ${receipt.blockNumber}`);
-
- // Mirror revocation to the server
- const res = await api('/api/permissions/revoke', {
- method: 'POST',
- body: JSON.stringify({ id: grantedId, txHash: receipt.hash }),
- });
- const body = await res.json();
- assertOk(res, body, 'revoke');
- assert.strictEqual(body.status, 'revoked');
-
- // Confirm verify endpoint now returns invalid
- const vRes = await api(`/api/permissions/verify?hash=${grantedHash}&chainId=${CHAIN_ID}`);
- const vBody = await vRes.json();
- if (vBody.valid !== false) {
- console.log(' \x1b[33mWARN: verify still shows valid — indexer may not have run yet\x1b[0m');
- } else {
- assert.strictEqual(vBody.reason, 'delegation_revoked');
- console.log(' verify correctly shows delegation_revoked');
- }
- });
+ await check(
+ 'POST /api/permissions/revoke — on-chain disableDelegation + server mirror',
+ async () => {
+ assert.ok(grantedId && grantedHash && signedDelegation, 'grant must have passed');
+
+ // Submit the on-chain disableDelegation tx
+ const provider = new JsonRpcProvider(rpcUrl);
+ const signer = wallet.connect(provider);
+ const balance = await provider.getBalance(DELEGATOR_ADDRESS);
+ assert.ok(
+ balance > 0n,
+ `Delegator ${DELEGATOR_ADDRESS} has no ETH on chain ${CHAIN_ID} — fund it first`,
+ );
+
+ const { Contract } = await import('ethers');
+ const dm = new Contract(
+ DELEGATION_MANAGER_DEPLOYMENTS[CHAIN_ID],
+ DELEGATION_MANAGER_ABI,
+ signer,
+ );
+
+ // Build the delegation tuple the contract expects
+ const delegationTuple = {
+ delegate: signedDelegation.delegate,
+ delegator: signedDelegation.delegator,
+ authority: signedDelegation.authority,
+ caveats: signedDelegation.caveats,
+ salt: signedDelegation.salt,
+ signature: signedDelegation.signature,
+ };
+
+ console.log(' submitting disableDelegation tx…');
+ const tx = await dm.disableDelegation(delegationTuple);
+ const receipt = await tx.wait();
+ assert.ok(receipt.status === 1, `tx reverted: ${receipt.hash}`);
+ console.log(` tx: ${receipt.hash}`);
+ console.log(` block: ${receipt.blockNumber}`);
+
+ // Mirror revocation to the server
+ const res = await api('/api/permissions/revoke', {
+ method: 'POST',
+ body: JSON.stringify({ id: grantedId, txHash: receipt.hash }),
+ });
+ const body = await res.json();
+ assertOk(res, body, 'revoke');
+ assert.strictEqual(body.status, 'revoked');
+
+ // Confirm verify endpoint now returns invalid
+ const vRes = await api(
+ `/api/permissions/verify?hash=${grantedHash}&chainId=${CHAIN_ID}`,
+ );
+ const vBody = await vRes.json();
+ if (vBody.valid !== false) {
+ console.log(
+ ' \x1b[33mWARN: verify still shows valid — indexer may not have run yet\x1b[0m',
+ );
+ } else {
+ assert.strictEqual(vBody.reason, 'delegation_revoked');
+ console.log(' verify correctly shows delegation_revoked');
+ }
+ },
+ );
}
// ── 7. API — negative cases ──────────────────────────────────────────────
@@ -444,7 +534,12 @@ if (!SESSION_COOKIE) {
const res = await fetch(`${BASE_URL}/api/permissions/grant`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ agentId: AGENT_ID, chainId: CHAIN_ID, delegation: {}, scope: {} }),
+ body: JSON.stringify({
+ agentId: AGENT_ID,
+ chainId: CHAIN_ID,
+ delegation: {},
+ scope: {},
+ }),
});
assert.strictEqual(res.status, 401);
});
@@ -452,7 +547,10 @@ if (!SESSION_COOKIE) {
await check('POST /api/permissions/revoke — wrong id returns 404', async () => {
const res = await api('/api/permissions/revoke', {
method: 'POST',
- body: JSON.stringify({ id: '00000000-0000-0000-0000-000000000000', txHash: '0x' + '00'.repeat(32) }),
+ body: JSON.stringify({
+ id: '00000000-0000-0000-0000-000000000000',
+ txHash: '0x' + '00'.repeat(32),
+ }),
});
assert.ok(res.status === 404 || res.status === 400);
});
@@ -461,7 +559,9 @@ if (!SESSION_COOKIE) {
// ── Summary ───────────────────────────────────────────────────────────────────
console.log('\n' + '─'.repeat(60));
-console.log(`\x1b[1mResults:\x1b[0m \x1b[32m${passed} passed\x1b[0m \x1b[31m${failed} failed\x1b[0m \x1b[33m${skipped} skipped\x1b[0m`);
+console.log(
+ `\x1b[1mResults:\x1b[0m \x1b[32m${passed} passed\x1b[0m \x1b[31m${failed} failed\x1b[0m \x1b[33m${skipped} skipped\x1b[0m`,
+);
if (failures.length) {
console.log('\nFailed checks:');
@@ -473,7 +573,9 @@ if (failures.length) {
}
if (!SESSION_COOKIE) {
- console.log('\n\x1b[33mTIP:\x1b[0m Set SMOKE_SESSION_COOKIE to run authenticated grant/list/revoke tests.');
+ console.log(
+ '\n\x1b[33mTIP:\x1b[0m Set SMOKE_SESSION_COOKIE to run authenticated grant/list/revoke tests.',
+ );
}
console.log('\nAll checks passed.');
diff --git a/scripts/test-toolkit.js b/scripts/test-toolkit.js
index 89aafba2b..2f1851f32 100644
--- a/scripts/test-toolkit.js
+++ b/scripts/test-toolkit.js
@@ -11,78 +11,119 @@ import {
PermissionError,
} from '../src/permissions/toolkit.js';
-const CHAIN_ID = 84532; // Base Sepolia
+const CHAIN_ID = 84532; // Base Sepolia
const DELEGATOR = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266'; // EIP-55 checksummed
-const DELEGATE = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8';
-const EXPIRY = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
+const DELEGATE = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8';
+const EXPIRY = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
// CAVEAT_ENFORCERS is keyed enforcer → { chainId → address }
const caveats = [
{
enforcer: CAVEAT_ENFORCERS.AllowedTargetsEnforcer[CHAIN_ID],
- terms: '0x000000000000000000000000' + DELEGATE.slice(2).toLowerCase(),
- args: '0x',
+ terms: '0x000000000000000000000000' + DELEGATE.slice(2).toLowerCase(),
+ args: '0x',
},
];
// ─── encodeScopedDelegation: happy path ──────────────────────────────────────
-const delegation = encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats, expiry: EXPIRY, chainId: CHAIN_ID });
+const delegation = encodeScopedDelegation({
+ delegator: DELEGATOR,
+ delegate: DELEGATE,
+ caveats,
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
+});
-assert.strictEqual(delegation.delegate, DELEGATE, 'delegate address');
+assert.strictEqual(delegation.delegate, DELEGATE, 'delegate address');
assert.strictEqual(delegation.delegator, DELEGATOR, 'delegator address');
assert.strictEqual(
delegation.authority,
'0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'ROOT_AUTHORITY',
);
-assert.strictEqual(typeof delegation.salt, 'bigint', 'salt is bigint');
-assert.strictEqual(delegation.caveats.length, 1, 'one caveat');
-assert.strictEqual(delegation.caveats[0].args, '0x', 'args default');
-assert.strictEqual(delegation.chainId, CHAIN_ID, 'chainId');
+assert.strictEqual(typeof delegation.salt, 'bigint', 'salt is bigint');
+assert.strictEqual(delegation.caveats.length, 1, 'one caveat');
+assert.strictEqual(delegation.caveats[0].args, '0x', 'args default');
+assert.strictEqual(delegation.chainId, CHAIN_ID, 'chainId');
console.log('✓ encodeScopedDelegation — happy path');
// ─── encodeScopedDelegation: non-checksummed input is accepted + checksummed ─
const lower = encodeScopedDelegation({
delegator: DELEGATOR.toLowerCase(),
- delegate: DELEGATE.toLowerCase(),
+ delegate: DELEGATE.toLowerCase(),
caveats,
- expiry: EXPIRY,
- chainId: CHAIN_ID,
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
});
assert.strictEqual(lower.delegator, DELEGATOR, 'delegator auto-checksummed');
-assert.strictEqual(lower.delegate, DELEGATE, 'delegate auto-checksummed');
+assert.strictEqual(lower.delegate, DELEGATE, 'delegate auto-checksummed');
console.log('✓ encodeScopedDelegation — address checksumming');
// ─── encodeScopedDelegation: error cases ─────────────────────────────────────
assert.throws(
- () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATOR, caveats, expiry: EXPIRY, chainId: CHAIN_ID }),
+ () =>
+ encodeScopedDelegation({
+ delegator: DELEGATOR,
+ delegate: DELEGATOR,
+ caveats,
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
+ }),
(e) => e instanceof PermissionError && e.code === 'signature_invalid',
'delegate === delegator must throw signature_invalid',
);
assert.throws(
- () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats: [], expiry: EXPIRY, chainId: CHAIN_ID }),
+ () =>
+ encodeScopedDelegation({
+ delegator: DELEGATOR,
+ delegate: DELEGATE,
+ caveats: [],
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
+ }),
(e) => e instanceof PermissionError,
'empty caveats must throw',
);
assert.throws(
- () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats, expiry: Math.floor(Date.now() / 1000) + 30, chainId: CHAIN_ID }),
+ () =>
+ encodeScopedDelegation({
+ delegator: DELEGATOR,
+ delegate: DELEGATE,
+ caveats,
+ expiry: Math.floor(Date.now() / 1000) + 30,
+ chainId: CHAIN_ID,
+ }),
(e) => e instanceof PermissionError && e.code === 'delegation_expired',
'near-future expiry must throw delegation_expired',
);
assert.throws(
- () => encodeScopedDelegation({ delegator: DELEGATOR, delegate: DELEGATE, caveats, expiry: EXPIRY, chainId: 999999 }),
+ () =>
+ encodeScopedDelegation({
+ delegator: DELEGATOR,
+ delegate: DELEGATE,
+ caveats,
+ expiry: EXPIRY,
+ chainId: 999999,
+ }),
(e) => e instanceof PermissionError && e.code === 'chain_not_supported',
'unsupported chain (999999) must throw chain_not_supported',
);
assert.throws(
- () => encodeScopedDelegation({ delegator: 'not-an-address', delegate: DELEGATE, caveats, expiry: EXPIRY, chainId: CHAIN_ID }),
+ () =>
+ encodeScopedDelegation({
+ delegator: 'not-an-address',
+ delegate: DELEGATE,
+ caveats,
+ expiry: EXPIRY,
+ chainId: CHAIN_ID,
+ }),
(e) => e instanceof PermissionError && e.code === 'signature_invalid',
'invalid address must throw signature_invalid',
);
@@ -93,28 +134,28 @@ console.log('✓ encodeScopedDelegation — error cases');
const signed = {
...delegation,
signature: '0x' + 'ab'.repeat(65),
- hash: '0x' + 'cd'.repeat(32),
- uri: 'ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
+ hash: '0x' + 'cd'.repeat(32),
+ uri: 'ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi',
scope: {
- token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
+ token: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
maxAmount: '1000000',
- period: 'daily',
- targets: [DELEGATE],
- expiry: EXPIRY,
+ period: 'daily',
+ targets: [DELEGATE],
+ expiry: EXPIRY,
},
};
const entry = delegationToManifestEntry(signed);
-assert.strictEqual(entry.chainId, CHAIN_ID, 'entry.chainId');
-assert.strictEqual(entry.delegator, DELEGATOR, 'entry.delegator');
-assert.strictEqual(entry.delegate, DELEGATE, 'entry.delegate');
-assert.strictEqual(entry.hash, signed.hash, 'entry.hash');
-assert.strictEqual(entry.uri, signed.uri, 'entry.uri');
-assert.strictEqual(entry.scope.token, signed.scope.token, 'entry.scope.token');
-assert.strictEqual(entry.scope.maxAmount, '1000000', 'entry.scope.maxAmount');
-assert.strictEqual(entry.scope.period, 'daily', 'entry.scope.period');
-assert.deepStrictEqual(entry.scope.targets, [DELEGATE], 'entry.scope.targets');
-assert.strictEqual(entry.scope.expiry, EXPIRY, 'entry.scope.expiry');
+assert.strictEqual(entry.chainId, CHAIN_ID, 'entry.chainId');
+assert.strictEqual(entry.delegator, DELEGATOR, 'entry.delegator');
+assert.strictEqual(entry.delegate, DELEGATE, 'entry.delegate');
+assert.strictEqual(entry.hash, signed.hash, 'entry.hash');
+assert.strictEqual(entry.uri, signed.uri, 'entry.uri');
+assert.strictEqual(entry.scope.token, signed.scope.token, 'entry.scope.token');
+assert.strictEqual(entry.scope.maxAmount, '1000000', 'entry.scope.maxAmount');
+assert.strictEqual(entry.scope.period, 'daily', 'entry.scope.period');
+assert.deepStrictEqual(entry.scope.targets, [DELEGATE], 'entry.scope.targets');
+assert.strictEqual(entry.scope.expiry, EXPIRY, 'entry.scope.expiry');
// signature must NOT be in the manifest entry
assert.strictEqual('signature' in entry, false, 'signature must not appear in manifest entry');
console.log('✓ delegationToManifestEntry — with scope');
@@ -122,20 +163,20 @@ console.log('✓ delegationToManifestEntry — with scope');
// ─── delegationToManifestEntry: without scope (defaults) ─────────────────────
const noScope = delegationToManifestEntry({ ...signed, scope: undefined, uri: undefined });
-assert.ok(noScope.scope, 'default scope present');
+assert.ok(noScope.scope, 'default scope present');
assert.strictEqual(noScope.scope.token, 'native', 'default token = native');
-assert.strictEqual(noScope.scope.period, 'once', 'default period = once');
-assert.strictEqual('uri' in noScope, false, 'no uri when not provided');
+assert.strictEqual(noScope.scope.period, 'once', 'default period = once');
+assert.strictEqual('uri' in noScope, false, 'no uri when not provided');
console.log('✓ delegationToManifestEntry — defaults');
// ─── PermissionError shape ────────────────────────────────────────────────────
const err = new PermissionError('delegation_revoked', 'test revoke');
-assert.ok(err instanceof Error, 'is Error');
+assert.ok(err instanceof Error, 'is Error');
assert.ok(err instanceof PermissionError, 'is PermissionError');
-assert.strictEqual(err.code, 'delegation_revoked', 'err.code');
-assert.strictEqual(err.name, 'PermissionError', 'err.name');
-assert.strictEqual(err.message, 'test revoke', 'err.message');
+assert.strictEqual(err.code, 'delegation_revoked', 'err.code');
+assert.strictEqual(err.name, 'PermissionError', 'err.name');
+assert.strictEqual(err.message, 'test revoke', 'err.message');
console.log('✓ PermissionError shape');
console.log('\nAll tests passed.');
diff --git a/sdk/README.md b/sdk/README.md
index 4c89ef16e..403ad6dc9 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -127,11 +127,17 @@ const { spec, delegations } = await client.getMetadata(agentId);
// Grant a new delegation (browser only — needs MetaMask)
const { id, delegationHash } = await client.grant({
- agentId,
- chainId: 84532,
- preset: { token: 'native', maxAmount: '1000000', period: 'daily', targets: ['0xTarget'], expiryDays: 30 },
- delegate: agentSmartAccountAddress,
- signer, // ethers v6 Signer from connectWallet()
+ agentId,
+ chainId: 84532,
+ preset: {
+ token: 'native',
+ maxAmount: '1000000',
+ period: 'daily',
+ targets: ['0xTarget'],
+ expiryDays: 30,
+ },
+ delegate: agentSmartAccountAddress,
+ signer, // ethers v6 Signer from connectWallet()
});
// Verify on-chain that a delegation is still active
@@ -144,7 +150,10 @@ await client.revoke({ id, delegationHash, signer });
For advanced use (direct toolkit access with tree-shaking):
```ts
-import { encodeScopedDelegation, isDelegationValid } from '@nirholas/agent-kit/permissions/advanced';
+import {
+ encodeScopedDelegation,
+ isDelegationValid,
+} from '@nirholas/agent-kit/permissions/advanced';
```
## License
diff --git a/sdk/src/permissions.js b/sdk/src/permissions.js
index 7c4bda4e6..48d2abe1a 100644
--- a/sdk/src/permissions.js
+++ b/sdk/src/permissions.js
@@ -139,7 +139,9 @@ export class PermissionsClient {
const caveats = [
{
enforcer: CAVEAT_ENFORCERS.AllowedTargetsEnforcer[chainId],
- terms: encodeCaveats(preset.targets.map((t) => ({ enforcer: t, terms: '0x', args: '0x' }))),
+ terms: encodeCaveats(
+ preset.targets.map((t) => ({ enforcer: t, terms: '0x', args: '0x' })),
+ ),
args: '0x',
},
{
@@ -154,7 +156,13 @@ export class PermissionsClient {
},
];
- const unsigned = encodeScopedDelegation({ delegator: delegatorAddr, delegate, caveats, expiry, chainId });
+ const unsigned = encodeScopedDelegation({
+ delegator: delegatorAddr,
+ delegate,
+ caveats,
+ expiry,
+ chainId,
+ });
const signed = await signDelegation(unsigned, signer);
const data = await this._request(`${this._base}/api/permissions/grant`, {
@@ -220,7 +228,10 @@ export class PermissionsClient {
const network = await signer.provider.getNetwork();
const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[Number(network.chainId)];
if (!managerAddr) {
- throw new PermissionError('chain_not_supported', `no DelegationManager for chain ${network.chainId}`);
+ throw new PermissionError(
+ 'chain_not_supported',
+ `no DelegationManager for chain ${network.chainId}`,
+ );
}
const dm = new Contract(managerAddr, DELEGATION_MANAGER_ABI, signer);
const tx = await dm.disableDelegation(delegationHash);
@@ -243,6 +254,8 @@ export class PermissionsClient {
async verify(hash, chainId) {
const url = `${this._base}/api/permissions/verify?hash=${encodeURIComponent(hash)}&chainId=${chainId}`;
const data = await this._request(url);
- return data.reason !== undefined ? { valid: data.valid, reason: data.reason } : { valid: data.valid };
+ return data.reason !== undefined
+ ? { valid: data.valid, reason: data.reason }
+ : { valid: data.valid };
}
}
diff --git a/sdk/test/permissions.test.js b/sdk/test/permissions.test.js
index 11b787581..4d4f9d4f4 100644
--- a/sdk/test/permissions.test.js
+++ b/sdk/test/permissions.test.js
@@ -195,12 +195,19 @@ test('revoke — throws browser_only PermissionError in Node.js', async () => {
// ---------------------------------------------------------------------------
test('server 4xx ok:false → PermissionError with server error code', async () => {
- mockFetch({ ok: false, error: 'delegation_not_found', message: 'No delegation found for that id' });
+ mockFetch({
+ ok: false,
+ error: 'delegation_not_found',
+ message: 'No delegation found for that id',
+ });
const client = new PermissionsClient({ baseUrl: 'https://example.com' });
await assert.rejects(
() => client.getMetadata('bad-agent'),
(err) => {
- assert.ok(err instanceof PermissionError, `expected PermissionError, got ${err.constructor.name}`);
+ assert.ok(
+ err instanceof PermissionError,
+ `expected PermissionError, got ${err.constructor.name}`,
+ );
assert.equal(err.code, 'delegation_not_found');
assert.equal(err.message, 'No delegation found for that id');
return true;
diff --git a/specs/schema/README.md b/specs/schema/README.md
index 13f010874..9e8d64991 100644
--- a/specs/schema/README.md
+++ b/specs/schema/README.md
@@ -4,28 +4,28 @@
Stores ERC-7710 signed delegation envelopes. Spec: `permissions/0.1`.
-| Column | Type | Description |
-|---|---|---|
-| `id` | UUID | Primary key, generated by `gen_random_uuid()`. |
-| `agent_id` | UUID | Foreign key to `agent_identities(id)`; cascades on agent delete. |
-| `chain_id` | INTEGER | EVM chain ID (must be > 0). |
-| `delegator_address` | TEXT | EIP-55 checksummed user wallet address (42 chars, `0x`-prefixed). |
-| `delegate_address` | TEXT | EIP-55 checksummed agent smart-account address (42 chars, `0x`-prefixed). |
-| `delegation_hash` | TEXT | keccak256 of the delegation envelope; unique across all rows. |
-| `delegation_json` | JSONB | Full signed ERC-7710 delegation envelope as returned by MetaMask. |
-| `scope` | JSONB | Permission scope: `{ token, maxAmount, targets[], expiry, period }`. |
-| `status` | TEXT | Lifecycle state: `active`, `revoked`, or `expired`. Default `active`. |
-| `expires_at` | TIMESTAMPTZ | Wall-clock expiry of the delegation (from the signed scope). |
-| `created_at` | TIMESTAMPTZ | Row creation time; set to `NOW()` on insert. |
-| `revoked_at` | TIMESTAMPTZ | Timestamp of on-chain revocation; NULL while active. |
-| `tx_hash_revoke` | TEXT | Transaction hash of the `disableDelegation` call; NULL until revoked. |
-| `last_redeemed_at` | TIMESTAMPTZ | Timestamp of most recent successful redemption; updated by task-09 redeem endpoint. |
-| `redemption_count` | INTEGER | Running count of successful redemptions; updated by task-09 redeem endpoint. Default 0. |
+| Column | Type | Description |
+| ------------------- | ----------- | --------------------------------------------------------------------------------------- |
+| `id` | UUID | Primary key, generated by `gen_random_uuid()`. |
+| `agent_id` | UUID | Foreign key to `agent_identities(id)`; cascades on agent delete. |
+| `chain_id` | INTEGER | EVM chain ID (must be > 0). |
+| `delegator_address` | TEXT | EIP-55 checksummed user wallet address (42 chars, `0x`-prefixed). |
+| `delegate_address` | TEXT | EIP-55 checksummed agent smart-account address (42 chars, `0x`-prefixed). |
+| `delegation_hash` | TEXT | keccak256 of the delegation envelope; unique across all rows. |
+| `delegation_json` | JSONB | Full signed ERC-7710 delegation envelope as returned by MetaMask. |
+| `scope` | JSONB | Permission scope: `{ token, maxAmount, targets[], expiry, period }`. |
+| `status` | TEXT | Lifecycle state: `active`, `revoked`, or `expired`. Default `active`. |
+| `expires_at` | TIMESTAMPTZ | Wall-clock expiry of the delegation (from the signed scope). |
+| `created_at` | TIMESTAMPTZ | Row creation time; set to `NOW()` on insert. |
+| `revoked_at` | TIMESTAMPTZ | Timestamp of on-chain revocation; NULL while active. |
+| `tx_hash_revoke` | TEXT | Transaction hash of the `disableDelegation` call; NULL until revoked. |
+| `last_redeemed_at` | TIMESTAMPTZ | Timestamp of most recent successful redemption; updated by task-09 redeem endpoint. |
+| `redemption_count` | INTEGER | Running count of successful redemptions; updated by task-09 redeem endpoint. Default 0. |
### Indexes
-| Index | Covers |
-|---|---|
-| `idx_delegations_agent` | Lookups by `agent_id` (list + redeem flows). |
-| `idx_delegations_status` | Partial index on `status = 'active'` (active-delegation queries). |
-| `idx_delegations_delegator` | Lookups by `delegator_address` (user manage panel). |
+| Index | Covers |
+| --------------------------- | ----------------------------------------------------------------- |
+| `idx_delegations_agent` | Lookups by `agent_id` (list + redeem flows). |
+| `idx_delegations_status` | Partial index on `status = 'active'` (active-delegation queries). |
+| `idx_delegations_delegator` | Lookups by `delegator_address` (user manage panel). |
diff --git a/src/agent-home.js b/src/agent-home.js
index 83a68afcc..ccefea0db 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -144,7 +144,9 @@ export class AgentHome {
if (agentId) {
const permContainer = panel.querySelector('#agent-permissions-container');
import('./permissions/manage-panel.js')
- .then(({ mountManagePanel }) => mountManagePanel({ container: permContainer, agentId }))
+ .then(({ mountManagePanel }) =>
+ mountManagePanel({ container: permContainer, agentId }),
+ )
.catch(() => {});
}
diff --git a/src/app.js b/src/app.js
index 35bed8b5d..818bcfb3e 100644
--- a/src/app.js
+++ b/src/app.js
@@ -10,6 +10,7 @@ import { AvatarCreator } from './avatar-creator.js';
import { resolveURI, isDecentralizedURI } from './ipfs.js';
import { saveRemoteGlbToAccount, getMe, readAuthHint } from './account.js';
import { getWidget } from './widgets.js';
+import { mountAnimationGallery } from './widgets/animation-gallery.js';
import queryString from 'query-string';
// Agent system — the new primitive layer
@@ -741,6 +742,9 @@ class App {
// Apply post-create brand bits once viewer exists.
queueMicrotask(() => this._applyWidgetConfig(cfg));
+ // Type-specific mount (runs after viewer + content come up).
+ queueMicrotask(() => this._mountWidgetByType(widget.type, cfg));
+
// Caption overlay — render once, simple.
if (cfg.caption) this._renderWidgetCaption(cfg.caption);
@@ -748,6 +752,18 @@ class App {
this._postToParent({ type: 'widget:ready', id: widget.id, widgetType: widget.type });
}
+ async _mountWidgetByType(type, cfg) {
+ try {
+ if (type === 'animation-gallery') {
+ const container = document.body;
+ const ctl = await mountAnimationGallery(this.viewer, cfg, container);
+ this._widgetController = ctl;
+ }
+ } catch (e) {
+ console.warn('[widget] mount failed', type, e?.message);
+ }
+ }
+
_applyWidgetConfig(cfg) {
if (!this.viewer) return;
try {
diff --git a/src/cloud.js b/src/cloud.js
index fd6abd105..36866bdcc 100644
--- a/src/cloud.js
+++ b/src/cloud.js
@@ -40,9 +40,29 @@ function seededRand(seed) {
* @param {string} opts.color tint color (default 'white')
*/
export class Cloud extends Object3D {
- constructor({ seed = 0, segments = 20, bounds = [5, 1, 1], scale = 1, volume = 6, speed = 0, fade = 10, opacity = 1, color = 'white' } = {}) {
+ constructor({
+ seed = 0,
+ segments = 20,
+ bounds = [5, 1, 1],
+ scale = 1,
+ volume = 6,
+ speed = 0,
+ fade = 10,
+ opacity = 1,
+ color = 'white',
+ } = {}) {
super();
- this._cfg = { seed, segments, bounds, scale, volume, speed, fade, opacity, color: new Color(color) };
+ this._cfg = {
+ seed,
+ segments,
+ bounds,
+ scale,
+ volume,
+ speed,
+ fade,
+ opacity,
+ color: new Color(color),
+ };
this._segs = [];
this._build();
}
@@ -104,7 +124,10 @@ export class Clouds extends Object3D {
});
this._mesh = new InstancedMesh(new PlaneGeometry(1, 1), mat, this._limit);
this._mesh.instanceMatrix.setUsage(DynamicDrawUsage);
- this._mesh.instanceColor = new InstancedBufferAttribute(new Float32Array(this._limit * 3), 3);
+ this._mesh.instanceColor = new InstancedBufferAttribute(
+ new Float32Array(this._limit * 3),
+ 3,
+ );
this._mesh.count = 0;
this._mesh.frustumCulled = false;
this.add(this._mesh);
diff --git a/src/components/validator-report.jsx b/src/components/validator-report.jsx
index 5a4ab7499..6c6316b0e 100644
--- a/src/components/validator-report.jsx
+++ b/src/components/validator-report.jsx
@@ -12,9 +12,52 @@ export function ValidatorReport({
hints,
infos,
}) {
+ const totalIssues =
+ issues.numErrors + issues.numWarnings + issues.numInfos + issues.numHints;
+ const isClean = totalIssues === 0;
return (
<div class="report">
<h1>Validation report</h1>
+ {isClean ? (
+ <div class="report-banner report-banner-clean" role="status">
+ <span class="report-banner-icon" aria-hidden="true">
+ ✓
+ </span>
+ <span>All clear — no validation issues found.</span>
+ </div>
+ ) : (
+ <div class="report-banner report-banner-issues" role="status">
+ <span>
+ Found <b>{totalIssues}</b> issue{totalIssues === 1 ? '' : 's'}:{' '}
+ {issues.numErrors > 0 && (
+ <span>
+ <b>{issues.numErrors}</b> error{issues.numErrors === 1 ? '' : 's'}
+ </span>
+ )}
+ {issues.numErrors > 0 && issues.numWarnings > 0 && ', '}
+ {issues.numWarnings > 0 && (
+ <span>
+ <b>{issues.numWarnings}</b> warning{issues.numWarnings === 1 ? '' : 's'}
+ </span>
+ )}
+ {(issues.numErrors > 0 || issues.numWarnings > 0) &&
+ (issues.numInfos > 0 || issues.numHints > 0) &&
+ ', '}
+ {issues.numInfos > 0 && (
+ <span>
+ <b>{issues.numInfos}</b> info
+ </span>
+ )}
+ {issues.numInfos > 0 && issues.numHints > 0 && ', '}
+ {issues.numHints > 0 && (
+ <span>
+ <b>{issues.numHints}</b> hint{issues.numHints === 1 ? '' : 's'}
+ </span>
+ )}
+ .
+ </span>
+ </div>
+ )}
<ul>
<li>
<b>Format:</b> glTF {info.version}
diff --git a/src/components/validator-table.jsx b/src/components/validator-table.jsx
index 2175ff8b2..a8e8f22f3 100644
--- a/src/components/validator-table.jsx
+++ b/src/components/validator-table.jsx
@@ -3,35 +3,45 @@ import vhtml from 'vhtml';
/** @jsx vhtml */
export function ValidatorTable({ title, color, messages }) {
+ const count = messages.length;
+ const headingId = `report-section-${title.toLowerCase()}`;
return (
- <table class="report-table">
- <thead>
- <tr style={`background: ${color}`}>
- <th>{title}</th>
- <th>Message</th>
- <th>Pointer</th>
- </tr>
- </thead>
- <tbody>
- {messages.map(({ code, message, pointer }) => {
- return (
- <tr>
- <td>
- <code>{code}</code>
- </td>
- <td>{message}</td>
- <td>
- <code>{pointer}</code>
- </td>
+ <section class="report-section" aria-labelledby={headingId}>
+ <h2 id={headingId} class="report-section-heading" style={`border-left-color: ${color}`}>
+ {title}
+ {count > 1 ? 's' : ''} <span class="report-count">({count})</span>
+ </h2>
+ <div class="report-table-wrap">
+ <table class="report-table" aria-label={`${title} issues`}>
+ <thead>
+ <tr style={`background: ${color}`}>
+ <th scope="col">Code</th>
+ <th scope="col">Message</th>
+ <th scope="col">Pointer</th>
</tr>
- );
- })}
- {messages.length === 0 && (
- <tr>
- <td colspan="3">No issues found.</td>
- </tr>
- )}
- </tbody>
- </table>
+ </thead>
+ <tbody>
+ {messages.map(({ code, message, pointer }) => {
+ return (
+ <tr>
+ <td>
+ <code>{code}</code>
+ </td>
+ <td>{message}</td>
+ <td>
+ <code>{pointer || '\u2014'}</code>
+ </td>
+ </tr>
+ );
+ })}
+ {messages.length === 0 && (
+ <tr>
+ <td colspan="3">No issues found.</td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ </section>
);
}
diff --git a/src/permissions/grant-modal.js b/src/permissions/grant-modal.js
index 4a898e2f1..8362b0ccd 100644
--- a/src/permissions/grant-modal.js
+++ b/src/permissions/grant-modal.js
@@ -34,12 +34,8 @@ const TOKENS = {
};
const KNOWN_CONTRACTS = {
- 84532: [
- { name: 'Uniswap V3 Router', address: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4' },
- ],
- 11155111: [
- { name: 'Uniswap V3 Router', address: '0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48' },
- ],
+ 84532: [{ name: 'Uniswap V3 Router', address: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4' }],
+ 11155111: [{ name: 'Uniswap V3 Router', address: '0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48' }],
1: [
{ name: 'Uniswap V3 Router', address: '0xE592427A0AEce92De3Edee1F18E0157C05861564' },
{ name: 'Uniswap V2 Router', address: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' },
@@ -108,13 +104,16 @@ function buildReviewLines(form, chainId) {
const decimals = meta ? meta.decimals : 18;
const amount = form.amount ? formatAmount(toBaseUnits(form.amount, decimals), decimals) : '?';
- const periodLabel = { once: 'in total', daily: 'per day', weekly: 'per week' }[form.period] ?? '';
+ const periodLabel =
+ { once: 'in total', daily: 'per day', weekly: 'per week' }[form.period] ?? '';
const expiryTs = resolveExpiry(form.expiry, form.customExpiry);
const expiryDate = expiryTs
? new Date(expiryTs * 1000).toLocaleDateString('en-US', {
- month: 'short', day: 'numeric', year: 'numeric',
- })
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ })
: 'an unknown date';
const lines = [];
@@ -126,15 +125,12 @@ function buildReviewLines(form, chainId) {
return known ? `${known.name} (${formatAddress(addr)})` : formatAddress(addr);
});
- const targetDesc =
- form.targets.length === 0
- ? 'any contract'
- : targetNames.join(', ');
+ const targetDesc = form.targets.length === 0 ? 'any contract' : targetNames.join(', ');
lines.push(
`This agent can spend up to <strong>${escapeHtml(amount)} ${escapeHtml(symbol)}</strong>` +
- ` ${escapeHtml(periodLabel)} on <strong>${escapeHtml(targetDesc)}</strong>` +
- ` until <strong>${escapeHtml(expiryDate)}</strong>.`,
+ ` ${escapeHtml(periodLabel)} on <strong>${escapeHtml(targetDesc)}</strong>` +
+ ` until <strong>${escapeHtml(expiryDate)}</strong>.`,
);
return lines;
@@ -409,7 +405,9 @@ export class GrantPermissionsModal {
const prev = this._previouslyFocused;
this._previouslyFocused = null;
if (prev && typeof prev.focus === 'function' && document.contains(prev)) {
- try { prev.focus(); } catch (_) {}
+ try {
+ prev.focus();
+ } catch (_) {}
}
}
@@ -480,9 +478,7 @@ export class GrantPermissionsModal {
const targetRows = this._form.targets
.map((addr) => {
- const known = contracts.find(
- (c) => c.address.toLowerCase() === addr.toLowerCase(),
- );
+ const known = contracts.find((c) => c.address.toLowerCase() === addr.toLowerCase());
return `
<div class="gm-target-row" data-addr="${escapeHtml(addr)}">
<span class="gm-target-addr" title="${escapeHtml(addr)}">${escapeHtml(addr)}</span>
@@ -494,10 +490,7 @@ export class GrantPermissionsModal {
.join('');
const knownOptions = contracts
- .map(
- (c) =>
- `<option value="${escapeHtml(c.address)}">${escapeHtml(c.name)}</option>`,
- )
+ .map((c) => `<option value="${escapeHtml(c.address)}">${escapeHtml(c.name)}</option>`)
.join('');
this._body.innerHTML = `
@@ -665,9 +658,7 @@ export class GrantPermissionsModal {
}
_addTarget(addr, listEl) {
- if (
- this._form.targets.some((t) => t.toLowerCase() === addr.toLowerCase())
- ) return;
+ if (this._form.targets.some((t) => t.toLowerCase() === addr.toLowerCase())) return;
this._form.targets.push(addr);
const known = knownContractsForChain(this._chainId).find(
(c) => c.address.toLowerCase() === addr.toLowerCase(),
@@ -705,13 +696,9 @@ export class GrantPermissionsModal {
_renderStep2() {
const lines = buildReviewLines(this._form, this._chainId);
- const hasUnknown = this._form.targets.some(
- (addr) => !isKnownTarget(addr, this._chainId),
- );
+ const hasUnknown = this._form.targets.some((addr) => !isKnownTarget(addr, this._chainId));
- const lineItems = lines
- .map((l) => `<li class="gm-review-item">${l}</li>`)
- .join('');
+ const lineItems = lines.map((l) => `<li class="gm-review-item">${l}</li>`).join('');
this._body.innerHTML = `
<ul class="gm-review-list" role="list">${lineItems}</ul>
@@ -733,12 +720,12 @@ export class GrantPermissionsModal {
</div>
`;
- this._body.querySelector('#gm-back-btn').addEventListener('click', () =>
- this._renderStep(1),
- );
- this._body.querySelector('#gm-continue-btn').addEventListener('click', () =>
- this._renderStep(3),
- );
+ this._body
+ .querySelector('#gm-back-btn')
+ .addEventListener('click', () => this._renderStep(1));
+ this._body
+ .querySelector('#gm-continue-btn')
+ .addEventListener('click', () => this._renderStep(3));
}
// ── Step 3: Sign + submit ─────────────────────────────────────────────────
@@ -781,15 +768,13 @@ export class GrantPermissionsModal {
this._setActions(
`<button class="gm-btn gm-btn--ghost" id="gm-retry-conn">Retry</button>`,
);
- this._body.querySelector('#gm-retry-conn')?.addEventListener('click', () =>
- this._signAndSubmit(),
- );
+ this._body
+ .querySelector('#gm-retry-conn')
+ ?.addEventListener('click', () => this._signAndSubmit());
return;
}
- const meta = tokensForChain(this._chainId).find(
- (t) => t.address === this._form.token,
- );
+ const meta = tokensForChain(this._chainId).find((t) => t.address === this._form.token);
const decimals = meta ? meta.decimals : 18;
const maxAmount = toBaseUnits(this._form.amount || '0', decimals);
const expiry = resolveExpiry(this._form.expiry, this._form.customExpiry);
@@ -823,9 +808,9 @@ export class GrantPermissionsModal {
this._setActions(
`<button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>`,
);
- this._body.querySelector('#gm-back-from-err')?.addEventListener('click', () =>
- this._renderStep(1),
- );
+ this._body
+ .querySelector('#gm-back-from-err')
+ ?.addEventListener('click', () => this._renderStep(1));
return;
}
@@ -833,17 +818,18 @@ export class GrantPermissionsModal {
signed = await signDelegation({ ...delegation, scope }, signer);
this._signedDelegation = signed;
} catch (err) {
- const reason = err?.code === 4001 || err?.code === 'ACTION_REJECTED'
- ? 'Signature rejected.'
- : `Signature failed: ${err.message}`;
+ const reason =
+ err?.code === 4001 || err?.code === 'ACTION_REJECTED'
+ ? 'Signature rejected.'
+ : `Signature failed: ${err.message}`;
this._setStatus('✗', reason, 'gm-status--error');
this._setActions(`
<button class="gm-btn gm-btn--ghost" id="gm-back-from-err">← Back</button>
<button class="gm-btn gm-btn--primary" id="gm-retry-sign">Retry</button>
`);
- this._body.querySelector('#gm-back-from-err')?.addEventListener('click', () =>
- this._renderStep(1),
- );
+ this._body
+ .querySelector('#gm-back-from-err')
+ ?.addEventListener('click', () => this._renderStep(1));
this._body.querySelector('#gm-retry-sign')?.addEventListener('click', () => {
this._signedDelegation = null;
this._signAndSubmit();
@@ -881,8 +867,11 @@ export class GrantPermissionsModal {
const msg = err.message || String(err);
const isConflict = err.statusCode === 409;
- this._setStatus('✗', isConflict ? 'Already granted.' : `Failed: ${msg}`,
- 'gm-status--error');
+ this._setStatus(
+ '✗',
+ isConflict ? 'Already granted.' : `Failed: ${msg}`,
+ 'gm-status--error',
+ );
const detail = document.createElement('div');
detail.className = 'gm-error-detail';
@@ -895,15 +884,13 @@ export class GrantPermissionsModal {
<button class="gm-btn gm-btn--primary" id="gm-retry-submit">Retry submit</button>`;
this._setActions(retryHtml);
- this._body.querySelector('#gm-back-from-err')?.addEventListener('click', () =>
- this._renderStep(1),
- );
- this._body.querySelector('#gm-retry-submit')?.addEventListener('click', () =>
- this._submitDelegation(signed, scope),
- );
- this._body.querySelector('#gm-done-err')?.addEventListener('click', () =>
- this.close(),
- );
+ this._body
+ .querySelector('#gm-back-from-err')
+ ?.addEventListener('click', () => this._renderStep(1));
+ this._body
+ .querySelector('#gm-retry-submit')
+ ?.addEventListener('click', () => this._submitDelegation(signed, scope));
+ this._body.querySelector('#gm-done-err')?.addEventListener('click', () => this.close());
return;
}
@@ -918,7 +905,9 @@ export class GrantPermissionsModal {
_focusFirst() {
const items = this._focusables();
if (items.length) {
- try { items[0].focus(); } catch (_) {}
+ try {
+ items[0].focus();
+ } catch (_) {}
}
}
@@ -927,7 +916,7 @@ export class GrantPermissionsModal {
return Array.from(
this.overlay.querySelectorAll(
'button:not([disabled]), input:not([disabled]):not([hidden]), ' +
- 'select:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ 'select:not([disabled]), [tabindex]:not([tabindex="-1"])',
),
).filter((el) => !el.closest('[hidden]'));
}
@@ -983,7 +972,9 @@ export async function openGrantModal({ agentId, chainId, preset, delegateAddress
const res = await fetch(url);
const data = res.ok ? await res.json() : null;
delegate = data?.delegations?.[0]?.delegate ?? null;
- } catch { /* ignore */ }
+ } catch {
+ /* ignore */
+ }
}
if (!delegate) {
return { ok: false, reason: 'delegate_address_unknown' };
@@ -997,10 +988,10 @@ export async function openGrantModal({ agentId, chainId, preset, delegateAddress
const decimals = tokenMeta?.decimals ?? 6;
const presets = {};
- if (preset?.token) presets.token = preset.token;
- if (preset?.period) presets.period = preset.period;
- if (preset?.targets) presets.targets = preset.targets;
- if (preset?.maxAmount) presets.amount = String(Number(preset.maxAmount) / 10 ** decimals);
+ if (preset?.token) presets.token = preset.token;
+ if (preset?.period) presets.period = preset.period;
+ if (preset?.targets) presets.targets = preset.targets;
+ if (preset?.maxAmount) presets.amount = String(Number(preset.maxAmount) / 10 ** decimals);
if (preset?.expiry_days) {
presets.expiry = '30d';
}
diff --git a/src/permissions/manage-panel.js b/src/permissions/manage-panel.js
index 24fea4744..d1c4d770f 100644
--- a/src/permissions/manage-panel.js
+++ b/src/permissions/manage-panel.js
@@ -113,12 +113,19 @@ class ManagePanel {
const chainName = chainMeta?.shortName ?? `${d.chain_id}`;
const explorerBase = chainMeta?.explorer ?? '';
- const delegatorUrl = explorerBase ? addressExplorerUrl(d.chain_id, d.delegator_address) : '#';
+ const delegatorUrl = explorerBase
+ ? addressExplorerUrl(d.chain_id, d.delegator_address)
+ : '#';
const delegateUrl = explorerBase ? addressExplorerUrl(d.chain_id, d.delegate_address) : '#';
const scopeText = _scopeSentence(d.scope);
const usageLine = _usageLine(d.redemption_count, d.last_redeemed_at);
- const badgeClass = { active: 'mp-badge--active', revoked: 'mp-badge--revoked', expired: 'mp-badge--expired' }[d.status] || '';
+ const badgeClass =
+ {
+ active: 'mp-badge--active',
+ revoked: 'mp-badge--revoked',
+ expired: 'mp-badge--expired',
+ }[d.status] || '';
const hashShort = d.delegation_hash
? `${d.delegation_hash.slice(0, 8)}…${d.delegation_hash.slice(-6)}`
: 'unknown hash';
@@ -145,9 +152,11 @@ class ManagePanel {
</a>
</div>
<div class="mp-card-actions">
- ${d.status === 'active'
- ? `<button class="mp-revoke-btn" data-id="${_esc(d.id)}" data-hash="${_esc(d.delegation_hash || '')}" data-chain="${d.chain_id}">Revoke</button>`
- : ''}
+ ${
+ d.status === 'active'
+ ? `<button class="mp-revoke-btn" data-id="${_esc(d.id)}" data-hash="${_esc(d.delegation_hash || '')}" data-chain="${d.chain_id}">Revoke</button>`
+ : ''
+ }
</div>
<div class="mp-card-error" style="display:none"></div>
<div class="mp-card-pending" style="display:none"></div>
@@ -194,9 +203,7 @@ class ManagePanel {
const delegatorAddr = (d.delegator_address || '').toLowerCase();
if (signerAddress !== delegatorAddr) {
- _showError(
- `Connect with ${_shortAddr(d.delegator_address)} to revoke.`,
- );
+ _showError(`Connect with ${_shortAddr(d.delegator_address)} to revoke.`);
return;
}
@@ -303,12 +310,28 @@ function _shortAddr(addr) {
function _scopeSentence(scope) {
if (!scope) return 'Unknown scope';
const { token, maxAmount, period, targets, expiry } = scope;
- const tokenLabel = token && token !== 'native' ? _shortAddr(token) : (token === 'native' ? 'native token' : 'token');
+ const tokenLabel =
+ token && token !== 'native'
+ ? _shortAddr(token)
+ : token === 'native'
+ ? 'native token'
+ : 'token';
const amountLabel = maxAmount ? _formatAmount(maxAmount) : '?';
- const periodLabel = { daily: 'per day', weekly: 'per week', once: 'once' }[period] || period || '';
- const targetLabel = targets?.length === 1 ? `on ${_shortAddr(targets[0])}` : targets?.length > 1 ? `on ${targets.length} contracts` : '';
+ const periodLabel =
+ { daily: 'per day', weekly: 'per week', once: 'once' }[period] || period || '';
+ const targetLabel =
+ targets?.length === 1
+ ? `on ${_shortAddr(targets[0])}`
+ : targets?.length > 1
+ ? `on ${targets.length} contracts`
+ : '';
const expiryLabel = expiry ? `until ${_formatDate(expiry)}` : '';
- const parts = [`Up to ${amountLabel} ${tokenLabel}`, periodLabel, targetLabel, expiryLabel].filter(Boolean);
+ const parts = [
+ `Up to ${amountLabel} ${tokenLabel}`,
+ periodLabel,
+ targetLabel,
+ expiryLabel,
+ ].filter(Boolean);
return parts.join(' ');
}
diff --git a/src/permissions/toolkit.js b/src/permissions/toolkit.js
index 1676c2fd3..ac632234d 100644
--- a/src/permissions/toolkit.js
+++ b/src/permissions/toolkit.js
@@ -7,7 +7,14 @@
* 5 MB threshold (@metamask/delegation-abis alone is 6.2 MB unpacked).
*/
-import { AbiCoder, Contract, getAddress, JsonRpcProvider, randomBytes, TypedDataEncoder } from 'ethers';
+import {
+ AbiCoder,
+ Contract,
+ getAddress,
+ JsonRpcProvider,
+ randomBytes,
+ TypedDataEncoder,
+} from 'ethers';
import {
CAVEAT_ENFORCERS,
DELEGATION_MANAGER_ABI,
@@ -60,7 +67,11 @@ function checksum(addr, label) {
*/
function managerAddress(chainId) {
const addr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
- if (!addr) throw new PermissionError('chain_not_supported', `No DelegationManager deployment for chain ${chainId}`);
+ if (!addr)
+ throw new PermissionError(
+ 'chain_not_supported',
+ `No DelegationManager deployment for chain ${chainId}`,
+ );
return addr;
}
@@ -130,7 +141,7 @@ const SINGLE_DEFAULT_MODE = '0x0100000000000000000000000000000000000000000000000
*/
export function encodeScopedDelegation({ delegator, delegate, caveats, expiry, chainId }) {
const delegatorAddr = checksum(delegator, 'delegator');
- const delegateAddr = checksum(delegate, 'delegate');
+ const delegateAddr = checksum(delegate, 'delegate');
if (delegateAddr === delegatorAddr) {
throw new PermissionError('signature_invalid', 'delegate must differ from delegator');
@@ -139,25 +150,28 @@ export function encodeScopedDelegation({ delegator, delegate, caveats, expiry, c
throw new PermissionError('signature_invalid', 'at least one caveat is required');
}
if (expiry <= Math.floor(Date.now() / 1000) + 60) {
- throw new PermissionError('delegation_expired', 'expiry must be at least 60 seconds in the future');
+ throw new PermissionError(
+ 'delegation_expired',
+ 'expiry must be at least 60 seconds in the future',
+ );
}
managerAddress(chainId); // throws chain_not_supported if unknown
const normalizedCaveats = caveats.map((c, i) => ({
enforcer: checksum(c.enforcer, `caveats[${i}].enforcer`),
- terms: c.terms ?? '0x',
- args: c.args ?? '0x',
+ terms: c.terms ?? '0x',
+ args: c.args ?? '0x',
}));
// Cryptographically random 32-byte salt to prevent replay.
const salt = BigInt('0x' + Buffer.from(randomBytes(32)).toString('hex'));
return {
- delegate: delegateAddr,
+ delegate: delegateAddr,
delegator: delegatorAddr,
authority: ROOT_AUTHORITY,
- caveats: normalizedCaveats,
+ caveats: normalizedCaveats,
salt,
expiry,
chainId,
@@ -188,11 +202,11 @@ export async function signDelegation(delegation, signer) {
const domain = EIP712_DOMAIN({ chainId: delegation.chainId, verifyingContract });
const typedValue = {
- delegate: delegation.delegate,
+ delegate: delegation.delegate,
delegator: delegation.delegator,
authority: delegation.authority ?? ROOT_AUTHORITY,
- caveats: delegation.caveats,
- salt: delegation.salt ?? 0n,
+ caveats: delegation.caveats,
+ salt: delegation.salt ?? 0n,
};
let signature;
@@ -223,19 +237,21 @@ export async function signDelegation(delegation, signer) {
*/
export async function redeemDelegation({ delegation, calls, signer, chainId }) {
if (!signer) throw new PermissionError('signature_invalid', 'signer is required');
- if (!signer.provider) throw new PermissionError('chain_not_supported', 'signer has no provider attached');
+ if (!signer.provider)
+ throw new PermissionError('chain_not_supported', 'signer has no provider attached');
const addr = managerAddress(chainId);
// Pre-flight: check delegation is not disabled on-chain.
const dmRead = new Contract(addr, DELEGATION_MANAGER_ABI, signer.provider);
const disabled = await dmRead.disabledDelegations(delegation.hash);
- if (disabled) throw new PermissionError('delegation_revoked', 'delegation has been revoked on-chain');
+ if (disabled)
+ throw new PermissionError('delegation_revoked', 'delegation has been revoked on-chain');
// Build permissionContexts: one entry per call, each wrapping the same delegation chain.
const permissionContext = encodePermissionContext([delegation]);
const permissionContexts = calls.map(() => permissionContext);
- const modes = calls.map(() => SINGLE_DEFAULT_MODE);
+ const modes = calls.map(() => SINGLE_DEFAULT_MODE);
const executionCallDatas = calls.map((c) =>
encodeSingleExecution(checksum(c.to, 'calls[].to'), c.value ?? 0n, c.data ?? '0x'),
);
@@ -247,9 +263,9 @@ export async function redeemDelegation({ delegation, calls, signer, chainId }) {
return {
txHash: tx.hash,
receipt: {
- status: receipt.status,
+ status: receipt.status,
blockNumber: receipt.blockNumber,
- gasUsed: receipt.gasUsed.toString(),
+ gasUsed: receipt.gasUsed.toString(),
},
};
}
@@ -270,7 +286,8 @@ export async function redeemDelegation({ delegation, calls, signer, chainId }) {
export async function isDelegationValid({ hash, chainId, rpcUrl, delegation }) {
const addr = managerAddress(chainId); // throws if unsupported
- const url = rpcUrl ?? (typeof process !== 'undefined' ? process.env[`RPC_URL_${chainId}`] : undefined);
+ const url =
+ rpcUrl ?? (typeof process !== 'undefined' ? process.env[`RPC_URL_${chainId}`] : undefined);
if (!url) return { valid: false, reason: 'no rpcUrl provided for on-chain check' };
try {
@@ -292,13 +309,18 @@ export async function isDelegationValid({ hash, chainId, rpcUrl, delegation }) {
const verifyingContract = addr;
const domain = EIP712_DOMAIN({ chainId, verifyingContract });
const typedValue = {
- delegate: delegation.delegate,
+ delegate: delegation.delegate,
delegator: delegation.delegator,
authority: delegation.authority ?? ROOT_AUTHORITY,
- caveats: delegation.caveats,
- salt: delegation.salt,
+ caveats: delegation.caveats,
+ salt: delegation.salt,
};
- const recovered = TypedDataEncoder.recoverAddress(domain, DELEGATION_TYPES, typedValue, delegation.signature);
+ const recovered = TypedDataEncoder.recoverAddress(
+ domain,
+ DELEGATION_TYPES,
+ typedValue,
+ delegation.signature,
+ );
if (recovered.toLowerCase() !== delegation.delegator.toLowerCase()) {
return { valid: false, reason: 'signature_invalid' };
}
@@ -341,11 +363,11 @@ export function delegationToManifestEntry(signedDelegation) {
hash,
...(uri ? { uri } : {}),
scope: scope ?? {
- token: 'native',
+ token: 'native',
maxAmount: '0',
- period: 'once',
- targets: [],
- expiry: expiry ?? 0,
+ period: 'once',
+ targets: [],
+ expiry: expiry ?? 0,
},
};
}
diff --git a/src/runtime/delegation-redeem.js b/src/runtime/delegation-redeem.js
index efb5c84f7..e3b4befaf 100644
--- a/src/runtime/delegation-redeem.js
+++ b/src/runtime/delegation-redeem.js
@@ -245,7 +245,8 @@ export async function redeemFromSkill({ agentId, chainId, calls, skillId, mode =
// Resolve auto mode
let resolvedMode = mode;
if (mode === 'auto') {
- const hasWallet = typeof window !== 'undefined' && !!window.ethereum && !!delegation.signature;
+ const hasWallet =
+ typeof window !== 'undefined' && !!window.ethereum && !!delegation.signature;
const hasToken = !!_getRelayerToken(agentId);
if (hasWallet) resolvedMode = 'client';
else if (hasToken) resolvedMode = 'relayer';
diff --git a/src/validator.js b/src/validator.js
index 12227e378..235987436 100644
--- a/src/validator.js
+++ b/src/validator.js
@@ -125,13 +125,12 @@ export class Validator {
});
Object.keys(CODES).forEach((code) => {
Object.keys(CODES[code].pointerCounts).forEach((pointer) => {
+ const count = CODES[code].pointerCounts[pointer];
+ if (count < 2) return;
report.errors.push({
code: code,
pointer: pointer,
- message: CODES[code].message.replace(
- '{count}',
- CODES[code].pointerCounts[pointer],
- ),
+ message: CODES[code].message.replace('{count}', count),
});
});
});
diff --git a/src/viewer.js b/src/viewer.js
index ff8acd6f9..f02266a93 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -17,7 +17,6 @@ import {
} from 'three';
import Stats from 'three/addons/libs/stats.module.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
@@ -30,8 +29,7 @@ import {
DEFAULT_CAMERA,
Preset,
MANAGER,
- DRACO_LOADER,
- KTX2_LOADER,
+ getDecoders,
traverseMaterials,
} from './viewer/internal.js';
import { addLights, removeLights } from './viewer/lights.js';
@@ -308,42 +306,44 @@ export class Viewer {
return (path || '') + url;
});
- const loader = new GLTFLoader(MANAGER)
- .setCrossOrigin('anonymous')
- .setDRACOLoader(DRACO_LOADER)
- .setKTX2Loader(KTX2_LOADER.detectSupport(this.renderer))
- .setMeshoptDecoder(MeshoptDecoder);
-
const blobURLs = [];
- loader.load(
- url,
- (gltf) => {
- window.VIEWER.json = gltf;
+ getDecoders().then(({ dracoLoader, ktx2Loader, meshoptDecoder }) => {
+ const loader = new GLTFLoader(MANAGER)
+ .setCrossOrigin('anonymous')
+ .setDRACOLoader(dracoLoader)
+ .setKTX2Loader(ktx2Loader.detectSupport(this.renderer))
+ .setMeshoptDecoder(meshoptDecoder);
- const scene = gltf.scene || gltf.scenes[0];
- const clips = gltf.animations || [];
+ loader.load(
+ url,
+ (gltf) => {
+ window.VIEWER.json = gltf;
- if (!scene) {
- // Valid, but not supported by this viewer.
- throw new Error(
- 'This model contains no scene, and cannot be viewed here. However,' +
- ' it may contain individual 3D resources.',
- );
- }
+ const scene = gltf.scene || gltf.scenes[0];
+ const clips = gltf.animations || [];
- this.setContent(scene, clips);
+ if (!scene) {
+ // Valid, but not supported by this viewer.
+ throw new Error(
+ 'This model contains no scene, and cannot be viewed here. However,' +
+ ' it may contain individual 3D resources.',
+ );
+ }
- blobURLs.forEach(URL.revokeObjectURL);
+ this.setContent(scene, clips);
- // See: https://github.com/google/draco/issues/349
- // DRACOLoader.releaseDecoderModule();
+ blobURLs.forEach(URL.revokeObjectURL);
- resolve(gltf);
- },
- undefined,
- reject,
- );
+ // See: https://github.com/google/draco/issues/349
+ // DRACOLoader.releaseDecoderModule();
+
+ resolve(gltf);
+ },
+ undefined,
+ reject,
+ );
+ }, reject);
});
}
diff --git a/src/viewer/internal.js b/src/viewer/internal.js
index 76b7029d7..53eeaa723 100644
--- a/src/viewer/internal.js
+++ b/src/viewer/internal.js
@@ -1,18 +1,36 @@
import { LoadingManager, REVISION } from 'three';
-import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
-import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
export const DEFAULT_CAMERA = '[default]';
export const Preset = { ASSET_GENERATOR: 'assetgenerator' };
export const MANAGER = new LoadingManager();
const THREE_PATH = `https://unpkg.com/three@0.${REVISION}.x`;
-export const DRACO_LOADER = new DRACOLoader(MANAGER).setDecoderPath(
- `${THREE_PATH}/examples/jsm/libs/draco/gltf/`,
-);
-export const KTX2_LOADER = new KTX2Loader(MANAGER).setTranscoderPath(
- `${THREE_PATH}/examples/jsm/libs/basis/`,
-);
+
+/**
+ * Lazy, memoized setup of the Draco/KTX2/Meshopt decoders. Dynamically imports
+ * each module the first time a model is loaded, so the first-paint bundle does
+ * not pay for decoders that most callers never use.
+ *
+ * @returns {Promise<{ dracoLoader: DRACOLoader, ktx2Loader: KTX2Loader, meshoptDecoder: any }>}
+ */
+let _decodersPromise = null;
+export function getDecoders() {
+ if (_decodersPromise) return _decodersPromise;
+ _decodersPromise = Promise.all([
+ import('three/addons/loaders/DRACOLoader.js'),
+ import('three/addons/loaders/KTX2Loader.js'),
+ import('three/addons/libs/meshopt_decoder.module.js'),
+ ]).then(([dracoMod, ktx2Mod, meshoptMod]) => {
+ const dracoLoader = new dracoMod.DRACOLoader(MANAGER).setDecoderPath(
+ `${THREE_PATH}/examples/jsm/libs/draco/gltf/`,
+ );
+ const ktx2Loader = new ktx2Mod.KTX2Loader(MANAGER).setTranscoderPath(
+ `${THREE_PATH}/examples/jsm/libs/basis/`,
+ );
+ return { dracoLoader, ktx2Loader, meshoptDecoder: meshoptMod.MeshoptDecoder };
+ });
+ return _decodersPromise;
+}
export function traverseMaterials(object, callback) {
const seen = new Set();
diff --git a/src/wallet/connect-button.js b/src/wallet/connect-button.js
index 5bbb2b0cc..cd1bd4390 100644
--- a/src/wallet/connect-button.js
+++ b/src/wallet/connect-button.js
@@ -92,7 +92,8 @@ export class ConnectWalletController extends EventTarget {
};
this.#s = initialState();
- this.#onAccountsChanged = (accounts) => this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });
+ this.#onAccountsChanged = (accounts) =>
+ this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });
this.#onChainChanged = (chainIdHex) => {
const chainId = parseInt(chainIdHex, 16);
this.#dispatch({ type: 'CHAIN_CHANGED', chainId });
@@ -109,10 +110,18 @@ export class ConnectWalletController extends EventTarget {
}
}
- get state() { return this.#s.status; }
- get address() { return this.#s.address; }
- get chainId() { return this.#s.chainId; }
- get error() { return this.#s.error; }
+ get state() {
+ return this.#s.status;
+ }
+ get address() {
+ return this.#s.address;
+ }
+ get chainId() {
+ return this.#s.chainId;
+ }
+ get error() {
+ return this.#s.error;
+ }
/** @param {{ type: string, [k: string]: any }} action */
#dispatch(action) {
@@ -168,7 +177,10 @@ export class ConnectWalletController extends EventTarget {
});
} else if (e?.code !== 4001) {
// 4001 = user rejected — surface as error; other codes are bugs
- this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });
+ this.#dispatch({
+ type: 'ERROR',
+ error: e instanceof Error ? e : new Error(String(e)),
+ });
}
}
}
diff --git a/src/wallet/state.js b/src/wallet/state.js
index 6130989eb..df6c20bef 100644
--- a/src/wallet/state.js
+++ b/src/wallet/state.js
@@ -42,13 +42,19 @@ export function reduce(state, action) {
case 'HAS_PROVIDER':
return { ...state, status: STATES.REQUESTING_ACCOUNTS };
case 'ACCOUNTS_RESOLVED':
- return { ...state, status: STATES.CONNECTED, address: action.address, chainId: action.chainId };
+ return {
+ ...state,
+ status: STATES.CONNECTED,
+ address: action.address,
+ chainId: action.chainId,
+ };
case 'WRONG_CHAIN':
return { ...state, status: STATES.WRONG_CHAIN };
case 'CHAIN_OK':
return { ...state, status: STATES.CONNECTED };
case 'SIGN':
- if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN) return state;
+ if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN)
+ return state;
return { ...state, status: STATES.SIGNING };
case 'SIGNATURE_OBTAINED':
return { ...state, status: STATES.VERIFYING };
@@ -60,7 +66,12 @@ export function reduce(state, action) {
return initialState();
case 'ACCOUNTS_CHANGED':
if (!action.accounts || action.accounts.length === 0) return initialState();
- return { ...state, address: action.accounts[0], chainId: state.chainId, status: STATES.CONNECTED };
+ return {
+ ...state,
+ address: action.accounts[0],
+ chainId: state.chainId,
+ status: STATES.CONNECTED,
+ };
case 'CHAIN_CHANGED':
return { ...state, chainId: action.chainId };
default:
diff --git a/src/widget-types.js b/src/widget-types.js
index faf06ec78..af812c9a0 100644
--- a/src/widget-types.js
+++ b/src/widget-types.js
@@ -17,7 +17,7 @@ export const WIDGET_TYPES = {
'animation-gallery': {
label: 'Animation Gallery',
desc: 'Click through every clip on a rigged avatar.',
- status: 'pending',
+ status: 'ready',
icon: '▶',
},
'talking-agent': {
diff --git a/src/widgets/animation-gallery.js b/src/widgets/animation-gallery.js
new file mode 100644
index 000000000..6aee5d6a7
--- /dev/null
+++ b/src/widgets/animation-gallery.js
@@ -0,0 +1,306 @@
+/**
+ * Animation Gallery Widget — a clip browser overlaid on the 3D viewer.
+ *
+ * Lets visitors tap through every animation clip on a rigged avatar without
+ * touching dat.GUI or the full controls chrome. Supports:
+ *
+ * - `defaultClip` — clip name that autoplays on mount
+ * - `loopAll` — chain clips in order on completion
+ * - `showClipPicker` — hide the picker UI (used by parent-driven embeds)
+ *
+ * Parent pages can still send `widget:command` postMessages with
+ * `play_clip { name }` to drive playback externally; this widget's UI and
+ * external commands coexist.
+ */
+
+import { LoopOnce, LoopRepeat } from 'three';
+
+const POLL_INTERVAL_MS = 100;
+const POLL_MAX_MS = 8000;
+
+/**
+ * @param {import('../viewer.js').Viewer} viewer
+ * @param {object} config Gallery config (see widget-types.js 'animation-gallery').
+ * @param {HTMLElement} container Root container.
+ * @returns {Promise<{ destroy: () => void }>}
+ */
+export async function mountAnimationGallery(viewer, config, container) {
+ const state = {
+ destroyed: false,
+ currentAction: null,
+ currentClipName: null,
+ finishedHandler: null,
+ panel: null,
+ };
+
+ // Turntable look-and-feel by default — autoRotate inherited from brand cfg.
+ if (viewer.controls && config.autoRotate !== false) {
+ viewer.controls.autoRotate = true;
+ if (typeof config.rotationSpeed === 'number') {
+ viewer.controls.autoRotateSpeed = config.rotationSpeed;
+ }
+ }
+
+ const clips = await _waitForClips(viewer);
+ if (state.destroyed) return _controller(state);
+ if (!clips || clips.length === 0) {
+ _renderEmpty(container);
+ return _controller(state);
+ }
+
+ const cleanNames = clips.map((c) => _stripClipIndex(c.name));
+ const initialIdx = _pickInitialIndex(cleanNames, config.defaultClip);
+
+ _stopAllActions(viewer);
+
+ if (config.showClipPicker !== false) {
+ state.panel = _renderPicker(container, cleanNames, initialIdx, (idx) => {
+ _playAt(viewer, clips, idx, config.loopAll, state);
+ _highlight(state.panel, idx);
+ });
+ }
+
+ _playAt(viewer, clips, initialIdx, config.loopAll, state);
+
+ return _controller(state, () => {
+ state.destroyed = true;
+ _detachFinished(viewer, state);
+ if (state.panel) state.panel.remove();
+ });
+}
+
+// ─── helpers ──────────────────────────────────────────────────────────────
+
+function _controller(state, destroyFn) {
+ return {
+ destroy:
+ destroyFn ||
+ (() => {
+ state.destroyed = true;
+ }),
+ };
+}
+
+function _waitForClips(viewer) {
+ return new Promise((resolve) => {
+ const started = Date.now();
+ const poll = () => {
+ if (viewer?.clips?.length && viewer.mixer) {
+ resolve(viewer.clips.slice());
+ return;
+ }
+ if (Date.now() - started > POLL_MAX_MS) {
+ resolve([]);
+ return;
+ }
+ setTimeout(poll, POLL_INTERVAL_MS);
+ };
+ poll();
+ });
+}
+
+function _stripClipIndex(name) {
+ // viewer.js rewrites clip.name to "1. Original". Show the original.
+ const m = /^\d+\.\s*(.*)$/.exec(name);
+ return m ? m[1] : name;
+}
+
+function _pickInitialIndex(cleanNames, defaultClip) {
+ if (!defaultClip) return 0;
+ const i = cleanNames.findIndex((n) => n === defaultClip);
+ return i >= 0 ? i : 0;
+}
+
+function _stopAllActions(viewer) {
+ if (!viewer?.mixer) return;
+ viewer.mixer.stopAllAction();
+ const states = viewer.state?.actionStates;
+ if (states) {
+ for (const k of Object.keys(states)) states[k] = false;
+ }
+}
+
+function _detachFinished(viewer, state) {
+ if (state.finishedHandler && viewer?.mixer) {
+ viewer.mixer.removeEventListener('finished', state.finishedHandler);
+ state.finishedHandler = null;
+ }
+}
+
+function _playAt(viewer, clips, idx, loopAll, state) {
+ if (!viewer?.mixer || idx < 0 || idx >= clips.length) return;
+ _detachFinished(viewer, state);
+ _stopAllActions(viewer);
+
+ const clip = clips[idx];
+ const action = viewer.mixer.clipAction(clip);
+ action.reset();
+ action.enabled = true;
+ action.setEffectiveTimeScale(1);
+ action.setEffectiveWeight(1);
+ action.setLoop(loopAll ? LoopOnce : LoopRepeat, loopAll ? 1 : Infinity);
+ action.clampWhenFinished = false;
+ action.play();
+
+ if (viewer.state?.actionStates) {
+ viewer.state.actionStates[clip.name] = true;
+ }
+
+ state.currentAction = action;
+ state.currentClipName = clip.name;
+
+ if (loopAll) {
+ state.finishedHandler = () => {
+ if (state.destroyed) return;
+ const next = (idx + 1) % clips.length;
+ _playAt(viewer, clips, next, loopAll, state);
+ if (state.panel) _highlight(state.panel, next);
+ };
+ viewer.mixer.addEventListener('finished', state.finishedHandler);
+ }
+
+ if (viewer.invalidate) viewer.invalidate();
+}
+
+function _renderPicker(container, names, initialIdx, onSelect) {
+ const panel = document.createElement('div');
+ panel.className = 'anim-gallery-panel';
+ panel.setAttribute('role', 'listbox');
+ panel.setAttribute('aria-label', 'Animation clips');
+
+ const header = document.createElement('div');
+ header.className = 'anim-gallery-header';
+ header.textContent = `Clips (${names.length})`;
+ panel.appendChild(header);
+
+ const list = document.createElement('ul');
+ list.className = 'anim-gallery-list';
+
+ names.forEach((name, i) => {
+ const li = document.createElement('li');
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'anim-gallery-item';
+ btn.setAttribute('role', 'option');
+ btn.dataset.idx = String(i);
+ btn.textContent = name;
+ if (i === initialIdx) {
+ btn.classList.add('is-active');
+ btn.setAttribute('aria-selected', 'true');
+ }
+ btn.addEventListener('click', () => onSelect(i));
+ li.appendChild(btn);
+ list.appendChild(li);
+ });
+
+ panel.appendChild(list);
+ container.appendChild(panel);
+ _injectStyles();
+ return panel;
+}
+
+function _highlight(panel, idx) {
+ if (!panel) return;
+ panel.querySelectorAll('.anim-gallery-item').forEach((btn) => {
+ const active = Number(btn.dataset.idx) === idx;
+ btn.classList.toggle('is-active', active);
+ btn.setAttribute('aria-selected', active ? 'true' : 'false');
+ });
+}
+
+function _renderEmpty(container) {
+ const empty = document.createElement('div');
+ empty.className = 'anim-gallery-empty';
+ empty.textContent = 'No animation clips on this model.';
+ container.appendChild(empty);
+ _injectStyles();
+}
+
+let _stylesInjected = false;
+function _injectStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.textContent = `
+ .anim-gallery-panel {
+ position: fixed;
+ right: 16px;
+ top: 16px;
+ max-height: calc(100vh - 32px);
+ width: 220px;
+ background: rgba(10, 10, 10, 0.82);
+ backdrop-filter: blur(12px);
+ color: #e0e0e0;
+ font-family: Inter, system-ui, sans-serif;
+ border-radius: 10px;
+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35);
+ z-index: 10;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ }
+ .anim-gallery-header {
+ padding: 10px 14px;
+ font-size: 13px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ opacity: 0.75;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+ }
+ .anim-gallery-list {
+ list-style: none;
+ margin: 0;
+ padding: 6px 0;
+ overflow-y: auto;
+ }
+ .anim-gallery-list li { margin: 0; padding: 0; }
+ .anim-gallery-item {
+ width: 100%;
+ text-align: left;
+ background: transparent;
+ border: 0;
+ color: inherit;
+ padding: 8px 14px;
+ cursor: pointer;
+ font: inherit;
+ font-size: 13px;
+ line-height: 1.35;
+ transition: background-color 120ms ease;
+ }
+ .anim-gallery-item:hover {
+ background: rgba(255, 255, 255, 0.06);
+ }
+ .anim-gallery-item.is-active {
+ background: rgba(139, 92, 246, 0.22);
+ color: #fff;
+ box-shadow: inset 3px 0 0 #8b5cf6;
+ }
+ .anim-gallery-item:focus-visible {
+ outline: 2px solid #8b5cf6;
+ outline-offset: -2px;
+ }
+ .anim-gallery-empty {
+ position: fixed;
+ right: 16px;
+ top: 16px;
+ padding: 10px 14px;
+ background: rgba(10, 10, 10, 0.82);
+ color: #aaa;
+ font-family: Inter, system-ui, sans-serif;
+ font-size: 13px;
+ border-radius: 8px;
+ z-index: 10;
+ }
+ @media (max-width: 520px) {
+ .anim-gallery-panel {
+ right: 8px;
+ top: auto;
+ bottom: 8px;
+ width: calc(100% - 16px);
+ max-height: 40vh;
+ }
+ }
+ `;
+ document.head.appendChild(style);
+}
diff --git a/style.css b/style.css
index 477a7272a..0cfe5b764 100644
--- a/style.css
+++ b/style.css
@@ -664,6 +664,51 @@ footer .separator {
background: rgba(255, 255, 255, 0.02);
}
+.report-table-wrap {
+ overflow-x: auto;
+ margin-bottom: var(--space-md);
+}
+
+.report-section-heading {
+ font-size: 1.05rem;
+ margin: var(--space-md) 0 var(--space-xs);
+ padding-left: var(--space-md);
+ border-left: 4px solid #888;
+}
+
+.report-count {
+ font-weight: normal;
+ opacity: 0.7;
+ font-size: 0.9em;
+}
+
+.report-banner {
+ display: flex;
+ align-items: center;
+ gap: var(--space-md);
+ padding: var(--space-md);
+ border-radius: 6px;
+ margin-bottom: var(--space-md);
+ font-size: 0.95rem;
+}
+
+.report-banner-clean {
+ background: rgba(139, 195, 74, 0.12);
+ border: 1px solid rgba(139, 195, 74, 0.35);
+ color: #8bc34a;
+}
+
+.report-banner-issues {
+ background: rgba(244, 67, 54, 0.08);
+ border: 1px solid rgba(244, 67, 54, 0.25);
+ color: rgba(255, 255, 255, 0.85);
+}
+
+.report-banner-icon {
+ font-size: 1.5rem;
+ font-weight: bold;
+}
+
/******************************************************************************
* CSS Spinner
*
diff --git a/tests/api-agent-memory.test.js b/tests/api-agent-memory.test.js
index 206ee9221..823a666e1 100644
--- a/tests/api-agent-memory.test.js
+++ b/tests/api-agent-memory.test.js
@@ -16,7 +16,11 @@ vi.mock('../api/_lib/auth.js', () => ({
// env throws if required vars are missing — stub before handler imports it.
vi.mock('../api/_lib/env.js', () => ({
- env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
+ env: {
+ APP_ORIGIN: 'http://localhost:3000',
+ ISSUER: 'http://test',
+ MCP_RESOURCE: 'http://test',
+ },
}));
// Import the handler AFTER mocks are registered.
diff --git a/tests/api/agents.test.js b/tests/api/agents.test.js
index c1a4b620f..3c6391e96 100644
--- a/tests/api/agents.test.js
+++ b/tests/api/agents.test.js
@@ -46,9 +46,7 @@ const { default: handler } = await import('../../api/agents.js');
// ── Test helpers ──────────────────────────────────────────────────────────
function makeReq({ method = 'GET', url = '/api/agents', headers = {}, body = null } = {}) {
- const base = body
- ? Readable.from([Buffer.from(JSON.stringify(body))])
- : Readable.from([]);
+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
base.method = method;
base.url = url;
base.headers = {
diff --git a/tests/api/api-keys.test.js b/tests/api/api-keys.test.js
new file mode 100644
index 000000000..73f2ae933
--- /dev/null
+++ b/tests/api/api-keys.test.js
@@ -0,0 +1,206 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const authState = {
+ session: null,
+ bearer: null,
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+ hasScope: vi.fn((scope, needed) => {
+ if (!scope) return false;
+ return scope.split(/\s+/).includes(needed);
+ }),
+}));
+
+const sqlState = {
+ queue: [],
+ calls: [],
+};
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+const rlState = { success: true };
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: rlState.success })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const { default: handler } = await import('../../api/api-keys.js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function makeReq({ method = 'GET', url = '/api/api-keys', headers = {}, body = null } = {}) {
+ const base = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = {
+ host: 'localhost',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(reqOpts) {
+ const req = makeReq(reqOpts);
+ const res = makeRes();
+ await handler(req, res);
+ const payload = res.body ? JSON.parse(res.body) : null;
+ return { res, status: res.statusCode, body: payload };
+}
+
+beforeEach(() => {
+ authState.session = null;
+ authState.bearer = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rlState.success = true;
+});
+
+// ── Tests ─────────────────────────────────────────────────────────────────
+
+describe('GET /api/api-keys — list', () => {
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke({ method: 'GET' });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('does NOT return raw tokens (token_hash column not selected)', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue.push([
+ {
+ id: 'k1',
+ name: 'My key',
+ prefix: 'sk_live_abc123',
+ scope: 'avatars:read avatars:write',
+ last_used_at: null,
+ expires_at: null,
+ revoked_at: null,
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke({ method: 'GET' });
+
+ expect(status).toBe(200);
+ expect(body.data).toHaveLength(1);
+ expect(body.data[0].id).toBe('k1');
+ // No raw `token` field, no token_hash
+ expect(body.data[0].token).toBeUndefined();
+ expect(body.data[0].token_hash).toBeUndefined();
+ // Raw-token strings must never appear in the response
+ const serialized = JSON.stringify(body);
+ expect(serialized).not.toMatch(/sk_live_[a-f0-9]{32,}/);
+
+ // Verify the SELECT doesn't include token_hash
+ const selectCall = sqlState.calls[0];
+ expect(selectCall.query).not.toMatch(/token_hash/);
+ });
+});
+
+describe('POST /api/api-keys — create', () => {
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke({
+ method: 'POST',
+ body: { name: 'New key' },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('returns the raw token exactly once on creation', async () => {
+ authState.session = { id: 'user-2' };
+ sqlState.queue.push([
+ {
+ id: 'k2',
+ name: 'Publish',
+ prefix: 'sk_live_xxxxxx',
+ scope: 'avatars:read avatars:write',
+ expires_at: null,
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+
+ const { status, body } = await invoke({
+ method: 'POST',
+ body: { name: 'Publish' },
+ });
+
+ expect(status).toBe(201);
+ expect(body.data.id).toBe('k2');
+ expect(typeof body.data.token).toBe('string');
+ expect(body.data.token).toMatch(/^sk_live_[A-Za-z0-9_-]+$/);
+ expect(body.data.token.length).toBeGreaterThan(20);
+
+ // The INSERT must persist a hash, never the raw token
+ const insertCall = sqlState.calls.find((c) => /insert into api_keys/i.test(c.query));
+ expect(insertCall).toBeTruthy();
+ for (const v of insertCall.values) {
+ expect(v).not.toBe(body.data.token);
+ }
+ });
+
+ it('rejects unknown scopes with 400', async () => {
+ authState.session = { id: 'user-3' };
+ const { status, body } = await invoke({
+ method: 'POST',
+ body: { name: 'Bad', scope: 'avatars:read bogus:scope' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
+
+describe('method routing', () => {
+ it('rejects PUT with 405', async () => {
+ const { status, body } = await invoke({ method: 'PUT' });
+ expect(status).toBe(405);
+ expect(body.error).toBe('method_not_allowed');
+ });
+
+ it('short-circuits OPTIONS (CORS preflight) with 204', async () => {
+ const { status } = await invoke({
+ method: 'OPTIONS',
+ headers: { origin: 'http://localhost:3000' },
+ });
+ expect(status).toBe(204);
+ });
+});
+
+// Revoke lives at api/api-keys/[id].js — out of scope for this file's tests.
+describe.todo('DELETE /api/api-keys/:id — revoke 200');
+describe.todo('DELETE /api/api-keys/:id — 404 unknown id');
diff --git a/tests/api/embed-policy.test.js b/tests/api/embed-policy.test.js
index 1dff7bcba..5d262b001 100644
--- a/tests/api/embed-policy.test.js
+++ b/tests/api/embed-policy.test.js
@@ -160,7 +160,10 @@ describe('validateEmbedPolicy', () => {
it('rejects more than 100 hosts', () => {
const policy = {
- origins: { mode: 'allowlist', hosts: Array.from({ length: 101 }, (_, i) => `host${i}.com`) },
+ origins: {
+ mode: 'allowlist',
+ hosts: Array.from({ length: 101 }, (_, i) => `host${i}.com`),
+ },
surfaces: { script: true, iframe: true, widget: true, mcp: false },
brain: {
mode: 'we-pay',
diff --git a/tests/api/llm-anthropic.test.js b/tests/api/llm-anthropic.test.js
new file mode 100644
index 000000000..021336196
--- /dev/null
+++ b/tests/api/llm-anthropic.test.js
@@ -0,0 +1,395 @@
+// Tests for /api/llm/anthropic — we-pay LLM proxy.
+// Focus: monthly token budgeting (input+output), embed-policy enforcement
+// (origin, surface, brain mode), upstream error sanitization, model allowlist.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-secret-llm';
+process.env.ANTHROPIC_API_KEY ||= 'sk-ant-test-key';
+process.env.UPSTASH_REDIS_REST_URL ||= 'https://redis.test';
+process.env.UPSTASH_REDIS_REST_TOKEN ||= 'redis-token';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const policyState = { policy: null };
+
+vi.mock('../../api/_lib/embed-policy.js', () => ({
+ readEmbedPolicy: vi.fn(async () => policyState.policy),
+}));
+
+const rlState = {
+ ip: { success: true },
+ agent: { success: true },
+};
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ embedLlmIp: vi.fn(async () => rlState.ip),
+ embedLlmAgent: vi.fn(async () => rlState.agent),
+ },
+ clientIp: () => '203.0.113.1',
+}));
+
+const usageEvents = [];
+vi.mock('../../api/_lib/usage.js', () => ({
+ recordEvent: (evt) => usageEvents.push(evt),
+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
+}));
+
+// In-memory Redis stub backing the @upstash/redis client. Token + quota
+// counters are kept here so tests can prime initial usage and assert deltas.
+const redisStore = new Map();
+const redisCalls = [];
+class FakeRedis {
+ constructor(_opts) {}
+ async incr(key) {
+ const next = (redisStore.get(key) ?? 0) + 1;
+ redisStore.set(key, next);
+ redisCalls.push({ op: 'incr', key, value: next });
+ return next;
+ }
+ async incrby(key, delta) {
+ const next = (redisStore.get(key) ?? 0) + delta;
+ redisStore.set(key, next);
+ redisCalls.push({ op: 'incrby', key, delta, value: next });
+ return next;
+ }
+ async get(key) {
+ return redisStore.get(key) ?? null;
+ }
+ async expire(key, ttl) {
+ redisCalls.push({ op: 'expire', key, ttl });
+ return 1;
+ }
+}
+
+vi.mock('@upstash/redis', () => ({ Redis: FakeRedis }));
+
+// Default upstream mock — overridden per-test as needed.
+const fetchState = {
+ response: () => upstreamOk({ ok: true, usage: { input_tokens: 10, output_tokens: 20 } }),
+ calls: [],
+};
+
+function upstreamOk(json) {
+ return {
+ ok: true,
+ status: 200,
+ headers: new Map([['content-type', 'application/json']]),
+ text: async () => JSON.stringify(json),
+ };
+}
+
+function upstreamErr(status, body) {
+ return {
+ ok: false,
+ status,
+ headers: new Map([['content-type', 'application/json']]),
+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),
+ };
+}
+
+// Map.get is case-sensitive but the handler reads via headers.get('content-type')
+// — patch Headers-like objects to mimic native fetch Headers behavior.
+function patchHeaders(map) {
+ return { get: (k) => map.get(k.toLowerCase()) ?? map.get(k) ?? null };
+}
+
+globalThis.fetch = vi.fn(async (url, init) => {
+ fetchState.calls.push({ url, init });
+ const r = await fetchState.response();
+ r.headers = patchHeaders(r.headers instanceof Map ? r.headers : new Map(Object.entries(r.headers || {})));
+ return r;
+});
+
+const { default: handler } = await import('../../api/llm/anthropic.js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function makeReq({ url = '/api/llm/anthropic?agent=agent-1', headers = {}, body = null } = {}) {
+ const base = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ base.method = 'POST';
+ base.url = url;
+ base.headers = {
+ host: 'app.test',
+ 'content-type': 'application/json',
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+
+async function invoke(opts = {}) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ const json = res.body ? safeJson(res.body) : null;
+ return { res, status: res.statusCode, body: json };
+}
+
+function safeJson(s) { try { return JSON.parse(s); } catch { return s; } }
+
+const VALID_BODY = {
+ messages: [{ role: 'user', content: 'hello' }],
+ max_tokens: 100,
+};
+
+const WE_PAY_POLICY = {
+ version: 1,
+ origins: { mode: 'allowlist', hosts: ['client.test'] },
+ surfaces: { script: true, iframe: true, widget: true, mcp: false },
+ brain: {
+ mode: 'we-pay',
+ proxy_url: null,
+ monthly_quota: null,
+ rate_limit_per_min: null,
+ model: 'claude-opus-4-6',
+ cost_limit_cents: null,
+ },
+ storage: { primary: 'r2', pinned_ipfs: false, onchain_attested: false },
+};
+
+// ── Reset between tests ───────────────────────────────────────────────────
+
+beforeEach(() => {
+ policyState.policy = JSON.parse(JSON.stringify(WE_PAY_POLICY));
+ rlState.ip = { success: true };
+ rlState.agent = { success: true };
+ usageEvents.length = 0;
+ redisStore.clear();
+ redisCalls.length = 0;
+ fetchState.calls.length = 0;
+ fetchState.response = () =>
+ upstreamOk({ ok: true, usage: { input_tokens: 10, output_tokens: 20 } });
+});
+
+// ── agent + policy gating ─────────────────────────────────────────────────
+
+describe('/api/llm/anthropic — agent + policy gating', () => {
+ it('rejects when no agent query param supplied', async () => {
+ const { status, body } = await invoke({ url: '/api/llm/anthropic', body: VALID_BODY });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('returns 404 when policy not found for agent', async () => {
+ policyState.policy = null;
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('returns 402 payment_required when brain.mode is not we-pay', async () => {
+ policyState.policy.brain.mode = 'wallet-gated';
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(402);
+ expect(body.error).toBe('payment_required');
+ });
+
+ it('returns 403 embed_denied_surface when script surface is disabled', async () => {
+ policyState.policy.surfaces.script = false;
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(403);
+ expect(body.error).toBe('embed_denied_surface');
+ });
+});
+
+// ── origin enforcement ───────────────────────────────────────────────────
+
+describe('/api/llm/anthropic — origin / referer policy', () => {
+ it('rejects an origin not on the allowlist', async () => {
+ const { status, body } = await invoke({
+ body: VALID_BODY,
+ headers: { origin: 'https://attacker.test' },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('embed_denied_origin');
+ });
+
+ it('allows server-to-server (no Origin header) requests', async () => {
+ const { status } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(200);
+ });
+
+ it('allows first-party localhost origin without policy entry', async () => {
+ policyState.policy.origins.hosts = []; // explicitly empty
+ const { status } = await invoke({
+ body: VALID_BODY,
+ headers: { origin: 'http://localhost:3000' },
+ });
+ expect(status).toBe(200);
+ });
+});
+
+// ── rate limiting ────────────────────────────────────────────────────────
+
+describe('/api/llm/anthropic — rate limiting', () => {
+ it('returns 429 on per-IP rate limit', async () => {
+ rlState.ip = { success: false };
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(429);
+ expect(body.error_description).toMatch(/IP/);
+ });
+
+ it('returns 429 on per-agent rate limit when policy declares one', async () => {
+ policyState.policy.brain.rate_limit_per_min = 5;
+ rlState.agent = { success: false };
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(429);
+ expect(body.error_description).toMatch(/agent rate limit/);
+ });
+});
+
+// ── monthly call-count quota ─────────────────────────────────────────────
+
+describe('/api/llm/anthropic — monthly call quota', () => {
+ it('returns 429 quota_exceeded once monthly_quota is reached', async () => {
+ policyState.policy.brain.monthly_quota = 2;
+ // Pre-seed the call counter so the next incr crosses the quota.
+ const monthKey = new Date().toISOString().slice(0, 7);
+ redisStore.set(`llm:quota:agent-1:${monthKey}`, 2);
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(429);
+ expect(body.error).toBe('quota_exceeded');
+ expect(body.error_description).toMatch(/monthly quota of 2/);
+ });
+
+ it('passes through when under monthly_quota', async () => {
+ policyState.policy.brain.monthly_quota = 100;
+ const { status } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(200);
+ });
+});
+
+// ── monthly token budget ────────────────────────────────────────────────
+
+describe('/api/llm/anthropic — monthly token budget', () => {
+ it('returns 429 quota_exceeded when token budget already met (default budget)', async () => {
+ const monthKey = new Date().toISOString().slice(0, 7);
+ // Default budget is 1_000_000 — pre-seed at the cap.
+ redisStore.set(`llm:tokens:agent-1:${monthKey}`, 1_000_000);
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(429);
+ expect(body.error).toBe('quota_exceeded');
+ expect(body.error_description).toMatch(/monthly token budget/);
+ });
+
+ it('derives a smaller token budget from policy.brain.cost_limit_cents', async () => {
+ // 15 cents @ 1.5¢/1k tokens = 10_000-token budget.
+ policyState.policy.brain.cost_limit_cents = 15;
+ const monthKey = new Date().toISOString().slice(0, 7);
+ redisStore.set(`llm:tokens:agent-1:${monthKey}`, 10_000);
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(429);
+ expect(body.error_description).toMatch(/10000/);
+ });
+
+ it('debits actual token usage to the per-agent counter on success', async () => {
+ fetchState.response = () =>
+ upstreamOk({ ok: true, usage: { input_tokens: 123, output_tokens: 456 } });
+ const { status } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(200);
+ const monthKey = new Date().toISOString().slice(0, 7);
+ expect(redisStore.get(`llm:tokens:agent-1:${monthKey}`)).toBe(579);
+ });
+
+ it('does NOT debit tokens when upstream fails', async () => {
+ fetchState.response = () => upstreamErr(500, { error: 'overloaded' });
+ await invoke({ body: VALID_BODY });
+ const monthKey = new Date().toISOString().slice(0, 7);
+ expect(redisStore.get(`llm:tokens:agent-1:${monthKey}`)).toBeUndefined();
+ });
+});
+
+// ── request body validation + model allowlist ───────────────────────────
+
+describe('/api/llm/anthropic — request body + model', () => {
+ it('rejects empty messages array', async () => {
+ const { status, body } = await invoke({ body: { messages: [] } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects model not on allowlist', async () => {
+ const { status, body } = await invoke({
+ body: { ...VALID_BODY, model: 'gpt-4' },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/not in allowlist/);
+ });
+
+ it('uses the model from the policy when caller omits one', async () => {
+ policyState.policy.brain.model = 'claude-sonnet-4-6';
+ await invoke({ body: VALID_BODY });
+ const sentBody = JSON.parse(fetchState.calls[0].init.body);
+ expect(sentBody.model).toBe('claude-sonnet-4-6');
+ });
+
+ it('caller-supplied allowlisted model overrides policy default', async () => {
+ policyState.policy.brain.model = 'claude-opus-4-6';
+ await invoke({ body: { ...VALID_BODY, model: 'claude-opus-4-7' } });
+ const sentBody = JSON.parse(fetchState.calls[0].init.body);
+ expect(sentBody.model).toBe('claude-opus-4-7');
+ });
+});
+
+// ── upstream response handling ──────────────────────────────────────────
+
+describe('/api/llm/anthropic — upstream behaviour', () => {
+ it('proxies a successful upstream response unchanged', async () => {
+ const upstreamPayload = {
+ ok: true,
+ id: 'msg_123',
+ content: [{ type: 'text', text: 'hi' }],
+ usage: { input_tokens: 5, output_tokens: 7 },
+ };
+ fetchState.response = () => upstreamOk(upstreamPayload);
+ const { res, status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(200);
+ expect(body).toEqual(upstreamPayload);
+ expect(res.headers['content-type']).toMatch(/application\/json/);
+ });
+
+ it('sanitizes upstream errors into a generic 502 envelope (no leaking)', async () => {
+ fetchState.response = () =>
+ upstreamErr(429, { error: { type: 'rate_limit', message: 'slow down', secret: 'leaked' } });
+ const { status, body } = await invoke({ body: VALID_BODY });
+ expect(status).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ // The original Anthropic body must NOT be forwarded.
+ expect(JSON.stringify(body)).not.toContain('leaked');
+ expect(JSON.stringify(body)).not.toContain('rate_limit');
+ });
+
+ it('records a usage event with input/output token counts', async () => {
+ fetchState.response = () =>
+ upstreamOk({ ok: true, usage: { input_tokens: 11, output_tokens: 22 } });
+ await invoke({ body: VALID_BODY });
+ // recordEvent runs synchronously (queueMicrotask in production code is in
+ // usage.js; the mock here pushes immediately).
+ expect(usageEvents).toHaveLength(1);
+ expect(usageEvents[0]).toMatchObject({
+ kind: 'llm',
+ tool: 'anthropic.messages',
+ agentId: 'agent-1',
+ status: 'ok',
+ });
+ expect(usageEvents[0].meta.input_tokens).toBe(11);
+ expect(usageEvents[0].meta.output_tokens).toBe(22);
+ });
+});
diff --git a/tests/api/oauth-authorize.test.js b/tests/api/oauth-authorize.test.js
new file mode 100644
index 000000000..be10af9ff
--- /dev/null
+++ b/tests/api/oauth-authorize.test.js
@@ -0,0 +1,397 @@
+// Tests for /api/oauth/authorize — OAuth 2.1 authorization endpoint.
+// Focus: PKCE enforcement, strict redirect_uri matching (§3.1.2.2),
+// response_type validation, consent rendering and CSRF/Origin checks.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Provide the env vars the handler chain expects before importing modules.
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-secret-for-csrf-and-jwt-only';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const authState = {
+ session: null,
+ csrf: 'csrf-token-fixed',
+ csrfValid: true,
+ sameSite: true,
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ csrfTokenFor: vi.fn(async () => authState.csrf),
+ verifyCsrfToken: vi.fn(
+ async (_req, submitted) => authState.csrfValid && submitted === authState.csrf,
+ ),
+ isSameSiteOrigin: vi.fn(() => authState.sameSite),
+}));
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+vi.mock('../../api/_lib/crypto.js', () => ({
+ randomToken: vi.fn(() => 'fixed-code-1234567890abcdef'),
+}));
+
+const { default: handler } = await import('../../api/oauth/authorize.js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function makeReq({ method = 'GET', url, headers = {}, formBody = null } = {}) {
+ const base = formBody
+ ? Readable.from([Buffer.from(new URLSearchParams(formBody).toString())])
+ : Readable.from([]);
+ base.method = method;
+ base.url = url;
+ base.headers = {
+ host: 'app.test',
+ ...(formBody ? { 'content-type': 'application/x-www-form-urlencoded' } : {}),
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ return { res, status: res.statusCode, body: res.body, location: res.headers.location };
+}
+
+const VALID_QS = new URLSearchParams({
+ response_type: 'code',
+ client_id: 'mcp_test',
+ redirect_uri: 'https://client.test/cb',
+ scope: 'avatars:read',
+ state: 'abc123',
+ code_challenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
+ code_challenge_method: 'S256',
+}).toString();
+
+const VALID_CLIENT = {
+ client_id: 'mcp_test',
+ name: 'Test Client',
+ redirect_uris: ['https://client.test/cb'],
+ scope: 'avatars:read avatars:write profile',
+ client_type: 'public',
+ grant_types: ['authorization_code', 'refresh_token'],
+};
+
+function tryParseJson(s) {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return null;
+ }
+}
+
+// ── Reset between tests ───────────────────────────────────────────────────
+
+beforeEach(() => {
+ authState.session = null;
+ authState.csrfValid = true;
+ authState.sameSite = true;
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+// ── Validation: required params and PKCE ──────────────────────────────────
+
+describe('GET /api/oauth/authorize — request validation', () => {
+ it('rejects response_type other than "code"', async () => {
+ const qs = VALID_QS.replace('response_type=code', 'response_type=token');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${qs}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('unsupported_response_type');
+ });
+
+ it('rejects missing client_id', async () => {
+ const params = new URLSearchParams(VALID_QS);
+ params.delete('client_id');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_request');
+ });
+
+ it('rejects missing redirect_uri', async () => {
+ const params = new URLSearchParams(VALID_QS);
+ params.delete('redirect_uri');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_request');
+ });
+
+ it('rejects missing code_challenge (PKCE mandatory)', async () => {
+ const params = new URLSearchParams(VALID_QS);
+ params.delete('code_challenge');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error_description).toMatch(/code_challenge required/);
+ });
+
+ it('rejects missing code_challenge_method', async () => {
+ const params = new URLSearchParams(VALID_QS);
+ params.delete('code_challenge_method');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error_description).toMatch(/code_challenge_method required/);
+ });
+
+ it('rejects code_challenge_method other than S256 (e.g. "plain")', async () => {
+ const qs = VALID_QS.replace('code_challenge_method=S256', 'code_challenge_method=plain');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${qs}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error_description).toMatch(/must be S256/);
+ });
+});
+
+// ── Client / redirect_uri lookup ──────────────────────────────────────────
+
+describe('GET /api/oauth/authorize — client and redirect_uri', () => {
+ it('returns invalid_client when client_id is unknown', async () => {
+ sqlState.queue.push([]); // no client row
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${VALID_QS}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_client');
+ });
+
+ it('rejects redirect_uri not registered (different host)', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'https://attacker.test/cb');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+
+ it('rejects redirect_uri with extra path segment (exact-pathname match)', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'https://client.test/cb/extra');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+
+ it('rejects redirect_uri with different protocol (http vs https)', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'http://client.test/cb');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+
+ it('rejects redirect_uri carrying a query string', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'https://client.test/cb?injected=1');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+
+ it('rejects redirect_uri carrying a fragment', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'https://client.test/cb#frag');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+
+ it('rejects redirect_uri on different port', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const params = new URLSearchParams(VALID_QS);
+ params.set('redirect_uri', 'https://client.test:8443/cb');
+ const { status, body } = await invoke({ url: `/api/oauth/authorize?${params}` });
+ expect(status).toBe(400);
+ expect(tryParseJson(body).error).toBe('invalid_redirect_uri');
+ });
+});
+
+// ── Unauthenticated flow → bounce to login ────────────────────────────────
+
+describe('GET /api/oauth/authorize — unauthenticated', () => {
+ it('redirects anonymous caller to /login with consent URL preserved', async () => {
+ sqlState.queue.push([VALID_CLIENT]);
+ const { status, location } = await invoke({ url: `/api/oauth/authorize?${VALID_QS}` });
+ expect(status).toBe(302);
+ expect(location).toMatch(/^\/login\?next=/);
+ // The "next" target must point back to the consent page with original params.
+ const next = decodeURIComponent(location.split('next=')[1]);
+ expect(next.startsWith('/oauth/consent?')).toBe(true);
+ expect(next).toContain('client_id=mcp_test');
+ expect(next).toContain('code_challenge=');
+ });
+});
+
+// ── Authenticated GET → consent page ──────────────────────────────────────
+
+describe('GET /api/oauth/authorize — consent page render', () => {
+ it('renders an HTML consent page for an authenticated user', async () => {
+ authState.session = { id: 'user-1', email: 'u@test', display_name: 'Alice' };
+ sqlState.queue.push([VALID_CLIENT]);
+ const { res, status, body } = await invoke({ url: `/api/oauth/authorize?${VALID_QS}` });
+ expect(status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/text\/html/);
+ expect(body).toContain('Authorize <b>Test Client</b>');
+ expect(body).toContain('name="csrf"');
+ // Original PKCE params are preserved as hidden inputs for POST submit.
+ expect(body).toContain('name="code_challenge"');
+ expect(body).toContain('name="redirect_uri"');
+ // Frame protections present.
+ expect(res.headers['x-frame-options']).toBe('DENY');
+ expect(res.headers['content-security-policy']).toMatch(/frame-ancestors 'none'/);
+ });
+});
+
+// ── POST consent submission ───────────────────────────────────────────────
+
+describe('POST /api/oauth/authorize — consent submission', () => {
+ function consentForm(extra = {}) {
+ return {
+ response_type: 'code',
+ client_id: 'mcp_test',
+ redirect_uri: 'https://client.test/cb',
+ scope: 'avatars:read',
+ state: 'abc123',
+ code_challenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
+ code_challenge_method: 'S256',
+ csrf: 'csrf-token-fixed',
+ decision: 'allow',
+ ...extra,
+ };
+ }
+
+ it('issues a code and redirects with code+state on allow', async () => {
+ authState.session = { id: 'user-1', email: 'u@test', display_name: 'Alice' };
+ sqlState.queue.push([VALID_CLIENT]); // client lookup
+ sqlState.queue.push([]); // insert auth code
+ const { status, location } = await invoke({
+ method: 'POST',
+ url: '/api/oauth/authorize',
+ formBody: consentForm(),
+ });
+ expect(status).toBe(302);
+ expect(location.startsWith('https://client.test/cb?')).toBe(true);
+ const back = new URL(location);
+ expect(back.searchParams.get('code')).toBe('fixed-code-1234567890abcdef');
+ expect(back.searchParams.get('state')).toBe('abc123');
+ // Insert recorded with the issued code, client, user, redirect, scope, challenge.
+ const insert = sqlState.calls.find((c) => /insert into oauth_auth_codes/i.test(c.query));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain('fixed-code-1234567890abcdef');
+ expect(insert.values).toContain('mcp_test');
+ expect(insert.values).toContain('user-1');
+ });
+
+ it('redirects with error=access_denied when user denies', async () => {
+ authState.session = { id: 'user-1', email: 'u@test', display_name: 'Alice' };
+ sqlState.queue.push([VALID_CLIENT]);
+ const { status, location } = await invoke({
+ method: 'POST',
+ url: '/api/oauth/authorize',
+ formBody: consentForm({ decision: 'deny' }),
+ });
+ expect(status).toBe(302);
+ const u = new URL(location);
+ expect(u.origin + u.pathname).toBe('https://client.test/cb');
+ expect(u.searchParams.get('error')).toBe('access_denied');
+ expect(u.searchParams.get('state')).toBe('abc123');
+ });
+
+ it('rejects POST with bad CSRF token', async () => {
+ authState.session = { id: 'user-1', email: 'u@test', display_name: 'Alice' };
+ authState.csrfValid = false;
+ sqlState.queue.push([VALID_CLIENT]);
+ const { status, body } = await invoke({
+ method: 'POST',
+ url: '/api/oauth/authorize',
+ formBody: consentForm({ csrf: 'wrong' }),
+ });
+ expect(status).toBe(403);
+ expect(tryParseJson(body).error).toBe('forbidden');
+ expect(tryParseJson(body).error_description).toMatch(/csrf/);
+ });
+
+ it('rejects cross-site POST (Origin check)', async () => {
+ authState.session = { id: 'user-1', email: 'u@test', display_name: 'Alice' };
+ authState.sameSite = false;
+ sqlState.queue.push([VALID_CLIENT]);
+ const { status, body } = await invoke({
+ method: 'POST',
+ url: '/api/oauth/authorize',
+ formBody: consentForm(),
+ });
+ expect(status).toBe(403);
+ expect(tryParseJson(body).error_description).toMatch(/cross-site/);
+ });
+
+ it('intersects requested scope with client-allowed scope when issuing code', async () => {
+ authState.session = { id: 'user-1', email: 'u@test', display_name: 'Alice' };
+ sqlState.queue.push([VALID_CLIENT]); // client lookup
+ sqlState.queue.push([]); // insert
+ // Request a scope NOT registered for the client — must be dropped.
+ await invoke({
+ method: 'POST',
+ url: '/api/oauth/authorize',
+ formBody: consentForm({ scope: 'avatars:read avatars:delete' }),
+ });
+ const insert = sqlState.calls.find((c) => /insert into oauth_auth_codes/i.test(c.query));
+ expect(insert).toBeTruthy();
+ // Stored scope value (positional arg) should NOT include avatars:delete.
+ const storedScope = insert.values.find(
+ (v) => typeof v === 'string' && v.includes('avatars:read'),
+ );
+ expect(storedScope).toBe('avatars:read');
+ expect(storedScope).not.toMatch(/avatars:delete/);
+ });
+});
+
+// ── Method handling ───────────────────────────────────────────────────────
+
+describe('/api/oauth/authorize — HTTP method handling', () => {
+ it('returns 405 on unsupported method (DELETE)', async () => {
+ const { status } = await invoke({
+ method: 'DELETE',
+ url: `/api/oauth/authorize?${VALID_QS}`,
+ });
+ expect(status).toBe(405);
+ });
+
+ it('handles OPTIONS preflight with 204', async () => {
+ const { status } = await invoke({
+ method: 'OPTIONS',
+ url: `/api/oauth/authorize?${VALID_QS}`,
+ });
+ expect(status).toBe(204);
+ });
+});
diff --git a/tests/api/oauth-token.test.js b/tests/api/oauth-token.test.js
new file mode 100644
index 000000000..051ebf08f
--- /dev/null
+++ b/tests/api/oauth-token.test.js
@@ -0,0 +1,458 @@
+// Tests for /api/oauth/token — OAuth 2.1 token endpoint.
+// Focus: authorization_code grant + PKCE verification, refresh_token rotation
+// with strict scope-narrowing, client authentication, and reuse detection.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+process.env.JWT_SECRET ||= 'test-secret-token-suite-only';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ const next = sqlState.queue.shift();
+ if (next instanceof Error) throw next;
+ return next;
+ }),
+}));
+
+const rlState = { success: true };
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { oauthToken: vi.fn(async () => ({ success: rlState.success })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const authState = {
+ mintAccess: vi.fn(async ({ scope }) => `access.${scope.replaceAll(' ', '+')}.jwt`),
+ issueRefresh: vi.fn(async ({ scope }) => ({
+ token: `refresh.${scope.replaceAll(' ', '+')}`,
+ id: 'rt-id',
+ })),
+ rotate: null,
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ mintAccessToken: (...args) => authState.mintAccess(...args),
+ issueRefreshToken: (...args) => authState.issueRefresh(...args),
+ rotateRefreshToken: (...args) => authState.rotate(...args),
+}));
+
+const cryptoState = {
+ // PKCE: handler computes sha256Base64Url(verifier) and compares against
+ // the stored code_challenge. Tests can set what the mock returns.
+ pkceComputed: 'EXPECTED_CHALLENGE',
+ sha256: vi.fn(async (s) => `hash:${s}`),
+ constTimeEqual: true,
+};
+
+vi.mock('../../api/_lib/crypto.js', () => ({
+ sha256: (...args) => cryptoState.sha256(...args),
+ sha256Base64Url: vi.fn(async () => cryptoState.pkceComputed),
+ constantTimeEquals: vi.fn(() => cryptoState.constTimeEqual),
+}));
+
+const { default: handler } = await import('../../api/oauth/token.js');
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function makeReq({ method = 'POST', headers = {}, formBody = {} } = {}) {
+ const base = Readable.from([Buffer.from(new URLSearchParams(formBody).toString())]);
+ base.method = method;
+ base.url = '/api/oauth/token';
+ base.headers = {
+ host: 'app.test',
+ 'content-type': 'application/x-www-form-urlencoded',
+ ...headers,
+ };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ const json = res.body ? safeJson(res.body) : null;
+ return { res, status: res.statusCode, body: json };
+}
+
+function safeJson(s) {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return s;
+ }
+}
+
+const PUBLIC_CLIENT = {
+ client_id: 'mcp_pub',
+ client_type: 'public',
+ scope: 'avatars:read avatars:write profile offline_access',
+ grant_types: ['authorization_code', 'refresh_token'],
+};
+
+const CONFIDENTIAL_CLIENT = {
+ client_id: 'mcp_conf',
+ client_type: 'confidential',
+ client_secret_hash: 'hash:secret123',
+ scope: 'avatars:read profile',
+ grant_types: ['authorization_code', 'refresh_token'],
+};
+
+const FUTURE = new Date(Date.now() + 60_000).toISOString();
+const PAST = new Date(Date.now() - 60_000).toISOString();
+
+const AUTH_CODE_ROW = {
+ code: 'auth-code-1',
+ client_id: 'mcp_pub',
+ user_id: 'user-1',
+ redirect_uri: 'https://client.test/cb',
+ scope: 'avatars:read profile',
+ resource: 'https://app.test/api/mcp',
+ code_challenge: 'EXPECTED_CHALLENGE',
+ code_challenge_method: 'S256',
+ expires_at: FUTURE,
+ consumed_at: null,
+};
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rlState.success = true;
+ cryptoState.pkceComputed = 'EXPECTED_CHALLENGE';
+ cryptoState.constTimeEqual = true;
+ authState.mintAccess.mockClear();
+ authState.issueRefresh.mockClear();
+ authState.rotate = vi.fn();
+});
+
+// ── Method / preflight ────────────────────────────────────────────────────
+
+describe('/api/oauth/token — method handling', () => {
+ it('returns 405 for GET', async () => {
+ const req = makeReq({ method: 'GET' });
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('returns 204 for OPTIONS preflight', async () => {
+ const req = makeReq({ method: 'OPTIONS' });
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(204);
+ });
+});
+
+// ── Client identification + authentication ────────────────────────────────
+
+describe('/api/oauth/token — client auth', () => {
+ it('returns invalid_client when client_id missing', async () => {
+ const { status, body } = await invoke({ formBody: { grant_type: 'authorization_code' } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_client');
+ });
+
+ it('rate-limits per client_id', async () => {
+ rlState.success = false;
+ const { status, body } = await invoke({
+ formBody: { client_id: 'mcp_pub', grant_type: 'authorization_code' },
+ });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+
+ it('returns invalid_client when client unknown in DB', async () => {
+ sqlState.queue.push([]); // client lookup empty
+ const { status, body } = await invoke({
+ formBody: { client_id: 'mcp_unknown', grant_type: 'authorization_code' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_client');
+ });
+
+ it('rejects confidential client with bad secret', async () => {
+ sqlState.queue.push([CONFIDENTIAL_CLIENT]);
+ cryptoState.constTimeEqual = false;
+ const { status, body } = await invoke({
+ formBody: {
+ client_id: 'mcp_conf',
+ client_secret: 'wrong',
+ grant_type: 'authorization_code',
+ },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('invalid_client');
+ });
+
+ it('accepts confidential client secret via HTTP Basic auth header', async () => {
+ sqlState.queue.push([CONFIDENTIAL_CLIENT]);
+ cryptoState.constTimeEqual = true;
+ // Then the unsupported_grant_type path so we don't have to fully wire auth_code.
+ const basic = 'Basic ' + Buffer.from('mcp_conf:secret123').toString('base64');
+ const { status, body } = await invoke({
+ headers: { authorization: basic },
+ formBody: { grant_type: 'unsupported_grant' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('unsupported_grant_type');
+ });
+});
+
+// ── grant_type routing ────────────────────────────────────────────────────
+
+describe('/api/oauth/token — grant_type routing', () => {
+ it('rejects unknown grant_type', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ const { status, body } = await invoke({
+ formBody: { client_id: 'mcp_pub', grant_type: 'password' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('unsupported_grant_type');
+ });
+});
+
+// ── authorization_code grant ──────────────────────────────────────────────
+
+describe('/api/oauth/token — authorization_code grant', () => {
+ const baseForm = {
+ client_id: 'mcp_pub',
+ grant_type: 'authorization_code',
+ code: 'auth-code-1',
+ redirect_uri: 'https://client.test/cb',
+ code_verifier: 'verifier-string',
+ };
+
+ it('rejects when required fields missing', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ const { code_verifier: _drop, ...withoutVerifier } = baseForm;
+ const { status, body } = await invoke({ formBody: withoutVerifier });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_request');
+ });
+
+ it('rejects unknown auth code', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([]); // no code row
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_grant');
+ expect(body.error_description).toMatch(/unknown code/);
+ });
+
+ it('rejects already-consumed code AND revokes refresh tokens (replay defence)', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([{ ...AUTH_CODE_ROW, consumed_at: PAST }]);
+ sqlState.queue.push([]); // revoke update
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_grant');
+ const revoke = sqlState.calls.find((c) =>
+ /update oauth_refresh_tokens set revoked_at/i.test(c.query),
+ );
+ expect(revoke).toBeTruthy();
+ });
+
+ it('rejects expired code', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([{ ...AUTH_CODE_ROW, expires_at: PAST }]);
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/expired/);
+ });
+
+ it('rejects code issued to different client', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([{ ...AUTH_CODE_ROW, client_id: 'mcp_other' }]);
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/client mismatch/);
+ });
+
+ it('rejects redirect_uri mismatch', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([AUTH_CODE_ROW]);
+ const { status, body } = await invoke({
+ formBody: { ...baseForm, redirect_uri: 'https://client.test/other' },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/redirect_uri mismatch/);
+ });
+
+ it('rejects when PKCE verifier does not hash to stored challenge', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ sqlState.queue.push([AUTH_CODE_ROW]);
+ cryptoState.pkceComputed = 'WRONG_HASH';
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/PKCE verification failed/);
+ });
+
+ it('issues access + refresh on success and consumes the auth code', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]); // client
+ sqlState.queue.push([AUTH_CODE_ROW]); // code lookup
+ sqlState.queue.push([]); // mark code consumed
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(200);
+ expect(body.token_type).toBe('Bearer');
+ expect(body.expires_in).toBe(3600);
+ expect(body.scope).toBe('avatars:read profile');
+ expect(body.access_token).toContain('access.');
+ expect(body.refresh_token).toContain('refresh.');
+ // Code marked consumed.
+ const consume = sqlState.calls.find((c) =>
+ /update oauth_auth_codes set consumed_at/i.test(c.query),
+ );
+ expect(consume).toBeTruthy();
+ // Access token minted with the code's scope and resource.
+ expect(authState.mintAccess).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: 'user-1',
+ clientId: 'mcp_pub',
+ scope: 'avatars:read profile',
+ }),
+ );
+ });
+
+ it('omits refresh_token when client lacks refresh_token grant', async () => {
+ const noRefresh = { ...PUBLIC_CLIENT, grant_types: ['authorization_code'] };
+ sqlState.queue.push([noRefresh]);
+ sqlState.queue.push([AUTH_CODE_ROW]);
+ sqlState.queue.push([]);
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(200);
+ expect(body.refresh_token).toBeUndefined();
+ expect(authState.issueRefresh).not.toHaveBeenCalled();
+ });
+});
+
+// ── refresh_token grant ───────────────────────────────────────────────────
+
+describe('/api/oauth/token — refresh_token grant', () => {
+ const baseForm = {
+ client_id: 'mcp_pub',
+ grant_type: 'refresh_token',
+ refresh_token: 'old-refresh-secret',
+ };
+
+ it('rejects missing refresh_token', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ const { status, body } = await invoke({
+ formBody: { client_id: 'mcp_pub', grant_type: 'refresh_token' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_request');
+ });
+
+ it('issues a new access+refresh on successful rotation (no scope narrowing)', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.rotate = vi.fn(async ({ narrowScope }) => {
+ // Caller did not pass scope → narrowScope("stored") returns stored unchanged.
+ const eff = narrowScope('avatars:read profile');
+ return {
+ userId: 'user-1',
+ scope: eff,
+ resource: 'https://app.test/api/mcp',
+ next: { token: 'rotated-refresh', id: 'rt-2' },
+ };
+ });
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(200);
+ expect(body.scope).toBe('avatars:read profile');
+ expect(body.refresh_token).toBe('rotated-refresh');
+ expect(body.access_token).toContain('access.');
+ });
+
+ it('narrows scope when caller requests a strict subset', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.rotate = vi.fn(async ({ narrowScope }) => {
+ const eff = narrowScope('avatars:read profile');
+ return {
+ userId: 'user-1',
+ scope: eff,
+ resource: null,
+ next: { token: 'narrowed-refresh', id: 'rt-3' },
+ };
+ });
+ const { status, body } = await invoke({
+ formBody: { ...baseForm, scope: 'avatars:read' },
+ });
+ expect(status).toBe(200);
+ expect(body.scope).toBe('avatars:read');
+ });
+
+ it('rejects scope-widening attempt (requested scope not subset of stored)', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ // Simulate the handler calling narrowScope and the function throwing
+ // invalid_scope, which the handler converts into the JSON error below.
+ authState.rotate = vi.fn(async ({ narrowScope }) => {
+ narrowScope('avatars:read profile'); // throws
+ });
+ const { status, body } = await invoke({
+ formBody: { ...baseForm, scope: 'avatars:read avatars:delete' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_scope');
+ expect(body.error_description).toMatch(/exceeds granted scope/);
+ });
+
+ it('rejects empty scope subset (asks for nothing while sending scope param)', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.rotate = vi.fn(async ({ narrowScope }) => {
+ narrowScope('avatars:read profile'); // throws — '' is not a subset
+ });
+ const { status, body } = await invoke({
+ formBody: { ...baseForm, scope: 'unknown:scope' },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_scope');
+ });
+
+ it('propagates invalid_grant from rotation (e.g. revoked / unknown token)', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.rotate = vi.fn(async () => {
+ throw Object.assign(new Error('invalid_grant'), { status: 400 });
+ });
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_grant');
+ });
+
+ it('propagates refresh_reuse_detected (chain revoked) from rotation', async () => {
+ sqlState.queue.push([PUBLIC_CLIENT]);
+ authState.rotate = vi.fn(async () => {
+ throw Object.assign(new Error('reuse'), {
+ status: 400,
+ code: 'refresh_reuse_detected',
+ });
+ });
+ const { status, body } = await invoke({ formBody: baseForm });
+ expect(status).toBe(400);
+ expect(body.error).toBe('refresh_reuse_detected');
+ });
+});
diff --git a/tests/api/validate.test.js b/tests/api/validate.test.js
index 89b1c64ce..42da24fb1 100644
--- a/tests/api/validate.test.js
+++ b/tests/api/validate.test.js
@@ -135,7 +135,10 @@ describe('username schema', () => {
describe('registerBody schema', () => {
it('accepts valid registration body', () => {
- const result = registerBody.parse({ email: '[email protected]', password: 'securepassword1' });
+ const result = registerBody.parse({
+ email: '[email protected]',
+ password: 'securepassword1',
+ });
expect(result.email).toBe('[email protected]');
expect(result.password).toBe('securepassword1');
});
@@ -178,13 +181,13 @@ describe('createAvatarBody schema', () => {
});
it('rejects size_bytes over 500MB', () => {
- expect(() => createAvatarBody.parse({ ...base, size_bytes: 500 * 1024 * 1024 + 1 })).toThrow();
+ expect(() =>
+ createAvatarBody.parse({ ...base, size_bytes: 500 * 1024 * 1024 + 1 }),
+ ).toThrow();
});
it('rejects invalid checksum format', () => {
- expect(() =>
- createAvatarBody.parse({ ...base, checksum_sha256: 'not-a-hash' }),
- ).toThrow();
+ expect(() => createAvatarBody.parse({ ...base, checksum_sha256: 'not-a-hash' })).toThrow();
});
it('accepts valid 64-char hex checksum', () => {
diff --git a/tests/src/animation-slots.test.js b/tests/src/animation-slots.test.js
index c77c66543..9f77bcfd6 100644
--- a/tests/src/animation-slots.test.js
+++ b/tests/src/animation-slots.test.js
@@ -8,7 +8,18 @@ describe('SLOTS', () => {
});
it('contains expected slot names', () => {
- const expected = ['idle', 'wave', 'nod', 'shake', 'think', 'celebrate', 'concern', 'bow', 'point', 'shrug'];
+ const expected = [
+ 'idle',
+ 'wave',
+ 'nod',
+ 'shake',
+ 'think',
+ 'celebrate',
+ 'concern',
+ 'bow',
+ 'point',
+ 'shrug',
+ ];
expect(SLOTS).toEqual(expected);
});
diff --git a/tests/src/manifest-normalize.test.js b/tests/src/manifest-normalize.test.js
new file mode 100644
index 000000000..0720bca5b
--- /dev/null
+++ b/tests/src/manifest-normalize.test.js
@@ -0,0 +1,197 @@
+import { describe, it, expect } from 'vitest';
+import { normalize } from '../../src/manifest.js';
+
+describe('normalize — full AGENT_MANIFEST', () => {
+ it('passes through a manifest whose spec is agent-manifest/0.1', () => {
+ const json = {
+ spec: 'agent-manifest/0.1',
+ name: 'Ada',
+ body: { uri: 'model.glb', format: 'gltf-binary' },
+ brain: { provider: 'anthropic' },
+ };
+ const m = normalize(json, { baseURI: 'https://example.com/' });
+ expect(m.spec).toBe('agent-manifest/0.1');
+ expect(m.name).toBe('Ada');
+ expect(m._baseURI).toBe('https://example.com/');
+ expect(m.body.uri).toBe('model.glb');
+ });
+
+ it('accepts any agent-manifest/* version prefix', () => {
+ const json = { spec: 'agent-manifest/0.9', name: 'X' };
+ const m = normalize(json);
+ expect(m.spec).toBe('agent-manifest/0.9');
+ });
+
+ it('defaults empty body and backfills body.uri from image', () => {
+ const json = {
+ spec: 'agent-manifest/0.1',
+ name: 'A',
+ image: 'https://example.com/ada.glb',
+ };
+ const m = normalize(json);
+ expect(m.body.uri).toBe('https://example.com/ada.glb');
+ });
+
+ it('does not overwrite body.uri when already set', () => {
+ const json = {
+ spec: 'agent-manifest/0.1',
+ name: 'A',
+ image: 'https://example.com/thumb.png',
+ body: { uri: 'model.glb' },
+ };
+ const m = normalize(json);
+ expect(m.body.uri).toBe('model.glb');
+ });
+
+ it('defaults baseURI to empty string when not passed', () => {
+ const m = normalize({ spec: 'agent-manifest/0.1', name: 'A' });
+ expect(m._baseURI).toBe('');
+ });
+});
+
+describe('normalize — ERC-8004 registration JSON', () => {
+ it('adapts eip-8004 type into a manifest', () => {
+ const json = {
+ type: ['eip-8004', 'agent-registration'],
+ name: 'Bob',
+ description: 'a bot',
+ image: 'https://example.com/thumb.png',
+ registrations: [{ agentId: 42 }],
+ services: [{ name: 'something', uri: 'x' }],
+ };
+ const m = normalize(json);
+ expect(m.spec).toBe('agent-manifest/0.1');
+ expect(m._source).toBe('erc8004-registration');
+ expect(m.name).toBe('Bob');
+ expect(m.description).toBe('a bot');
+ expect(m.id.agentId).toBe('42');
+ expect(m.brain.provider).toBe('none');
+ expect(m.memory.mode).toBe('local');
+ expect(m.tools).toEqual(['wave', 'lookAt', 'play_clip', 'setExpression']);
+ expect(m.services).toEqual([{ name: 'something', uri: 'x' }]);
+ });
+
+ it('prefers avatar3D service URI over top-level image for body.uri', () => {
+ const json = {
+ type: ['eip-8004'],
+ name: 'C',
+ image: 'https://example.com/thumb.png',
+ registrations: [{ agentId: 1 }],
+ services: [
+ {
+ name: 'avatar',
+ type: 'avatar-3d',
+ endpoint: 'https://example.com/ada.glb',
+ },
+ ],
+ };
+ const m = normalize(json);
+ expect(m.body.uri).toBe('https://example.com/ada.glb');
+ });
+
+ it('falls back to image when no 3D avatar service declared', () => {
+ const json = {
+ type: ['eip-8004'],
+ name: 'D',
+ image: 'https://example.com/thumb.png',
+ registrations: [{ agentId: 2 }],
+ services: [],
+ };
+ const m = normalize(json);
+ // image may itself be a 2D thumbnail; we still use it as the last-resort
+ // body URI so the viewer has something to try.
+ expect(m.body.uri).toBe('https://example.com/thumb.png');
+ });
+
+ it('coerces registrations array missing to empty-id result', () => {
+ const json = {
+ type: ['eip-8004'],
+ name: 'E',
+ image: '',
+ };
+ const m = normalize(json);
+ expect(m.id.agentId).toBeUndefined();
+ });
+
+ it('preserves x402Support and embedPolicy passthroughs', () => {
+ const json = {
+ type: ['eip-8004'],
+ name: 'F',
+ registrations: [{ agentId: 1 }],
+ x402Support: true,
+ embedPolicy: { allowOrigins: ['https://good.example'] },
+ };
+ const m = normalize(json);
+ expect(m.x402Support).toBe(true);
+ expect(m.embedPolicy).toEqual({ allowOrigins: ['https://good.example'] });
+ });
+
+ it('defaults services to empty array when not an array', () => {
+ const json = {
+ type: ['eip-8004'],
+ name: 'G',
+ registrations: [{ agentId: 1 }],
+ services: 'not-an-array',
+ };
+ const m = normalize(json);
+ expect(m.services).toEqual([]);
+ });
+
+ it('resolves ipfs:// URI on the avatar body', () => {
+ const json = {
+ type: ['eip-8004'],
+ name: 'H',
+ registrations: [{ agentId: 1 }],
+ services: [
+ {
+ name: 'avatar',
+ type: 'avatar-3d',
+ endpoint: 'ipfs://QmTestCID',
+ },
+ ],
+ };
+ const m = normalize(json);
+ expect(m.body.uri).toMatch(/^https:\/\/.+\/ipfs\/QmTestCID$/);
+ });
+});
+
+describe('normalize — unknown / partial JSON (best effort)', () => {
+ it('returns a manifest shape with safe defaults', () => {
+ const m = normalize({});
+ expect(m.spec).toBe('agent-manifest/0.1');
+ expect(m.name).toBe('Unnamed agent');
+ expect(m.description).toBe('');
+ expect(m.body.uri).toBe('');
+ expect(m.body.format).toBe('gltf-binary');
+ expect(m.brain).toEqual({ provider: 'none' });
+ expect(m.memory).toEqual({ mode: 'local' });
+ expect(m.tools).toEqual(['wave', 'lookAt', 'play_clip', 'setExpression']);
+ expect(m.version).toBe('0.1.0');
+ });
+
+ it('uses json.model when body.uri missing', () => {
+ const m = normalize({ model: 'custom.glb' });
+ expect(m.body.uri).toBe('custom.glb');
+ });
+
+ it('prefers body.uri over json.image and json.model', () => {
+ const m = normalize({
+ body: { uri: 'body.glb' },
+ image: 'image.glb',
+ model: 'model.glb',
+ });
+ expect(m.body.uri).toBe('body.glb');
+ });
+
+ it('passes through custom skills/tools/version', () => {
+ const m = normalize({
+ name: 'Custom',
+ skills: [{ name: 'greet' }],
+ tools: ['wave'],
+ version: '2.0.0',
+ });
+ expect(m.skills).toEqual([{ name: 'greet' }]);
+ expect(m.tools).toEqual(['wave']);
+ expect(m.version).toBe('2.0.0');
+ });
+});
diff --git a/tests/src/manifest.test.js b/tests/src/manifest.test.js
new file mode 100644
index 000000000..72907a2d6
--- /dev/null
+++ b/tests/src/manifest.test.js
@@ -0,0 +1,227 @@
+import { describe, it, expect } from 'vitest';
+import { normalize } from '../../src/manifest.js';
+
+describe('normalize — full agent-manifest', () => {
+ it('preserves manifest fields and stamps _baseURI', () => {
+ const input = {
+ spec: 'agent-manifest/0.1',
+ name: 'Nich',
+ description: 'a friend',
+ body: { uri: 'avatar.glb', format: 'gltf-binary' },
+ brain: { provider: 'anthropic' },
+ };
+ const m = normalize(input, { baseURI: 'https://example.com/agents/nich/' });
+ expect(m.spec).toBe('agent-manifest/0.1');
+ expect(m.name).toBe('Nich');
+ expect(m._baseURI).toBe('https://example.com/agents/nich/');
+ expect(m.body.uri).toBe('avatar.glb');
+ expect(m.brain.provider).toBe('anthropic');
+ });
+
+ it('fills body.uri from top-level image when body.uri is missing', () => {
+ const input = {
+ spec: 'agent-manifest/0.1',
+ name: 'Nich',
+ image: 'thumbnail.glb',
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.body.uri).toBe('thumbnail.glb');
+ });
+
+ it('does not overwrite existing body.uri with image', () => {
+ const input = {
+ spec: 'agent-manifest/0.1',
+ image: 'thumb.glb',
+ body: { uri: 'avatar.glb' },
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.body.uri).toBe('avatar.glb');
+ });
+
+ it('defaults baseURI to empty string when not provided', () => {
+ const input = { spec: 'agent-manifest/0.1', name: 'x' };
+ const m = normalize(input);
+ expect(m._baseURI).toBe('');
+ });
+
+ it('accepts spec prefix agent-manifest/ with any version suffix', () => {
+ const input = { spec: 'agent-manifest/0.99', name: 'future' };
+ const m = normalize(input, { baseURI: 'x' });
+ expect(m.name).toBe('future');
+ });
+});
+
+describe('normalize — ERC-8004 registration', () => {
+ it('adapts eip-8004 registration JSON to manifest shape', () => {
+ const input = {
+ type: ['AgentRegistration', 'eip-8004'],
+ name: 'OnChainBot',
+ description: 'registered agent',
+ image: 'https://example.com/thumb.png',
+ registrations: [{ agentId: '42' }],
+ services: [
+ {
+ name: 'avatar',
+ type: 'service/avatar/3d+gltf',
+ endpoint: 'https://cdn.example/bot.glb',
+ },
+ ],
+ };
+ const m = normalize(input, { baseURI: 'https://example.com/' });
+ expect(m.spec).toBe('agent-manifest/0.1');
+ expect(m._source).toBe('erc8004-registration');
+ expect(m.id.agentId).toBe('42');
+ expect(m.name).toBe('OnChainBot');
+ expect(m.body.uri).toBe('https://cdn.example/bot.glb');
+ expect(m.body.format).toBe('gltf-binary');
+ expect(m.brain.provider).toBe('none');
+ expect(m.memory.mode).toBe('local');
+ expect(m.tools).toContain('wave');
+ });
+
+ it('falls back to image when no avatar service declared', () => {
+ const input = {
+ type: ['eip-8004'],
+ name: 'NoAvatar',
+ image: 'https://example.com/fallback.glb',
+ registrations: [{ agentId: '1' }],
+ services: [],
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.body.uri).toBe('https://example.com/fallback.glb');
+ });
+
+ it('coerces agentId to string', () => {
+ const input = {
+ type: ['eip-8004'],
+ registrations: [{ agentId: 123 }],
+ image: 'x',
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(typeof m.id.agentId).toBe('string');
+ expect(m.id.agentId).toBe('123');
+ });
+
+ it('handles missing registrations array', () => {
+ const input = { type: ['eip-8004'], image: 'x' };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.id.agentId).toBeUndefined();
+ });
+
+ it('preserves services array', () => {
+ const svcs = [
+ { name: 'avatar', endpoint: 'https://a.glb' },
+ { name: 'chat', endpoint: 'https://chat' },
+ ];
+ const input = {
+ type: ['eip-8004'],
+ registrations: [{ agentId: '1' }],
+ image: 'x',
+ services: svcs,
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.services).toEqual(svcs);
+ });
+
+ it('defaults services to empty array when not provided', () => {
+ const input = { type: ['eip-8004'], registrations: [{ agentId: '1' }], image: 'x' };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.services).toEqual([]);
+ });
+
+ it('defaults services to empty array when not an array', () => {
+ const input = {
+ type: ['eip-8004'],
+ registrations: [{ agentId: '1' }],
+ image: 'x',
+ services: 'not-an-array',
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.services).toEqual([]);
+ });
+
+ it('coerces x402Support to boolean', () => {
+ const trueCase = normalize(
+ {
+ type: ['eip-8004'],
+ registrations: [{ agentId: '1' }],
+ image: 'x',
+ x402Support: { version: 1 },
+ },
+ { baseURI: '' },
+ );
+ expect(trueCase.x402Support).toBe(true);
+
+ const falseCase = normalize(
+ { type: ['eip-8004'], registrations: [{ agentId: '1' }], image: 'x' },
+ { baseURI: '' },
+ );
+ expect(falseCase.x402Support).toBe(false);
+ });
+
+ it('preserves embedPolicy when provided', () => {
+ const policy = { allowedOrigins: ['*'] };
+ const m = normalize(
+ {
+ type: ['eip-8004'],
+ registrations: [{ agentId: '1' }],
+ image: 'x',
+ embedPolicy: policy,
+ },
+ { baseURI: '' },
+ );
+ expect(m.embedPolicy).toEqual(policy);
+ });
+
+ it('defaults embedPolicy to null', () => {
+ const m = normalize(
+ { type: ['eip-8004'], registrations: [{ agentId: '1' }], image: 'x' },
+ { baseURI: '' },
+ );
+ expect(m.embedPolicy).toBeNull();
+ });
+
+ it('resolves ipfs:// URI in body.uri', () => {
+ const input = {
+ type: ['eip-8004'],
+ registrations: [{ agentId: '1' }],
+ image: 'ipfs://bafkrei123',
+ };
+ const m = normalize(input, { baseURI: '' });
+ expect(m.body.uri).toMatch(/^https:\/\//);
+ expect(m.body.uri).toContain('bafkrei123');
+ });
+});
+
+describe('normalize — fallback / unknown input', () => {
+ it('produces a best-effort manifest from minimal input', () => {
+ const m = normalize({ name: 'Mystery' }, { baseURI: '' });
+ expect(m.spec).toBe('agent-manifest/0.1');
+ expect(m.name).toBe('Mystery');
+ expect(m.body.format).toBe('gltf-binary');
+ expect(m.brain).toEqual({ provider: 'none' });
+ expect(m.memory).toEqual({ mode: 'local' });
+ expect(m.version).toBe('0.1.0');
+ });
+
+ it('uses body.uri, image, or model as fallback hierarchy', () => {
+ expect(normalize({ body: { uri: 'a.glb' } }).body.uri).toBe('a.glb');
+ expect(normalize({ image: 'b.glb' }).body.uri).toBe('b.glb');
+ expect(normalize({ model: 'c.glb' }).body.uri).toBe('c.glb');
+ });
+
+ it('supplies defaults for missing optional fields', () => {
+ const m = normalize({}, { baseURI: '' });
+ expect(m.name).toBe('Unnamed agent');
+ expect(m.description).toBe('');
+ expect(m.body.uri).toBe('');
+ expect(Array.isArray(m.skills)).toBe(true);
+ expect(m.tools).toContain('play_clip');
+ });
+
+ it('preserves user-provided brain config', () => {
+ const m = normalize({ brain: { provider: 'anthropic', model: 'claude-x' } }, { baseURI: '' });
+ expect(m.brain.provider).toBe('anthropic');
+ expect(m.brain.model).toBe('claude-x');
+ });
+});
diff --git a/tests/src/validator.test.js b/tests/src/validator.test.js
new file mode 100644
index 000000000..f763f0a27
--- /dev/null
+++ b/tests/src/validator.test.js
@@ -0,0 +1,262 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+
+// We test `setReport` and `setResponse` in isolation. They are pure given input.
+// `validate()` itself requires browser APIs (fetch, THREE.Cache) — out of scope here.
+
+// Import by patching out the browser-only bits. `validator.js` imports
+// `three` and `gltf-validator` at module-load; those have no side effects in node.
+import { Validator } from '../../src/validator.js';
+
+function makeReport({
+ errors = [],
+ warnings = [],
+ infos = [],
+ hints = [],
+ generator = 'test-gen 1.0',
+} = {}) {
+ const messages = [
+ ...errors.map((m) => ({ severity: 0, ...m })),
+ ...warnings.map((m) => ({ severity: 1, ...m })),
+ ...infos.map((m) => ({ severity: 2, ...m })),
+ ...hints.map((m) => ({ severity: 3, ...m })),
+ ];
+ return {
+ info: { generator },
+ issues: {
+ numErrors: errors.length,
+ numWarnings: warnings.length,
+ numInfos: infos.length,
+ numHints: hints.length,
+ messages,
+ maxSeverity: -1,
+ },
+ };
+}
+
+describe('Validator.setReport', () => {
+ let validator;
+
+ beforeEach(() => {
+ validator = new Validator(null);
+ });
+
+ it('splits messages by severity', () => {
+ const report = makeReport({
+ errors: [{ code: 'E1', message: 'err', pointer: '/a' }],
+ warnings: [{ code: 'W1', message: 'warn', pointer: '/b' }],
+ infos: [{ code: 'I1', message: 'info', pointer: '/c' }],
+ hints: [{ code: 'H1', message: 'hint', pointer: '/d' }],
+ });
+
+ validator.setReport(report, null);
+
+ expect(validator.report.errors).toHaveLength(1);
+ expect(validator.report.warnings).toHaveLength(1);
+ expect(validator.report.infos).toHaveLength(1);
+ expect(validator.report.hints).toHaveLength(1);
+ });
+
+ it('sets maxSeverity to the most severe non-empty level', () => {
+ const onlyHints = makeReport({ hints: [{ code: 'H1', message: 'h', pointer: '' }] });
+ validator.setReport(onlyHints, null);
+ expect(validator.report.issues.maxSeverity).toBe(3);
+
+ const withWarning = makeReport({
+ warnings: [{ code: 'W1', message: 'w', pointer: '' }],
+ hints: [{ code: 'H1', message: 'h', pointer: '' }],
+ });
+ validator.setReport(withWarning, null);
+ expect(validator.report.issues.maxSeverity).toBe(1);
+
+ const withError = makeReport({
+ errors: [{ code: 'E1', message: 'e', pointer: '' }],
+ warnings: [{ code: 'W1', message: 'w', pointer: '' }],
+ });
+ validator.setReport(withError, null);
+ expect(validator.report.issues.maxSeverity).toBe(0);
+ });
+
+ it('leaves maxSeverity at -1 when there are no issues', () => {
+ const clean = makeReport();
+ validator.setReport(clean, null);
+ expect(validator.report.issues.maxSeverity).toBe(-1);
+ });
+
+ it('copies generator onto the report', () => {
+ const report = makeReport({ generator: 'Blender 4.0' });
+ validator.setReport(report, null);
+ expect(validator.report.generator).toBe('Blender 4.0');
+ });
+
+ it('uses empty string when info.generator is missing', () => {
+ const report = { info: {}, issues: { numErrors: 0, numWarnings: 0, numInfos: 0, numHints: 0, messages: [], maxSeverity: -1 } };
+ validator.setReport(report, null);
+ expect(validator.report.generator).toBe('');
+ });
+
+ it('aggregates multiple ACCESSOR_NON_UNIT errors on the same pointer', () => {
+ const report = makeReport({
+ errors: [
+ { code: 'ACCESSOR_NON_UNIT', message: 'not unit', pointer: '/meshes/0' },
+ { code: 'ACCESSOR_NON_UNIT', message: 'not unit', pointer: '/meshes/0' },
+ { code: 'ACCESSOR_NON_UNIT', message: 'not unit', pointer: '/meshes/0' },
+ ],
+ });
+ validator.setReport(report, null);
+
+ expect(validator.report.errors).toHaveLength(1);
+ const [aggregated] = validator.report.errors;
+ expect(aggregated.code).toBe('ACCESSOR_NON_UNIT');
+ expect(aggregated.pointer).toBe('/meshes/0');
+ expect(aggregated.message).toMatch(/3 accessor elements/);
+ expect(aggregated.message).toMatch(/\[AGGREGATED\]/);
+ });
+
+ it('aggregates per pointer independently when one pointer repeats', () => {
+ const report = makeReport({
+ errors: [
+ { code: 'ACCESSOR_NON_UNIT', message: 'not unit', pointer: '/meshes/0' },
+ { code: 'ACCESSOR_NON_UNIT', message: 'not unit', pointer: '/meshes/0' },
+ { code: 'ACCESSOR_NON_UNIT', message: 'not unit', pointer: '/meshes/1' },
+ ],
+ });
+ validator.setReport(report, null);
+ // /meshes/0 occurs twice → one aggregated entry replaces the two originals.
+ // /meshes/1 occurs once → the original is kept as-is, no aggregation.
+ const aggregated = validator.report.errors.filter((e) => /\[AGGREGATED\]/.test(e.message));
+ expect(aggregated).toHaveLength(1);
+ expect(aggregated[0].pointer).toBe('/meshes/0');
+ expect(aggregated[0].message).toMatch(/2 accessor elements/);
+ const singles = validator.report.errors.filter((e) => !/\[AGGREGATED\]/.test(e.message));
+ expect(singles).toHaveLength(1);
+ expect(singles[0].pointer).toBe('/meshes/1');
+ });
+
+ it('aggregates ACCESSOR_ANIMATION_INPUT_NON_INCREASING', () => {
+ const report = makeReport({
+ errors: [
+ { code: 'ACCESSOR_ANIMATION_INPUT_NON_INCREASING', message: 'bad', pointer: '/a' },
+ { code: 'ACCESSOR_ANIMATION_INPUT_NON_INCREASING', message: 'bad', pointer: '/a' },
+ { code: 'ACCESSOR_ANIMATION_INPUT_NON_INCREASING', message: 'bad', pointer: '/a' },
+ ],
+ });
+ validator.setReport(report, null);
+ expect(validator.report.errors).toHaveLength(1);
+ expect(validator.report.errors[0].message).toMatch(/3 animation input/);
+ });
+
+ it('leaves unaggregated error codes untouched', () => {
+ const report = makeReport({
+ errors: [
+ { code: 'SOME_OTHER_CODE', message: 'x', pointer: '/a' },
+ { code: 'SOME_OTHER_CODE', message: 'x', pointer: '/a' },
+ ],
+ });
+ validator.setReport(report, null);
+ expect(validator.report.errors).toHaveLength(2);
+ });
+});
+
+describe('Validator.setResponse', () => {
+ let validator;
+
+ beforeEach(() => {
+ validator = new Validator(null);
+ validator.setReport(
+ {
+ info: { generator: 'x' },
+ issues: { numErrors: 0, numWarnings: 0, numInfos: 0, numHints: 0, messages: [], maxSeverity: -1 },
+ },
+ null,
+ );
+ });
+
+ it('no-ops when response is falsy', () => {
+ validator.setResponse(null);
+ expect(validator.report.info.extras).toBeUndefined();
+ });
+
+ it('no-ops when parser json is missing', () => {
+ validator.setResponse({ parser: {} });
+ expect(validator.report.info.extras).toBeUndefined();
+ });
+
+ it('extracts asset extras when present', () => {
+ const response = {
+ parser: {
+ json: {
+ asset: {
+ extras: {
+ author: 'Jane',
+ license: 'CC-BY',
+ source: 'https://example.com/',
+ title: 'My Model',
+ },
+ },
+ },
+ },
+ };
+ validator.setResponse(response);
+ expect(validator.report.info.extras.title).toBe('My Model');
+ expect(validator.report.info.extras.author).toBe('Jane');
+ expect(validator.report.info.extras.license).toBe('CC-BY');
+ });
+
+ it('escapes HTML-unsafe characters in extras', () => {
+ const response = {
+ parser: {
+ json: {
+ asset: {
+ extras: { author: '<script>alert(1)</script>' },
+ },
+ },
+ },
+ };
+ validator.setResponse(response);
+ expect(validator.report.info.extras.author).not.toMatch(/<script>/);
+ expect(validator.report.info.extras.author).toMatch(/&lt;script&gt;/);
+ });
+
+ it('linkifies URLs in extras', () => {
+ const response = {
+ parser: {
+ json: {
+ asset: {
+ extras: { source: 'See https://example.com/asset for more.' },
+ },
+ },
+ },
+ };
+ validator.setResponse(response);
+ expect(validator.report.info.extras.source).toMatch(
+ /<a[^>]+href="https:\/\/example\.com\/asset"/,
+ );
+ });
+
+ it('linkifies email addresses', () => {
+ const response = {
+ parser: {
+ json: {
+ asset: { extras: { author: 'Jane Doe <[email protected]>' } },
+ },
+ },
+ };
+ validator.setResponse(response);
+ expect(validator.report.info.extras.author).toMatch(/href="mailto:jane@example\.com"/);
+ });
+
+ it('leaves extras undefined when asset.extras is missing', () => {
+ const response = { parser: { json: { asset: {} } } };
+ validator.setResponse(response);
+ expect(validator.report.info.extras).toBeUndefined();
+ });
+});
+
+describe('Validator.setReportException', () => {
+ it('clears the report on error', () => {
+ const validator = new Validator(null);
+ validator.report = { dummy: true };
+ validator.setReportException(new Error('boom'));
+ expect(validator.report).toBeNull();
+ });
+});
diff --git a/tests/src/widget-types.test.js b/tests/src/widget-types.test.js
new file mode 100644
index 000000000..c9a7e1c37
--- /dev/null
+++ b/tests/src/widget-types.test.js
@@ -0,0 +1,257 @@
+import { describe, it, expect } from 'vitest';
+import {
+ WIDGET_TYPES,
+ WIDGET_TYPE_KEYS,
+ BRAND_DEFAULTS,
+ defaultConfig,
+ validateConfig,
+ isReady,
+ resolveChainId,
+ chainLabel,
+ CHAIN_SLUGS,
+} from '../../src/widget-types.js';
+
+describe('WIDGET_TYPES', () => {
+ it('exposes the five known widget types', () => {
+ expect(WIDGET_TYPE_KEYS.sort()).toEqual(
+ ['turntable', 'animation-gallery', 'talking-agent', 'passport', 'hotspot-tour'].sort(),
+ );
+ });
+
+ it('every entry has label, desc, status, icon', () => {
+ for (const key of WIDGET_TYPE_KEYS) {
+ const entry = WIDGET_TYPES[key];
+ expect(typeof entry.label).toBe('string');
+ expect(typeof entry.desc).toBe('string');
+ expect(['ready', 'pending']).toContain(entry.status);
+ expect(typeof entry.icon).toBe('string');
+ }
+ });
+
+ it('BRAND_DEFAULTS is frozen', () => {
+ expect(Object.isFrozen(BRAND_DEFAULTS)).toBe(true);
+ });
+});
+
+describe('isReady', () => {
+ it('returns true for ready widgets', () => {
+ expect(isReady('turntable')).toBe(true);
+ expect(isReady('talking-agent')).toBe(true);
+ expect(isReady('passport')).toBe(true);
+ });
+
+ it('returns false for pending widgets', () => {
+ expect(isReady('hotspot-tour')).toBe(false);
+ });
+
+ it('returns false for unknown types', () => {
+ expect(isReady('bogus')).toBe(false);
+ });
+});
+
+describe('defaultConfig', () => {
+ it('merges BRAND_DEFAULTS with type defaults', () => {
+ const cfg = defaultConfig('turntable');
+ expect(cfg.background).toBe(BRAND_DEFAULTS.background);
+ expect(cfg.rotationSpeed).toBe(0.5);
+ });
+
+ it('returns hotspot-tour defaults with empty array', () => {
+ const cfg = defaultConfig('hotspot-tour');
+ expect(cfg.hotspots).toEqual([]);
+ });
+
+ it('throws on unknown type', () => {
+ expect(() => defaultConfig('unknown')).toThrow(/unknown widget type/);
+ });
+});
+
+describe('validateConfig — turntable', () => {
+ it('accepts default config', () => {
+ expect(() => validateConfig('turntable', defaultConfig('turntable'))).not.toThrow();
+ });
+
+ it('rejects rotationSpeed above 10', () => {
+ expect(() =>
+ validateConfig('turntable', { ...defaultConfig('turntable'), rotationSpeed: 11 }),
+ ).toThrow(/rotationSpeed/);
+ });
+
+ it('rejects negative rotationSpeed', () => {
+ expect(() =>
+ validateConfig('turntable', { ...defaultConfig('turntable'), rotationSpeed: -1 }),
+ ).toThrow(/rotationSpeed/);
+ });
+
+ it('rejects bad hex color', () => {
+ expect(() =>
+ validateConfig('turntable', { ...defaultConfig('turntable'), background: 'red' }),
+ ).toThrow();
+ });
+});
+
+describe('validateConfig — talking-agent', () => {
+ it('accepts default config', () => {
+ expect(() =>
+ validateConfig('talking-agent', defaultConfig('talking-agent')),
+ ).not.toThrow();
+ });
+
+ it('requires proxyURL when brainProvider is custom', () => {
+ expect(() =>
+ validateConfig('talking-agent', {
+ ...defaultConfig('talking-agent'),
+ brainProvider: 'custom',
+ proxyURL: '',
+ }),
+ ).toThrow(/proxyURL/);
+ });
+
+ it('accepts custom brainProvider with https proxyURL', () => {
+ const cfg = validateConfig('talking-agent', {
+ ...defaultConfig('talking-agent'),
+ brainProvider: 'custom',
+ proxyURL: 'https://my-proxy.example/chat',
+ });
+ expect(cfg.proxyURL).toBe('https://my-proxy.example/chat');
+ });
+
+ it('rejects http (non-https) proxyURL', () => {
+ expect(() =>
+ validateConfig('talking-agent', {
+ ...defaultConfig('talking-agent'),
+ proxyURL: 'http://insecure.example',
+ }),
+ ).toThrow();
+ });
+
+ it('rejects temperature above 1', () => {
+ expect(() =>
+ validateConfig('talking-agent', { ...defaultConfig('talking-agent'), temperature: 1.5 }),
+ ).toThrow();
+ });
+});
+
+describe('validateConfig — passport', () => {
+ it('accepts default config', () => {
+ expect(() => validateConfig('passport', defaultConfig('passport'))).not.toThrow();
+ });
+
+ it('rejects non-numeric agentId', () => {
+ expect(() =>
+ validateConfig('passport', { ...defaultConfig('passport'), agentId: 'abc' }),
+ ).toThrow(/agentId/);
+ });
+
+ it('rejects malformed wallet address', () => {
+ expect(() =>
+ validateConfig('passport', { ...defaultConfig('passport'), wallet: '0xnothex' }),
+ ).toThrow(/wallet/);
+ });
+
+ it('accepts valid uint256 agentId', () => {
+ const cfg = validateConfig('passport', {
+ ...defaultConfig('passport'),
+ agentId: '12345',
+ });
+ expect(cfg.agentId).toBe('12345');
+ });
+
+ it('rejects refreshIntervalSec above 3600', () => {
+ expect(() =>
+ validateConfig('passport', { ...defaultConfig('passport'), refreshIntervalSec: 5000 }),
+ ).toThrow();
+ });
+});
+
+describe('validateConfig — hotspot-tour', () => {
+ it('accepts empty hotspots array', () => {
+ expect(() =>
+ validateConfig('hotspot-tour', defaultConfig('hotspot-tour')),
+ ).not.toThrow();
+ });
+
+ it('rejects hotspot with missing position', () => {
+ expect(() =>
+ validateConfig('hotspot-tour', {
+ ...defaultConfig('hotspot-tour'),
+ hotspots: [{ id: 'a', label: 'Foo' }],
+ }),
+ ).toThrow();
+ });
+
+ it('accepts well-formed hotspot', () => {
+ const cfg = validateConfig('hotspot-tour', {
+ ...defaultConfig('hotspot-tour'),
+ hotspots: [{ id: 'a', label: 'Foo', position: [0, 1, 2] }],
+ });
+ expect(cfg.hotspots).toHaveLength(1);
+ });
+
+ it('rejects more than 40 hotspots', () => {
+ const many = Array.from({ length: 41 }, (_, i) => ({
+ id: `h${i}`,
+ label: `Hotspot ${i}`,
+ position: [0, 0, 0],
+ }));
+ expect(() =>
+ validateConfig('hotspot-tour', { ...defaultConfig('hotspot-tour'), hotspots: many }),
+ ).toThrow();
+ });
+});
+
+describe('validateConfig — errors', () => {
+ it('throws on unknown type', () => {
+ expect(() => validateConfig('unknown', {})).toThrow(/unknown widget type/);
+ });
+
+ it('validation errors have code "validation_error"', () => {
+ try {
+ validateConfig('turntable', { rotationSpeed: 999 });
+ } catch (err) {
+ expect(err.code).toBe('validation_error');
+ }
+ });
+});
+
+describe('resolveChainId', () => {
+ it('returns chainId for known slugs', () => {
+ expect(resolveChainId('base')).toBe(8453);
+ expect(resolveChainId('base-sepolia')).toBe(84532);
+ expect(resolveChainId('ethereum')).toBe(1);
+ });
+
+ it('returns numeric ref as-is', () => {
+ expect(resolveChainId(1)).toBe(1);
+ expect(resolveChainId(8453)).toBe(8453);
+ });
+
+ it('parses numeric string', () => {
+ expect(resolveChainId('137')).toBe(137);
+ });
+
+ it('returns null for unknown slug', () => {
+ expect(resolveChainId('bogus-chain')).toBe(null);
+ });
+
+ it('returns null for non-string, non-number input', () => {
+ expect(resolveChainId(null)).toBe(null);
+ expect(resolveChainId(undefined)).toBe(null);
+ expect(resolveChainId({})).toBe(null);
+ });
+
+ it('is case-insensitive for slugs', () => {
+ expect(resolveChainId('BASE')).toBe(CHAIN_SLUGS.base);
+ });
+});
+
+describe('chainLabel', () => {
+ it('returns slug for known chainId', () => {
+ expect(chainLabel(8453)).toBe('base');
+ expect(chainLabel(1)).toBe('ethereum');
+ });
+
+ it('returns fallback for unknown chainId', () => {
+ expect(chainLabel(999999)).toBe('chain-999999');
+ });
+});
diff --git a/yarn.lock b/yarn.lock
index c5aafd2b7..a89a4457b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1528,11 +1528,6 @@
resolved "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz"
integrity sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==
-"@picode/binary-reader@^0.0.4":
- version "0.0.4"
- resolved "https://registry.npmjs.org/@picode/binary-reader/-/binary-reader-0.0.4.tgz"
- integrity sha512-ae1+S0EH+K6uuE8aCQs+lpjDMBy54Gimz0j/LyTUx3H090nzyiyRKUsPx3SmZvgUqzJIZnw+sfIB8Us/iPbvPA==
-
"@privy-io/[email protected]":
version "1.8.3"
resolved "https://registry.npmjs.org/@privy-io/api-base/-/api-base-1.8.3.tgz"
@@ -2852,14 +2847,6 @@ [email protected]:
path-expression-matcher "^1.2.0"
strnum "^2.2.0"
-fbx-parser@^2.1.3:
- version "2.1.3"
- resolved "https://registry.npmjs.org/fbx-parser/-/fbx-parser-2.1.3.tgz"
- integrity sha512-2Yp/A4WHD0dc2A1lheX5243HiOObQY+Do8dd12v2ppFnG6T2Ic24I2PaeDau0vp/hKuqqA1LHjAG54sQWVY62w==
- dependencies:
- "@picode/binary-reader" "^0.0.4"
- pako "^2.0.3"
-
fdir@^6.5.0:
version "6.5.0"
resolved "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz"
@@ -3485,11 +3472,6 @@ package-json-from-dist@^1.0.0:
resolved "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz"
integrity sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==
-pako@^2.0.3:
- version "2.1.0"
- resolved "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz"
- integrity sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==
-
path-expression-matcher@^1.1.3, path-expression-matcher@^1.2.0:
version "1.5.0"
resolved "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz"
@@ -3561,6 +3543,20 @@ picomatch@^4.0.2, picomatch@^4.0.3, picomatch@^4.0.4:
resolved "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz"
integrity sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==
+ version "1.59.1"
+ resolved "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz"
+ integrity sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==
+
+playwright@^1.59.1:
+ version "1.59.1"
+ resolved "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz"
+ integrity sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==
+ dependencies:
+ playwright-core "1.59.1"
+ optionalDependencies:
+ fsevents "2.3.2"
+
possible-typed-array-names@^1.0.0:
version "1.1.0"
resolved "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz"
@@ -4139,11 +4135,6 @@ [email protected]:
resolved "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz"
integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==
-tweakpane@^4.0.5:
- version "4.0.5"
- resolved "https://registry.npmjs.org/tweakpane/-/tweakpane-4.0.5.tgz"
- integrity sha512-rxEXdSI+ArlG1RyO6FghC4ZUX8JkEfz8F3v1JuteXSV0pEtHJzyo07fcDG+NsJfN5L39kSbCYbB9cBGHyuI/tQ==
-
type-fest@^0.16.0:
version "0.16.0"
resolved "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz"