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.

feat(auth): document and test account linking, list its MCP tools in discovery, and ship the changelog entry

nirholas8ce1183a2e66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04e1c4f5f..befdd3507 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Specialist Teams: four agents, one board** (`/teams`): Assemble a squad of four 3D agents (a Researcher, an Entry scout, a Trader and a Launcher) under one spend policy. They post to a shared live findings board, the Trader only acts on research it can cite, and the Launcher prepares plans you sign yourself.
- **Spend** (`/spend`): What every agent spends by day, model and tool, the projected month end, dollar caps and token ceilings with alerts at 50, 80 and 100 percent, and resume or extend-once for a paused agent.
- **Squad Chat: one sentence, a plan, your approval** (`/team-chat`): Chat with your specialist squad or a solo agent. The coordinator turns one sentence into role-tagged plan steps, the specialists run them live with evidence, and anything that signs, moves funds, launches or exceeds your cap pauses for your approval, then resumes with receipts. Preferences you state are remembered.
+- **A complete REST API for agents, with signed webhooks**: Everything you can do with an agent in the app now works over plain HTTP with one API key: create and edit agents, start and stop them, chat, start runs and watch them live, schedule automations and fire them on demand, manage skills, and export or import an agent. Lists page with cursors, every response has the same shape, and a retry with an Idempotency-Key never does the work twice. Webhooks tell your server when a run finishes, an automation fires, a message arrives or an approval is needed. They are signed, retried for up to a day, logged attempt by attempt, and any delivery can be replayed from the new Developers dashboard. (`/docs/api-reference`) `[feature, sdk]`
- **Agents can compare every Solana swap route and see why one wins**: Ten trading tools are now available to agents in Claude or any MCP client, and over the API at /api/v1/trading. Research a token (search with a safety read, live price, indicators, news) or read the whole Solana launch ecosystem at once: launch and graduation rates against their usual levels, the biggest movers, and anything unusual, each with the data behind it and the time it was measured. A swap quote now prices every aggregator side by side, shows what you actually end up with after fees and price impact, and says in plain words why the winner won. Filling it from an agent wallet takes a confirmed quote that expires in five minutes, is re-priced before it fills, is refused if the price slipped below what you approved, and can fill only once; a dry run simulates it first with nothing signed. Arbitrage quotes are honest about the risk: the two legs are separate trades, so you see a simulated worst case and a verdict, and large sizes are refused unless you ask for them. (`/docs/trading-tools`) `[feature, sdk]`
- **Agents can find and register web domains**: Search any name across popular extensions with live availability and the exact yearly price, check a single name, and register it from your credits after a quote and an explicit yes. Coin pages now suggest available domains for the project name, and a registered domain can serve your agent's public page. Registration is for one year, renews at the same price, and has no markup. (`/domains`) `[feature]`
- **Agents can read their portfolio, run a launch sniper, set alerts and challenge each other to duels**: Fifteen new tools for Claude or any MCP client, plus a portfolio API at /api/v1/agents/:id/portfolio. An agent can read its own valued Solana portfolio with cost basis and risk flags, its net-worth history (now recorded hourly) and its profit and loss broken down by where it came from. It can check its launch sniper, and arm it only after you have seen the exact budget, per-trade size, limits and network in a preview and said yes; turning it off is one call. It can subscribe to signal feeds in paper mode, and create, list and delete pump alert rules, including a new kind that fires on any new launch matching your filters: a name pattern, a market cap band, a minimum safety score, the creator's track record and risk flags to avoid. Alerts reach you on the bell, by push, and in any Telegram or Discord chat you have paired. Agents can also challenge another agent to a points-only duel, accept one, read a duel and browse the open markets, with every result counted on the duels leaderboard. (`/docs/mcp`) `[feature, sdk]`
@@ -49,6 +50,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Run your agents on your own desktop**: The three.ws desktop app can now run agents, strategies, limit orders and automations on your machine. Signing keys stay in your operating system keychain, paper strategies keep working with no account or cloud connection, and every live trade waits for your approval in a native window that shows the exact recipient, amount, asset and chain. A tray menu lists each agent with pause, kill and review, and the mascot shows when an agent is working, waiting for you or in trouble. (`/docs/desktop-local-runtime`) `[feature]`
- **Set up your AI client with one command, and check it with doctor**: Run npx three-ws --claude (or --cursor, --codex, --vscode, --windsurf) and the CLI signs you in, connects three.ws and verifies it, with no prompts. Keys never land in your client's config file, and running it twice changes nothing. New installers at three.ws/cli/install and three.ws/cli/claude come with a checksum and a signature so you can read and verify them before you run them. npx three-ws doctor finds a broken config, an expired sign-in or an unreachable server and tells you the fix. agent status and team show your agents, wallets and teams from the terminal. (`/docs/cli`) `[feature, improvement]`
- **Sign in with Google, connect several AI clients at once, and grant permissions by group**: You can now sign in to three.ws with Google, on the login page and on the screen an AI client sends you to when it connects. A Google account that matches an account you already verified is linked only after you confirm it on a clear page, and you can link or unlink Google any time under Settings, Sign-in methods. Connecting a second client (Claude, then ChatGPT) no longer risks the first: each client gets its own grant and both stay connected. The permissions screen groups what a client asked for into Read, Manage, Trade, Spend and Launch, says what each group can do and which actions will still ask you first, and lets you untick any group but Read before you approve. Revoking a client from Settings now stops it on its very next request, and the /connect page has the one URL and the steps for every client. (`/connect`) `[feature, security]`
+- **Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature**: You can now sign in to three.ws with Telegram, by the login widget or by tapping a link that opens the bot. Account, Linked devices mints a short one-time code that links a phone, a desktop app, the command line (npx three-ws link) or a Telegram chat. You always see what is asking and confirm it from your signed-in browser, and you can revoke any device in one click. Agents and owners can attach a Solana or EVM wallet by signing a message. Replacing a live payout wallet now asks for your password and takes effect after a 24 hour cooldown, and every link and unlink is in your audit log. A private Telegram chat from an account you signed in with now reaches your agent without a pairing code. (`/dashboard/account`) `[feature, security]`
- **Specialist teams: four agents that research before they trade**: Assemble a squad of four 3D agents in one click: a Researcher that vets a token and posts a scored verdict, an Entry scout that checks fresh launches against your entry gates, a Trader that quotes, simulates or trades inside one spend policy, and a Launcher that prepares a launch plan for you to sign. They share a live findings board. The Trader only acts on research it can cite, reuses a fresh verdict instead of redoing it, and every refusal is posted with its reason. Only the Trader can ever sign, and only a live trade you confirm. (`/teams`) `[feature]`
- **Strategies now research every coin and ask before they buy**: Trading strategies can now check a coin before spending anything: minimum holders, how much the largest holder owns, liquidity, the rug and honeypot safety score, whether the creator can still mint or freeze, and the creator's track record. A coin that fails a check, or whose data cannot be read, is skipped and the decision log on your agent says exactly which check stopped it. You can also cap price impact per buy. Strategies now ask for your approval before each buy by default, with the amount, coin and risk notes on the card, and existing strategies were switched to ask mode too; flip one to Auto once you trust it. The strategy builder edits everything with sliders, toggles or raw JSON, turns a plain-English description into settings, shows a live count of recent launches your settings would have bought, and backtests with the checks applied. (`/strategies`) `[feature]`
- **Talk to your squad in one sentence**: Squad chat turns a plain sentence like "research $THREE and buy 0.05 SOL if it looks safe" into a plan of steps for your specialist team or any of your agents. Research and entry checks run live with their evidence, and anything that signs, moves funds, launches a coin or goes over your cap stops as an approval card with the full details. Approve and the squad picks the run back up and finishes with receipts. Paper mode is the default and never signs. Say "remember my default trade size is 0.1 SOL" and the squad keeps it. Coin names and descriptions are treated as data, so a coin written to trick AI agents cannot change the plan. You can type or dictate, and the squad's 3D avatars react as they work. (`/team-chat`) `[feature, security]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index b79b108c1..07f8e9cc6 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -382,6 +382,7 @@ surface-map row already covers:
| [workers/model-video2scene/](workers/model-video2scene) | Streaming video to 3D point-cloud reconstruction on Cloud Run GPU (LingBot-Map). Built and weights staged, not deployed as its own service yet, so `/capture` runs its designed unconfigured state until `GCP_VIDEO2SCENE_URL` is set |
| [workers/texture/](workers/texture) | Text-guided texturing + magic-brush region retexture GPU server |
| [workers/pump-fun-mcp/](workers/pump-fun-mcp) | Cloudflare Workers mirror of the canonical pump.fun MCP server |
+| Account linking | Telegram sign-in [api/auth/telegram/](api/auth/telegram), link codes [api/auth/link-codes/](api/auth/link-codes), external wallets [api/auth/external-wallet/](api/auth/external-wallet), shared logic [api/_lib/account-link/](api/_lib/account-link), device page [pages/link-device.html](pages/link-device.html) `→ /link-device` + [src/link-device.js](src/link-device.js), account panels [src/dashboard-next/pages/account-linking.js](src/dashboard-next/pages/account-linking.js), CLI `three-ws link` [packages/three-ws-cli/src/link-code.js](packages/three-ws-cli/src/link-code.js) | Live | One-time, rate-limited, owner-confirmed linking of Telegram, phones, desktop apps, the CLI and chats, plus signed-message Solana/EVM wallets with step-up and a 24h payout cooldown. Docs: [docs/account-linking.md](docs/account-linking.md), [docs/chat-gateways.md](docs/chat-gateways.md). |
| [workers/agent-gateway/](workers/agent-gateway) | Chat gateway worker: drains `gateway_inbox` (filled by the webhook receivers in [api/gateway/](api/gateway)) through `handleEvent` in [api/_lib/gateway/core.js](api/_lib/gateway/core.js) and delivers replies, approval previews, signed approval requests and notifications back to the chat. Leased per-chat claims, platform-aware retries and dead letters, a `/healthz` endpoint, and operator commands for the bots and the inbox. Built and tested, not deployed: deliveries wait in the inbox until it runs. Docs: [workers/agent-gateway/README.md](workers/agent-gateway/README.md). Tests: [workers/agent-gateway/tests/](workers/agent-gateway/tests) |
| [workers/signal-bridge/](workers/signal-bridge) | Signal leg of the chat gateway: the signal-cli REST bridge with its registration snapshotted to a Cloud Storage bucket so it survives redeploys. Single instance by design. Builds and runs locally, not deployed |
| [services/agent-screen-caster/](services/agent-screen-caster) | Self-hosted Playwright caster: an agent owner runs it on their own host with their agent id + key, and it streams the browser it drives into the agent-screen feed. No managed instance exists (the platform's own casting runs in `workers/agent-screen-pool` and `workers/agent-screen-worker`). Tests: [tests/agent-screen-caster.test.js](tests/agent-screen-caster.test.js) |
diff --git a/api/_mcpagent/discovery.js b/api/_mcpagent/discovery.js
index 392f88001..54d4759ef 100644
--- a/api/_mcpagent/discovery.js
+++ b/api/_mcpagent/discovery.js
@@ -19,7 +19,9 @@ export const RESOURCE_DESCRIPTION =
'find_services (search the live facilitator network for paid services), pay_quote (price a paid ' +
'endpoint without paying), pay_and_call (call a paid x402 endpoint and settle the USDC payment ' +
'from the signed-in user own three.ws agent wallet, bounded by their caps), provision_wallet, ' +
- 'monetize_endpoint (list your own paid service) and read_resource (live three:// resources). ' +
+ 'monetize_endpoint (list your own paid service), read_resource (live three:// resources), ' +
+ 'get_linked_accounts (sign-in methods, wallets and linked devices) and set_external_wallet ' +
+ '(attach a Solana or EVM wallet proved by a signed message). ' +
'An agent marketplace with USDC escrow on Solana: browse_marketplace, browse_public_agents, ' +
'get_listing, get_marketplace_history, preview_marketplace_action, create_marketplace_listing, ' +
'delist_marketplace_listing, place_bid, buy_now, get_my_bids, get_received_bids, ' +
diff --git a/data/changelog.json b/data/changelog.json
index 1c7697140..a282b85bb 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-10",
+ "title": "Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature",
+ "summary": "You can now sign in to three.ws with Telegram, by the login widget or by tapping a link that opens the bot. Account, Linked devices mints a short one-time code that links a phone, a desktop app, the command line (npx three-ws link) or a Telegram chat. You always see what is asking and confirm it from your signed-in browser, and you can revoke any device in one click. Agents and owners can attach a Solana or EVM wallet by signing a message. Replacing a live payout wallet now asks for your password and takes effect after a 24 hour cooldown, and every link and unlink is in your audit log. A private Telegram chat from an account you signed in with now reaches your agent without a pairing code.",
+ "tags": ["feature", "security"],
+ "link": "/dashboard/account"
+ },
{
"date": "2026-10-10",
"title": "Developer plans with quotas that are enforced, self-serve upgrades, key rotation, IP allowlists and per-key analytics",
diff --git a/data/pages.json b/data/pages.json
index b94a6ae5a..89c3f2ffd 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -4982,6 +4982,20 @@
"priority": 0.7,
"changefreq": "monthly"
},
+ {
+ "path": "/docs/account-linking",
+ "title": "Docs: Account linking",
+ "description": "Sign in with Telegram, link phones, desktop apps, the CLI and chats with one-time codes, and attach Solana or EVM wallets by signature, with audit-logged revoke.",
+ "priority": 0.7,
+ "changefreq": "monthly"
+ },
+ {
+ "path": "/docs/chat-gateways",
+ "title": "Docs: Chat gateways",
+ "description": "Talk to your agent from Telegram and other chat platforms: pairing, commands, approval limits, the Telegram webhook, privacy and rate limits.",
+ "priority": 0.7,
+ "changefreq": "monthly"
+ },
{
"path": "/docs/agent-mail",
"title": "Docs: Agent Mail",
diff --git a/docs/account-linking.md b/docs/account-linking.md
new file mode 100644
index 000000000..91cb8d5c4
--- /dev/null
+++ b/docs/account-linking.md
@@ -0,0 +1,71 @@
+# Account linking
+
+Four ways to connect things to one three.ws account, each safe by construction: single use, short lived, rate limited, shown to a signed-in owner before it takes effect, and written to the audit log.
+
+| You want to | Use |
+|-------------|-----|
+| Sign in with Telegram | [Telegram sign-in](#telegram-sign-in) |
+| Link a phone, desktop app, CLI or Telegram chat | [Link codes](#link-codes) |
+| Prove a Solana or EVM wallet as owner or payout wallet | [External wallets](#external-wallets) |
+| See everything linked | `GET /api/auth/linked-accounts` and Account, Linked devices |
+
+## Telegram sign-in
+
+Two flows, same account result.
+
+**Widget.** `GET /api/auth/telegram/start?intent=login|link|reauth&next=` opens Telegram's login widget. The callback verifies the payload server-side: HMAC-SHA256 over the sorted fields keyed by the SHA-256 of the bot token, constant-time compare, a five-minute freshness window on `auth_date`, and replay protection (a payload hash is stored and a second use is refused). `reauth` proves the person at the keyboard for sensitive actions, with a five-minute window.
+
+**Magic link.** `POST /api/auth/telegram/magic {intent:'login'|'link', next?}` returns `{id, poll_secret, deep_link, bot_username, expires_in}`. The page shows a QR and an Open in Telegram button. Telegram sends `/start tl_<token>` to the bot, the webhook claims it once, and the page, polling `GET /api/auth/telegram/poll?id&secret`, completes. The token lives ten minutes, is single use, and only works in a private chat. A link request never signs in as someone else: `link` binds to the session that started it.
+
+Other routes: `GET /api/auth/telegram/status`, `POST /api/auth/telegram/unlink` (needs a password or fresh reauth; refused if Telegram is the last sign-in method).
+
+Outcomes surface on `/login?error=telegram_<code>` or `/dashboard/settings?telegram=<code>`: `invalid_hash`, `stale`, `replayed`, `expired`, `not_linked`, `identity_in_use`, `already_linked`, `cancelled`, `failed`, `unavailable`. Needs `TELEGRAM_BOT_TOKEN` and the bot username; with neither set the login page shows no Telegram button.
+
+## Link codes
+
+A short code, `BCDF-GHJK`, minted on [Account, Linked devices](https://three.ws/dashboard/account#linked-devices) by a signed-in owner.
+
+1. **Mint** `POST /api/auth/link-codes/mint {device_kind, label?, scopes?}` with `device_kind` one of `phone`, `desktop`, `cli`, `telegram`. Ten-minute life, single use, only the hash is stored.
+2. **Claim** (device side, no login) `POST /api/auth/link-codes/claim {code, device_kind, device:{name, platform, client}}` returns a claim secret.
+3. **Confirm** the owner's page lists the pending claim with the device name, platform, client, IP and, for Telegram, the chat. The owner can narrow the scopes and presses Confirm or Reject (`POST /api/auth/link-codes/decide`). A different signed-in account cannot decide it (`wrong_account`), and scopes can never be widened (`scope_widened`).
+4. **Poll** `GET /api/auth/link-codes/poll?id&secret` returns the credential once: a session for a phone, an API key for a desktop app or CLI, a gateway pairing for Telegram. A second poll gets `consumed`.
+
+Devices are listed with `GET /api/auth/link-codes/devices` and removed with `POST /api/auth/link-codes/revoke {id}`, which kills the credential.
+
+Money-moving scopes are not linkable this way; mint those on the API keys page.
+
+**On the device**
+
+- CLI: `npx three-ws link BCDF-GHJK` claims, waits for your confirmation, and stores the key.
+- Phone or desktop app: open `/link-device?code=BCDF-GHJK`.
+- Telegram: send `/link BCDF-GHJK` to the bot.
+
+Limits: 20 mints per user per 10 minutes, 20 claims per IP per 10 minutes. Errors: `invalid_code`, `unknown_code`, `wrong_kind`, `expired`, `already_used`, `wrong_account`, `scope_widened`, `no_chat`, `unknown_claim`.
+
+## External wallets
+
+Attach a Solana or EVM wallet proved by a signed message.
+
+```
+POST /api/auth/external-wallet/challenge {chain:'solana'|'evm', address, role:'owner'|'payout', agent_id?}
+POST /api/auth/external-wallet/verify {chain, message, signature, password?}
+```
+
+The challenge returns a message with a one-time nonce and expiry. Sign it with the wallet and verify. A nonce burns on use, so a replay fails.
+
+- `role: owner` links the wallet as a sign-in wallet.
+- `role: payout` sets the agent's payout wallet. A first wallet is live at once. **Replacing a live payout wallet needs step-up** (password or fresh reauth, else `403 step_up_required` with the current address) and takes effect after a **24 hour cooldown**, during which the previous wallet keeps receiving. Where an approval is required, the request appears in the [approvals inbox](./approvals.md) as a payout wallet change and is never auto-approved.
+
+The same policy guards `PUT /api/monetization/wallet` and `POST /api/billing/payout-wallets`.
+
+MCP tools: `set_external_wallet` (challenge and verify steps) and `get_linked_accounts` on the main server. See [mcp.md](./mcp.md).
+
+## Linked accounts
+
+`GET /api/auth/linked-accounts` returns `{sign_in, wallets, payout, devices, chats}`.
+
+## Audit log
+
+Every link, unlink, reject, revoke, reauth and payout-wallet change is recorded (`link_*`, `unlink_*`, `reauth:telegram`, `link_code_*`), visible on the Account page activity and in `/api/audit-log`.
+
+Related: [authentication.md](./authentication.md), [chat-gateways.md](./chat-gateways.md), [approvals.md](./approvals.md).
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 0df89ef82..53a768192 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -4527,6 +4527,22 @@ Authentication is covered in detail in the [Authentication documentation](authen
| `/api/auth/wallets` | POST | Link a new wallet |
| `/api/auth/handoff` | POST | Mint a single-use code that signs Safari in as this session (iOS app) |
| `/api/auth/handoff` | GET | Exchange that code in Safari for a session cookie and land on the page |
+| `/api/auth/telegram/magic` | POST | Start a Telegram deep-link sign-in or link; returns a deep link and poll secret |
+| `/api/auth/telegram/poll` | GET | Poll a magic link until the bot claims it |
+| `/api/auth/telegram/status` | GET | Telegram link state for the signed-in account |
+| `/api/auth/telegram/unlink` | POST | Unlink Telegram (password or fresh reauth) |
+| `/api/auth/link-codes/mint` | POST | Mint a one-time code for a phone, desktop, CLI or Telegram chat |
+| `/api/auth/link-codes/claim`| POST | Device side: claim a code (no login), returns a claim secret |
+| `/api/auth/link-codes/poll` | GET | Device side: poll for the confirmed credential |
+| `/api/auth/link-codes/pending` | GET | Owner side: pending claims awaiting confirmation |
+| `/api/auth/link-codes/decide` | POST | Confirm or reject a claim, optionally narrowing scopes |
+| `/api/auth/link-codes/devices` | GET | Linked devices |
+| `/api/auth/link-codes/revoke` | POST | Revoke a linked device and its credential |
+| `/api/auth/external-wallet/challenge` | POST | Get a message to sign with a Solana or EVM wallet |
+| `/api/auth/external-wallet/verify` | POST | Verify the signature; link as owner or set the payout wallet |
+| `/api/auth/linked-accounts` | GET | Everything linked to the account |
+
+See [account-linking.md](account-linking.md) for the flows, limits and errors.
### Session handoff to Safari (iOS app)
diff --git a/docs/approvals.md b/docs/approvals.md
index e6baa8733..f530d2d24 100644
--- a/docs/approvals.md
+++ b/docs/approvals.md
@@ -213,7 +213,7 @@ The default is that every gated action asks you. An auto-approve rule is an
explicit exception you create:
- **venues**: which kinds of action it covers. `jupiter` (token swaps) and
- `wallet_transfer` (transfers). A rule for swaps never covers transfers.
+ `wallet_transfer` (transfers). A rule for swaps never covers transfers. Payout wallet changes are also gated by an approval but can never be auto-approved: the request shows the old and new address, and the new wallet takes effect 24 hours after approval.
- **max_usd**: the largest single action it covers, capped at $1,000 per
action. Anything larger always asks.
- **agent_id** (optional): limit it to one agent. **team_id** (optional):
diff --git a/docs/authentication.md b/docs/authentication.md
index fbb079ada..a0bae79fe 100644
--- a/docs/authentication.md
+++ b/docs/authentication.md
@@ -365,6 +365,10 @@ GOOGLE_OAUTH_CLIENT_SECRET=
Both unset: `GET /api/config` reports `googleEnabled: false`, the login page shows no Google button, `/api/auth/google/start` sends a browser to `/login?error=google_unavailable` and answers an API caller `501 not_configured`. Nothing else changes.
+## Sign in with Telegram, link codes and external wallets
+
+Telegram sign-in (widget and deep-link magic link), one-time link codes for phones, desktop apps, the CLI and Telegram chats, and signed-message external wallets are documented in [account-linking.md](./account-linking.md).
+
---
## Session Management
diff --git a/docs/chat-gateways.md b/docs/chat-gateways.md
new file mode 100644
index 000000000..8abeae124
--- /dev/null
+++ b/docs/chat-gateways.md
@@ -0,0 +1,67 @@
+# Chat gateways
+
+Talk to your three.ws agent from a chat app. A paired chat can ask for balances and portfolio, run `/pause` and `/kill`, approve or deny requests your spend policy holds, send voice notes and photos, and receive account notifications. Telegram and Discord are live today. Slack, WhatsApp, Signal, SMS and email share the same core.
+
+The API only verifies and queues. The [agent-gateway worker](../workers/agent-gateway/README.md) drains the queue, runs the turn and replies.
+
+## Platform capabilities
+
+One table in [api/_lib/gateway/platforms.js](../api/_lib/gateway/platforms.js) drives behavior per platform.
+
+| Platform | Buttons | Edit in place | Voice |
+|----------|---------|---------------|-------|
+| Telegram | yes | yes | yes |
+| Discord | yes | yes | yes |
+| Slack | yes | yes | yes |
+| WhatsApp | yes | no | yes |
+| Signal | no, reply with a six-digit code | no | yes |
+| SMS | no, reply with a six-digit code | no | no |
+| Email | no, reply with a six-digit code | no | yes |
+
+## Pairing a chat
+
+Three ways to pair, all ending in the same thing: a chat linked to exactly one account, by that account's owner.
+
+1. **From the chat.** Send `/start`. The bot replies with a pairing code and a link to `/settings/connections?code=...`. Sign in on the site and confirm. Codes expire in minutes.
+2. **From the site.** On [Connections](https://three.ws/settings/connections), press issue, then send `/link <code>` to the bot.
+3. **From Linked devices.** On [Account, Linked devices](https://three.ws/dashboard/account#linked-devices), mint a code for a Telegram chat and send `/link <code>` in the chat. The chat claims the code, then the signed-in browser sees which chat is asking and must press Confirm. Nothing pairs until that confirmation. See [account-linking.md](./account-linking.md).
+
+If the Telegram account that is chatting already signs in to a three.ws account (Telegram sign-in or a linked Telegram identity), a private chat resolves to that account without any code. Signing in with Telegram already proved control. Groups never auto-resolve, because a group is shared; they pair explicitly.
+
+Rules that always hold:
+
+- A paired group belongs to one person. Anyone else who writes there is told so and never reaches the owner's agent or wallet.
+- A forwarded message is never an instruction. A forwarded `/link` pairs nothing, and a forwarded request is not run.
+- `/unlink` disconnects a chat. The owner can also revoke it on Connections or Linked devices.
+
+## Commands
+
+`/balance`, `/portfolio`, `/runs`, `/launches`, `/agents`, `/use <agent>`, `/new`, `/voice on|off`, `/approvals`, `/positions`, `/pause`, `/kill`, `/unlink`, `/help`. `/help` is the source of truth; the list above mirrors [api/_lib/gateway/commands.js](../api/_lib/gateway/commands.js).
+
+## What can and cannot be approved from chat
+
+Trades never run from text alone. A preview arrives with Approve and Cancel buttons (or a six-digit code on platforms without buttons), expires after ten minutes, and only the exact approval executes it. Requests your spend policy holds arrive with Approve and Deny. `/pause` and `/kill` stop agents at once. Lifting a freeze is done on the web. Details: [approvals.md](./approvals.md#approving-from-telegram-and-discord). Changing a payout wallet is never auto-approved and always shows the old and new address.
+
+## Telegram webhook
+
+`POST /api/gateway/telegram` is the receiver. Telegram proves each delivery with the `X-Telegram-Bot-Api-Secret-Token` header it was given at `setWebhook`; an invalid header answers `401`. A verified update is stored in the inbox and answered `200` immediately. A retried `update_id` hits the inbox's unique key, so a redelivery never produces a second reply.
+
+A sign-in magic link (`/start tl_<token>`) is claimed inline in the webhook, not queued, so the browser waiting for it sees the claim within a second. It only works in a private chat.
+
+## Privacy
+
+Messages are stored to run the turn and keep thread context. Pairing records hold the platform user id, chat id and display name, nothing else about the Telegram account. Unlinking revokes the pairing immediately. Every pair and unpair is in the audit log.
+
+## Limits
+
+| Limit | Value |
+|-------|-------|
+| Messages per paired chat | 20 per minute |
+| Pairing codes issued per chat | 8 per hour |
+| Settings writes per user | 30 per hour |
+
+## Related
+
+- [Account linking](./account-linking.md): Telegram sign-in, link codes, external wallets
+- [Approvals](./approvals.md)
+- [agent-gateway worker](../workers/agent-gateway/README.md)
diff --git a/docs/start-here.md b/docs/start-here.md
index aecbe16c6..41da0688d 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -185,6 +185,8 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ
- **Listening to the economy?** → [Agent Symphony](./agent-symphony.md): /symphony plays the live agent economy as generative music; every event type has a voice, and solo mode isolates one agent by ear
- **Catching up on your inbox?** → [Notifications](./notifications.md): the bell, the /notifications center, category filters, and the full inbox API
- **An agent waiting on your yes?** → [Approvals](./approvals.md): the /approvals inbox, push Approve/Deny, signed deep links, payload-hash checks, and auto-approve rules
+- **Talking to your agent from Telegram or Discord?** → [Chat gateways](./chat-gateways.md): pairing, commands, what can be approved from chat, privacy
+- **Linking a phone, CLI, Telegram or wallet to your account?** → [Account linking](./account-linking.md): Telegram sign-in, one-time link codes, external wallets with step-up and cooldown
- **Keeping an agent inside a budget?** → [Usage control and spend](./inference-billing.md): dollar caps and hourly, daily and per-run token ceilings per agent, the /spend page with usage by day, model and tool and the projected month end, alerts at 50, 80 and 100 percent, resume and extend-once, top-ups in SOL, USDC and $THREE, and the free-tier error that carries your choices
- **Want your agent to have an email address?** → [Agent Mail](./agent-mail.md): a real inbox on agents.three.ws, quote-then-confirm sends, a recipient allowlist and daily cap, received mail treated as data, and rules that turn incoming mail into agent runs
- **Something too important for a badge?** → [Herald](./herald.md): the open SDK behind /herald, where a 3D character walks onto the page and says it out loud, with an interrupt budget (importance floor, quiet hours, dedupe, batching), an accessible card for machines with no GPU, a rail so CI or an AI agent can reach the tab you have open, and a CLI that announces when your build finishes
diff --git a/packages/three-ws-cli/tests/link-code.test.js b/packages/three-ws-cli/tests/link-code.test.js
new file mode 100644
index 000000000..07184b6bb
--- /dev/null
+++ b/packages/three-ws-cli/tests/link-code.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { normalizeCode, claimLinkCode, pollLinkCode, linkCodeLogin } from '../src/link-code.js';
+
+const origin = 'https://example.test';
+const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+const claim = { id: 'c1', claim_secret: 's3cret', poll_every_ms: 1000, expires_at: new Date(Date.now() + 600_000).toISOString(), scopes: ['read', 'generate'] };
+const noSleep = () => Promise.resolve();
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('normalizeCode', () => {
+ it('formats typed codes', () => {
+ expect(normalizeCode('bcdf ghjk')).toBe('BCDF-GHJK');
+ expect(normalizeCode('BCDFGHJK')).toBe('BCDF-GHJK');
+ });
+ it('rejects vowels, wrong length and junk', () => {
+ expect(normalizeCode('ABCD-EFGH')).toBeNull();
+ expect(normalizeCode('BCDF')).toBeNull();
+ expect(normalizeCode('')).toBeNull();
+ });
+});
+
+describe('claimLinkCode', () => {
+ it('rejects an invalid code without any request', async () => {
+ const f = vi.fn();
+ vi.stubGlobal('fetch', f);
+ await expect(claimLinkCode({ origin, code: 'nope' })).rejects.toMatchObject({ code: 'invalid_code' });
+ expect(f).not.toHaveBeenCalled();
+ });
+ it('posts the normalized code as a cli device', async () => {
+ const f = vi.fn(async () => json(200, claim));
+ vi.stubGlobal('fetch', f);
+ await claimLinkCode({ origin, code: 'bcdfghjk' });
+ const [url, init] = f.mock.calls[0];
+ expect(url).toBe(`${origin}/api/auth/link-codes/claim`);
+ const body = JSON.parse(init.body);
+ expect(body.code).toBe('BCDF-GHJK');
+ expect(body.device_kind).toBe('cli');
+ });
+});
+
+describe('pollLinkCode', () => {
+ it('waits while claimed, then returns the confirmed result', async () => {
+ const answers = [json(200, { status: 'claimed' }), json(200, { status: 'confirmed', credential: { kind: 'api_key', secret: 'k' } })];
+ vi.stubGlobal('fetch', vi.fn(async () => answers.shift()));
+ const out = await pollLinkCode({ origin, claim, sleep: noSleep });
+ expect(out.status).toBe('confirmed');
+ });
+ it('treats 404 as a rejected request', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => json(404, { error: 'unknown_claim' })));
+ await expect(pollLinkCode({ origin, claim, sleep: noSleep })).rejects.toMatchObject({ code: 'rejected' });
+ });
+ it.each(['rejected', 'expired', 'consumed'])('stops on %s', async (status) => {
+ vi.stubGlobal('fetch', vi.fn(async () => json(200, { status })));
+ await expect(pollLinkCode({ origin, claim, sleep: noSleep })).rejects.toMatchObject({ code: status });
+ });
+});
+
+describe('linkCodeLogin', () => {
+ it('returns an apikey auth record', async () => {
+ const answers = [json(200, claim), json(200, { status: 'confirmed', device_id: 'd1', credential: { kind: 'api_key', id: 'k1', secret: 'sk_live_abcdef123456' } })];
+ vi.stubGlobal('fetch', vi.fn(async () => answers.shift()));
+ const onClaimed = vi.fn();
+ const out = await linkCodeLogin({ origin, code: 'BCDF-GHJK', onClaimed });
+ expect(onClaimed).toHaveBeenCalled();
+ expect(out.auth).toMatchObject({ type: 'apikey', key: 'sk_live_abcdef123456', key_id: 'k1', scope: 'read generate' });
+ expect(out.device_id).toBe('d1');
+ });
+});
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 74879d303..b030ec5b8 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,11 +1,11 @@
{
- "generated_at": "2026-10-10T20:39:45.789Z",
+ "generated_at": "2026-10-10T20:52:15.832Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3933,
+ "total": 3935,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
@@ -239,6 +239,17 @@
"launch"
]
},
+ {
+ "date": "2026-10-10",
+ "type": "update",
+ "title": "A complete REST API for agents, with signed webhooks",
+ "summary": "Everything you can do with an agent in the app now works over plain HTTP with one API key: create and edit agents, start and stop them, chat, start runs and watch them live, schedule automations and fire them on demand, manage skills, and export or import an agent. Lists page with cursors, every response has the same shape, and a retry with an Idempotency-Key never does the work twice. Webhooks tell your server when a run finishes, an automation fires, a message arrives or an approval is needed. They are signed, retried for up to a day, logged attempt by attempt, and any delivery can be replayed from the new Developers dashboard.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-10-10",
"type": "update",
@@ -453,6 +464,17 @@
"security"
]
},
+ {
+ "date": "2026-10-10",
+ "type": "update",
+ "title": "Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature",
+ "summary": "You can now sign in to three.ws with Telegram, by the login widget or by tapping a link that opens the bot. Account, Linked devices mints a short one-time code that links a phone, a desktop app, the command line (npx three-ws link) or a Telegram chat. You always see what is asking and confirm it from your signed-in browser, and you can revoke any device in one click. Agents and owners can attach a Solana or EVM wallet by signing a message. Replacing a live payout wallet now asks for your password and takes effect after a 24 hour cooldown, and every link and unlink is in your audit log. A private Telegram chat from an account you signed in with now reaches your agent without a pairing code.",
+ "link": "/dashboard/account",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-10-10",
"type": "update",
@@ -1521,26 +1543,6 @@
"tags": [
"feature"
]
- },
- {
- "date": "2026-09-30",
- "type": "update",
- "title": "Spotlight entries now show verified results, and success stories are opt-in",
- "summary": "Every Agent Spotlight entry now has a Verified results block: coins the agent launched, creator fees it earned and income from other agents paying for its skills, computed by three.ws and linked to where you can check them. The builder cannot edit these numbers. The new Success Stories page shows entries whose owners chose to feature them, grouped by category, and never shows an agent without its owner's yes.",
- "link": "/stories",
- "tags": [
- "feature"
- ]
- },
- {
- "date": "2026-09-30",
- "type": "update",
- "title": "The coming iPhone app gains notifications, a share sheet entry and quick actions",
- "summary": "The three.ws iOS app, on its way to the App Store, now matches the Android app and goes further. Turn on notifications and sales, follows and remixes arrive on your iPhone with your unread count on the app icon, and a tap opens the page it is about. three.ws appears in the share sheet: share one to three photos and they wait in Create as the front, left and right views of a new 3D avatar, or share a .glb from Files to upload it. Press and hold the icon for Create avatar, Discover, My agents and Notifications.",
- "link": "/docs/ios-app",
- "tags": [
- "feature"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 6dc2773d1..426a6bc69 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-10-10T20:39:45.768Z",
+ "generated_at": "2026-10-10T20:52:15.787Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -236,6 +236,17 @@
"launch"
]
},
+ {
+ "date": "2026-10-10",
+ "type": "update",
+ "title": "A complete REST API for agents, with signed webhooks",
+ "summary": "Everything you can do with an agent in the app now works over plain HTTP with one API key: create and edit agents, start and stop them, chat, start runs and watch them live, schedule automations and fire them on demand, manage skills, and export or import an agent. Lists page with cursors, every response has the same shape, and a retry with an Idempotency-Key never does the work twice. Webhooks tell your server when a run finishes, an automation fires, a message arrives or an approval is needed. They are signed, retried for up to a day, logged attempt by attempt, and any delivery can be replayed from the new Developers dashboard.",
+ "link": "/docs/api-reference",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-10-10",
"type": "update",
@@ -450,6 +461,17 @@
"security"
]
},
+ {
+ "date": "2026-10-10",
+ "type": "update",
+ "title": "Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature",
+ "summary": "You can now sign in to three.ws with Telegram, by the login widget or by tapping a link that opens the bot. Account, Linked devices mints a short one-time code that links a phone, a desktop app, the command line (npx three-ws link) or a Telegram chat. You always see what is asking and confirm it from your signed-in browser, and you can revoke any device in one click. Agents and owners can attach a Solana or EVM wallet by signing a message. Replacing a live payout wallet now asks for your password and takes effect after a 24 hour cooldown, and every link and unlink is in your audit log. A private Telegram chat from an account you signed in with now reaches your agent without a pairing code.",
+ "link": "/dashboard/account",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
{
"date": "2026-10-10",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index ffdd4ecfc..91b75488e 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -190,6 +190,14 @@
<category>launch</category>
<description>Chat with your specialist squad or a solo agent. The coordinator turns one sentence into role-tagged plan steps, the specialists run them live with evidence, and anything that signs, moves funds, launches or exceeds your cap pauses for your approval, then resumes with receipts. Preferences you state are remembered.</description>
</item>
+ <item>
+ <title>A complete REST API for agents, with signed webhooks</title>
+ <link>https://three.ws/docs/api-reference</link>
+ <guid isPermaLink="false">2026-10-10:A complete REST API for agents, with signed webhooks</guid>
+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Everything you can do with an agent in the app now works over plain HTTP with one API key: create and edit agents, start and stop them, chat, start runs and watch them live, schedule automations and fire them on demand, manage skills, and export or import an agent. Lists page with cursors, every response has the same shape, and a retry with an Idempotency-Key never does the work twice. Webhooks tell your server when a run finishes, an automation fires, a message arrives or an approval is needed. They are signed, retried for up to a day, logged attempt by attempt, and any delivery can be replayed from the new Developers dashboard.</description>
+ </item>
<item>
<title>Agents can compare every Solana swap route and see why one wins</title>
<link>https://three.ws/docs/trading-tools</link>
@@ -350,6 +358,14 @@
<category>feature</category>
<description>You can now sign in to three.ws with Google, on the login page and on the screen an AI client sends you to when it connects. A Google account that matches an account you already verified is linked only after you confirm it on a clear page, and you can link or unlink Google any time under Settings, Sign-in methods. Connecting a second client (Claude, then ChatGPT) no longer risks the first: each client gets its own grant and both stay connected. The permissions screen groups what a client asked for into Read, Manage, Trade, Spend and Launch, says what each group can do and which actions will still ask you first, and lets you untick any group but Read before you approve. Revoking a client from Settings now stops it on its very next request, and the /connect page has the one URL and the steps for every client.</description>
</item>
+ <item>
+ <title>Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature</title>
+ <link>https://three.ws/dashboard/account</link>
+ <guid isPermaLink="false">2026-10-10:Sign in with Telegram, link devices with one-time codes, and prove payout wallets with a signature</guid>
+ <pubDate>Sat, 10 Oct 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>You can now sign in to three.ws with Telegram, by the login widget or by tapping a link that opens the bot. Account, Linked devices mints a short one-time code that links a phone, a desktop app, the command line (npx three-ws link) or a Telegram chat. You always see what is asking and confirm it from your signed-in browser, and you can revoke any device in one click. Agents and owners can attach a Solana or EVM wallet by signing a message. Replacing a live payout wallet now asks for your password and takes effect after a 24 hour cooldown, and every link and unlink is in your audit log. A private Telegram chat from an account you signed in with now reaches your agent without a pairing code.</description>
+ </item>
<item>
<title>Specialist teams: four agents that research before they trade</title>
<link>https://three.ws/teams</link>
diff --git a/tests/account-link.test.js b/tests/account-link.test.js
new file mode 100644
index 000000000..94f0ef883
--- /dev/null
+++ b/tests/account-link.test.js
@@ -0,0 +1,224 @@
+// Account linking: Telegram payload verification and replay, magic-link
+// claim/complete, link-code claim/decide, and the payout-wallet policy.
+// The database is replaced by a scripted tagged-template fake; hashing and
+// HMAC checks are real.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { createHash, createHmac } from 'node:crypto';
+
+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
+
+const queue = [];
+const calls = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: Object.assign(
+ async (strings, ...vals) => {
+ calls.push({ text: strings.join('?'), vals });
+ const next = queue.shift();
+ return typeof next === 'function' ? next() : (next ?? []);
+ },
+ { json: (v) => v },
+ ),
+}));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/identities.js', () => ({
+ findUserByIdentity: vi.fn(async () => null),
+ linkIdentity: vi.fn(async () => ({ relinked: false })),
+ touchIdentity: vi.fn(),
+ IdentityError: class IdentityError extends Error {},
+}));
+vi.mock('../api/_lib/gateway/bots.js', () => ({
+ telegramConfigured: () => true,
+ telegramUsername: async () => 'three_ws_bot',
+}));
+
+const { findUserByIdentity } = await import('../api/_lib/identities.js');
+const tl = await import('../api/_lib/account-link/telegram-login.js');
+const lc = await import('../api/_lib/account-link/link-codes.js');
+const ew = await import('../api/_lib/account-link/external-wallets.js');
+
+const TOKEN = '123456:TEST-bot-token';
+const env = { TELEGRAM_BOT_TOKEN: TOKEN };
+const NOW = Date.UTC(2026, 9, 10, 12, 0, 0);
+
+function sign(fields, token = TOKEN) {
+ const lines = Object.keys(fields).sort().map((k) => `${k}=${fields[k]}`).join('\n');
+ const hash = createHmac('sha256', createHash('sha256').update(token).digest()).update(lines).digest('hex');
+ return { ...fields, hash };
+}
+const fresh = (over = {}) => sign({ id: '42', first_name: 'Ada', username: 'ada', auth_date: String(NOW / 1000 - 30), ...over });
+
+beforeEach(() => {
+ queue.length = 0;
+ calls.length = 0;
+ findUserByIdentity.mockReset();
+ findUserByIdentity.mockResolvedValue(null);
+});
+
+describe('telegram widget payload', () => {
+ it('accepts a correctly signed fresh payload', () => {
+ const out = tl.verifyWidgetPayload(fresh(), { env, now: NOW });
+ expect(out.claims.subject).toBe('42');
+ expect(out.claims.username).toBe('ada');
+ });
+
+ it('rejects a tampered field', () => {
+ const p = fresh();
+ p.id = '43';
+ expect(() => tl.verifyWidgetPayload(p, { env, now: NOW })).toThrow(expect.objectContaining({ code: 'invalid_hash' }));
+ });
+
+ it('rejects a payload signed with another bot token', () => {
+ expect(() => tl.verifyWidgetPayload(fresh({}) && sign({ id: '42', auth_date: String(NOW / 1000) }, 'other:token'), { env, now: NOW }))
+ .toThrow(expect.objectContaining({ code: 'invalid_hash' }));
+ });
+
+ it('rejects a missing or malformed hash', () => {
+ expect(() => tl.verifyWidgetPayload({ id: '42', auth_date: '1' }, { env, now: NOW })).toThrow(expect.objectContaining({ code: 'invalid_hash' }));
+ });
+
+ it('rejects a stale payload outside the freshness window', () => {
+ const old = sign({ id: '42', auth_date: String(NOW / 1000 - tl.WIDGET_MAX_AGE_SEC - 1) });
+ expect(() => tl.verifyWidgetPayload(old, { env, now: NOW })).toThrow(expect.objectContaining({ code: 'stale' }));
+ });
+
+ it('rejects a payload dated in the future', () => {
+ const future = sign({ id: '42', auth_date: String(NOW / 1000 + 3600) });
+ expect(() => tl.verifyWidgetPayload(future, { env, now: NOW })).toThrow(expect.objectContaining({ code: 'invalid_payload' }));
+ });
+
+ it('refuses everything when no bot token is configured', () => {
+ expect(() => tl.verifyWidgetPayload(fresh(), { env: {}, now: NOW })).toThrow(expect.objectContaining({ code: 'not_configured' }));
+ });
+
+ it('treats the second use of the same payload as a replay', async () => {
+ queue.push([], [{ payload_hash: 'h' }]);
+ await tl.recordWidgetPayload('h', new Date(NOW));
+ queue.push([], []);
+ await expect(tl.recordWidgetPayload('h', new Date(NOW))).rejects.toMatchObject({ code: 'replayed', status: 409 });
+ });
+});
+
+describe('telegram magic link', () => {
+ const token = `tl_${'a'.repeat(43)}`;
+ const from = { id: 42, first_name: 'Ada', username: 'ada' };
+ const priv = { id: 42, type: 'private' };
+
+ it('rejects tokens that do not have the magic shape', async () => {
+ expect(await tl.claimMagicToken({ token: 'nope', from, chat: priv })).toEqual({ ok: false, reason: 'invalid' });
+ expect(calls).toHaveLength(0);
+ });
+
+ it('refuses to claim from a group chat', async () => {
+ expect(await tl.claimMagicToken({ token, from, chat: { id: -1, type: 'group' } })).toEqual({ ok: false, reason: 'group' });
+ });
+
+ it('a second tap (or an expired token) claims nothing', async () => {
+ queue.push([]);
+ expect(await tl.claimMagicToken({ token, from, chat: priv })).toEqual({ ok: false, reason: 'expired' });
+ });
+
+ it('a link token cannot attach a Telegram account owned by someone else', async () => {
+ queue.push([{ id: 'row1', intent: 'link', user_id: 'u1' }], []);
+ findUserByIdentity.mockResolvedValue({ id: 'u2' });
+ expect(await tl.claimMagicToken({ token, from, chat: priv })).toEqual({ ok: false, reason: 'in_use' });
+ });
+
+ it('completing a link from a different signed-in account is refused and burns the token', async () => {
+ queue.push([{ id: 'row1', intent: 'link', user_id: 'u1', claims: { subject: '42' } }], []);
+ await expect(tl.completeMagicToken({ id: 'row1', pollSecret: 's', sessionUserId: 'u2' })).rejects.toMatchObject({ code: 'wrong_account', status: 403 });
+ expect(calls.some((c) => /set status = 'expired'/.test(c.text))).toBe(true);
+ });
+
+ it('completing twice finds nothing to complete', async () => {
+ queue.push([]);
+ await expect(tl.completeMagicToken({ id: 'row1', pollSecret: 's' })).rejects.toMatchObject({ code: 'not_claimable', status: 409 });
+ });
+
+ it('only the poll secret unlocks a token row', async () => {
+ expect(await tl.readMagicToken({ id: 'row1', pollSecret: '' })).toBeNull();
+ queue.push([]);
+ expect(await tl.readMagicToken({ id: 'row1', pollSecret: 'wrong' })).toBeNull();
+ });
+});
+
+describe('link codes', () => {
+ it('normalizes case and separators and rejects junk', () => {
+ expect(lc.normalizeLinkCode('bcdf ghjk')).toBe('BCDFGHJK');
+ expect(lc.normalizeLinkCode('not a code')).toBeFalsy();
+ });
+
+ it('bounds a device description', () => {
+ const d = lc.describeClaim({ name: `x\u0000${'y'.repeat(500)}` });
+ expect(d.name.length).toBeLessThanOrEqual(80);
+ expect(d.name).not.toMatch(/\u0000/);
+ });
+
+ it('an unknown code is a 404', async () => {
+ queue.push([]);
+ await expect(lc.claimLinkCode({ code: 'BCDF-GHJK', claim: {} })).rejects.toMatchObject({ code: 'unknown_code', status: 404 });
+ });
+
+ it('a malformed code never reaches the database', async () => {
+ await expect(lc.claimLinkCode({ code: 'zzz', claim: {} })).rejects.toMatchObject({ code: 'invalid_code' });
+ expect(calls).toHaveLength(0);
+ });
+
+ it('an expired code is 410', async () => {
+ queue.push([{ id: 'c1', status: 'issued', device_kind: 'cli' }], []);
+ await expect(lc.claimLinkCode({ code: 'BCDF-GHJK', claim: {} })).rejects.toMatchObject({ code: 'expired', status: 410 });
+ });
+
+ it('a code that was already claimed cannot be claimed again', async () => {
+ queue.push([{ id: 'c1', status: 'claimed', device_kind: 'cli' }], []);
+ await expect(lc.claimLinkCode({ code: 'BCDF-GHJK', claim: {} })).rejects.toMatchObject({ code: 'already_used', status: 409 });
+ });
+
+ it('a code minted for another device kind is refused', async () => {
+ queue.push([{ id: 'c1', status: 'issued', device_kind: 'phone' }]);
+ await expect(lc.claimLinkCode({ code: 'BCDF-GHJK', claim: {}, expectKind: 'cli' })).rejects.toMatchObject({ code: 'wrong_kind' });
+ });
+
+ it('a different account cannot decide someone else\'s request', async () => {
+ queue.push([{ id: 'c1', user_id: 'owner', status: 'claimed', expires_at: new Date(Date.now() + 60000) }]);
+ await expect(lc.decideLinkCode({ id: 'c1', userId: 'intruder', decision: 'confirm' })).rejects.toMatchObject({ code: 'wrong_account', status: 403 });
+ expect(calls).toHaveLength(1);
+ });
+
+ it('confirming an expired request marks it expired and fails', async () => {
+ queue.push([{ id: 'c1', user_id: 'u', status: 'claimed', expires_at: new Date(Date.now() - 1000) }], []);
+ await expect(lc.decideLinkCode({ id: 'c1', userId: 'u', decision: 'confirm' })).rejects.toMatchObject({ code: 'expired', status: 410 });
+ });
+
+ it('a second confirm after the first finds the row decided', async () => {
+ queue.push([{ id: 'c1', user_id: 'u', status: 'confirmed', expires_at: new Date(Date.now() + 60000) }]);
+ await expect(lc.decideLinkCode({ id: 'c1', userId: 'u', decision: 'confirm' })).rejects.toMatchObject({ code: 'already_decided' });
+ });
+});
+
+describe('payout wallet policy', () => {
+ it('lets a first payout wallet through with no cooldown', async () => {
+ queue.push([]);
+ const p = await ew.payoutChangePolicy({ userId: 'u', chain: 'solana', address: 'A' });
+ expect(p.replacing).toBe(false);
+ expect(p.effectiveAt).toBe(p.approvedAt);
+ });
+
+ it('refuses to replace a live payout wallet without step-up', async () => {
+ queue.push([{ address: 'OLD' }]);
+ await expect(ew.payoutChangePolicy({ userId: 'u', chain: 'solana', address: 'NEW' })).rejects.toMatchObject({ code: 'step_up_required', status: 403 });
+ });
+
+ it('replaces it with step-up, but only after the 24 hour cooldown', async () => {
+ queue.push([{ address: 'OLD' }]);
+ const p = await ew.payoutChangePolicy({ userId: 'u', chain: 'solana', address: 'NEW', stepUp: true });
+ expect(p.replacing).toBe(true);
+ const wait = new Date(p.effectiveAt).getTime() - new Date(p.approvedAt).getTime();
+ expect(wait).toBeGreaterThanOrEqual(ew.PAYOUT_COOLDOWN_HOURS * 3600 * 1000 - 1000);
+ });
+
+ it('a proof with an unknown nonce is rejected', async () => {
+ queue.push([]);
+ await expect(ew.verifyWalletProof({ userId: 'u', chain: 'solana', message: 'm', signature: 's' })).rejects.toBeInstanceOf(ew.ExternalWalletError);
+ });
+});
diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.js
index 6b04b73e6..f226d9b19 100644
--- a/tests/api/mcp-agent.test.js
+++ b/tests/api/mcp-agent.test.js
@@ -122,7 +122,7 @@ describe('threews-agent MCP', () => {
'provision_wallet',
'monetize_endpoint',
'read_resource',
- 'browse_marketplace',
+ 'get_linked_accounts',
]);
// Every tool that moves funds is financial tier: hidden until the session
// turns its group on, so a default connection can never spend.