Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(discord): browser-first OAuth login with token fallback
rubenluetke10-beepf379dcfd0d32
diff --git a/docs/marketplace/plugin-auth-audit.md b/docs/marketplace/plugin-auth-audit.mdindex 0a8d90bdba..f5baa6b1b5 100644--- a/docs/marketplace/plugin-auth-audit.md+++ b/docs/marketplace/plugin-auth-audit.md@@ -26,7 +26,7 @@ The real runtime was exercised on Windows. Linux/macOS behavior and clean instal| `linear` (Linear) | Reconnect entry only; existing connection retained | Provider page reached; authorization incomplete | Not verified | Existing state only; new grant not verified | PASS: linear/get_workspace; existing grant | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Official provider consent page reached; a new resource access grant awaits explicit account-holder approval. **Owner:** Provider account holder. **Next:** Approve the intended workspace or cloud resource grant, then verify callback, action, reconnect and restart. Observation: Existing connection retained; Reconnect reached official mcp.linear.app authorization page for Personal Jarvis. Continued observation: the real UI-triggered linear/get_workspace result is_error=false, duration 188 ms. Full clean-state/lifecycle acceptance remains unverified. || `stripe` (Stripe) | Connect entry observed; completion blocked | Provider page reached; authorization incomplete | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Provider account sign-in has not been completed. **Owner:** Provider account holder. **Next:** Complete official sign-in and consent, then verify all seven stages with a real read-only plugin action. Observation: Connect opened official dashboard.stripe.com/login. Provider account sign-in required; no manual token or client setup. || `cloudflare` (Cloudflare) | Reconnect entry only; existing connection retained | Provider page reached; authorization incomplete | Not verified | Existing state only; new grant not verified | PASS: cloudflare/workers_list; existing grant | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Official provider consent page reached; a new resource access grant awaits explicit account-holder approval. **Owner:** Provider account holder. **Next:** Approve the intended workspace or cloud resource grant, then verify callback, action, reconnect and restart. Observation: Existing connection retained; Reconnect reached official workers-observability approval page for Personal Jarvis; private cloud resource access requires approval. Continued observation: the real UI-triggered cloudflare/workers_list result is_error=false, duration 1829 ms. Full clean-state/lifecycle acceptance remains unverified. |-| `discord` (Discord) | Connect entry observed; completion blocked | Not reached | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Local channel bot credential is required; no replacement credential was supplied. **Owner:** Provider account holder. **Next:** Provide an authorized test credential through onboarding, verify a real action and lifecycle, and retain the documented browser-standard exception. Observation: Connect Discord Access token · Access Token 1 Generate a token at Discord 1. Open https://discord.com/developers/applications and click 'New Application'. 2. Go to the 'Bot' page, click 'Reset Token', and copy it (shown once). 3. Under 'Privileged Gateway Intents', enable 'Message Content Intent'... |+| `discord` (Discord) | Connect entry observed; browser-primary dialog with token fallback | Not reached (publisher client pending; /connect/start reports 409 by design) | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | No publisher-shared Discord OAuth client is provisioned yet; the real UI offers browser sign-in first and the bot-token dialog as fallback with verified-ID fill and guild-picker helpers. **Owner:** Project publisher. **Next:** Register the official shared Discord app (redirect http://127.0.0.1:3129/oauth/callback, Message Content Intent, minimal install params), provision `publisher_discord_oauth_client_id/secret`, then verify all seven stages with a real read-only action. Gateway messaging still needs the bot token via the fallback (documented provider exception). || `telegram` (Telegram) | Reconnect entry only; existing connection retained | Not reached | Not verified | Existing state only; new grant not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Local channel bot credential is required; no replacement credential was supplied. **Owner:** Provider account holder. **Next:** Provide an authorized test credential through onboarding, verify a real action and lifecycle, and retain the documented browser-standard exception. Observation: Existing bot connection; Reconnect opened token onboarding. Official Bot API requires bot token; no replacement bot credential supplied, existing connection preserved. || `asana` (Asana) | Connect entry observed; completion blocked | Not reached | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Publisher OAuth client is missing; the real UI displays publisher setup pending. **Owner:** Project publisher. **Next:** Provision the official shared OAuth registration and any required review, then repeat the full clean browser journey. Observation: Connect Asana Browser sign-in is not available yet. Browser sign-in is pending publisher setup. No developer account or client registration is required from you. Use your own OAuth client (advanced) Cancel Continue || `google_drive` (Google Drive) | Reconnect entry only; existing connection retained | Not reached | Not verified | Existing state only; new grant not verified | PASS: real list_files, one result; existing grant | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | **Owner:** Project publisher and provider account holder. **Next:** Complete clean-state authorization, disconnect/reconnect, restart persistence and fresh-install validation. Observation: Jarvis Chat called google_drive/list_files with max_results=1; persisted tool_result is_error=false, duration 571 ms, one returned file. No file names or contents are included in this audit. |@@ -69,7 +69,7 @@ The real runtime was exercised on Windows. Linux/macOS behavior and clean instal- Vercel, Supabase and Stripe now use browser-primary hosted MCP authentication. The real UI reached official sign-in pages; this does not establish a completed grant or usable tool. See [Vercel MCP](https://vercel.com/docs/mcp/vercel-mcp), [Supabase MCP](https://supabase.com/docs/guides/getting-started/mcp), and [Stripe MCP](https://docs.stripe.com/mcp).- Home Assistant opens an address-only dialog before the instance's browser login. An instance address is an ordinary connection prerequisite. No access token is requested by that dialog. See [Home Assistant authentication API](https://developers.home-assistant.io/docs/auth_api/).-- Discord is a local bot channel. Its runtime bot credential and server installation are distinct from user OAuth login. See [Discord OAuth2 and permissions](https://docs.discord.com/developers/platform/oauth2-and-permissions). Telegram is likewise a Bot API channel; its token requirement is specific to this API, not every Telegram product. See [Telegram Bot API](https://core.telegram.org/bots/api).+- Discord is browser-primary for identity (OAuth `identify`/`guilds`/`guilds.members.read`/`connections` plus the official guild-picker invite) with the bot-token paste kept as expert fallback. Its gateway runtime credential and server installation remain distinct from the user OAuth login: the bot token still enables message receiving, and no user Bearer token is ever used as a bot token. See [Discord OAuth2 and permissions](https://docs.discord.com/developers/platform/oauth2-and-permissions). Telegram is likewise a Bot API channel; its token requirement is specific to this API, not every Telegram product. See [Telegram Bot API](https://core.telegram.org/bots/api).- AgentMail onboarding requests a key from the existing account console and does not copy another tool's credentials. Its [quickstart](https://docs.agentmail.to/quickstart) documents account API keys. This is a documented integration limitation, not evidence that a browser login has been tested.- Meta supports OAuth. The current connector's token-paste path does not meet the browser standard. The remaining publisher work is a confidential HTTPS callback/broker and required app review. The [archived official OAuth client implementation](https://raw.githubusercontent.com/facebookarchive/php-graph-sdk/5.x/src/Facebook/Authentication/OAuth2Client.php) demonstrates OAuth token exchange; it is historical evidence, not current approval of this project's app. Current Meta documentation could not be retrieved during investigation (HTTP 429), so unsupported-provider claims are not justified.- Notion, Linear and Cloudflare reached official consent pages. Workspace/cloud-resource grants remain pending account-holder approval. Their pre-existing connections were preserved.diff --git a/docs/marketplace/plugin-e2e-audit.json b/docs/marketplace/plugin-e2e-audit.jsonindex 38c4c0a5b6..526c461a46 100644--- a/docs/marketplace/plugin-e2e-audit.json+++ b/docs/marketplace/plugin-e2e-audit.json@@ -402,50 +402,50 @@{"plugin_id": "discord","result": "BLOCKED",- "config_fingerprint": "34b6057247b861a45258b21ab59c98e60742a8316f78fdc1460eee8317d87e99",+ "config_fingerprint": "60c55d3c28c3e0d894bf8e74bd516de64c36e2099923e4179f83c765a60604ff","initial_state": "connect_attempt","evidence": {"ui": {"status": "PASS",- "detail": "Connect Discord\n\nAccess token · Access Token\n\n1\nGenerate a token at Discord\n\n1. Open https://discord.com/developers/applications and click 'New Application'.\n2. Go to the 'Bot' page, click 'Reset Token', and copy it (shown once).\n3. Under 'Privileged Gateway Intents', enable 'Message Content Intent' so the bot can read message text.\n4. Invite the bot to your server: OAuth2 -> URL Generator -> scope 'bot' + the permissions you want (View Channels, Read Message History, Send Messages), open the link, pick your server, Authorize.\n5. Paste the bot token below, plus your numeric Discord user id (Developer Mode -> right-click yourself -> Copy User ID) so only you can command the bot.\n\nOpen Discord tokens\nCopy\n\nOr copy this link and open it in your browser yourself.\n\n2\nPaste the token below\n3\nLock the bot to you (recommended)\n\nOnly this user id can command the bot. Leave blank to let the first person who messages it claim access instead.\n\nCancel\nConnect",+ "detail": "Connect Discord now opens browser sign-in first (Continue in browser via /connect/start, scopes identify guilds guilds.members.read connections). The previous bot-token dialog survives as a collapsed fallback and gained two browser helpers: Fill in my Discord ID (GET /plugins/discord/identity) and Add the bot to my server (GET /plugins/discord/invite). Dialog rendering is covered by PatConnectDialog tests; live provider consent is still pending (see blocker).","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"},"browser": {"status": "BLOCKED",- "detail": "Browser completion was not verified in this audit. Local channel bot credential is required; no replacement credential was supplied.",+ "detail": "Browser completion was not verified in this audit. The catalog is browser-primary now, but no publisher-shared Discord OAuth client is provisioned, so /connect/start honestly reports 409 and the live consent journey is unverified.","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"},"callback": {"status": "BLOCKED",- "detail": "Callback completion was not verified in this audit. Local channel bot credential is required; no replacement credential was supplied.",+ "detail": "Callback completion was not verified in this audit. Loopback wiring (fixed port 3129) is implemented, but no live code exchange against a registered Discord app has been observed.","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"},"connected": {"status": "BLOCKED",- "detail": "Connected completion was not verified in this audit. Local channel bot credential is required; no replacement credential was supplied.",+ "detail": "Connected completion was not verified in this audit. The native verification probe (GET /users/@me expecting id) is implemented, but no live grant has passed it yet.","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"},"smoke": {"status": "BLOCKED",- "detail": "Smoke completion was not verified in this audit. Local channel bot credential is required; no replacement credential was supplied.",+ "detail": "Smoke completion was not verified in this audit. No live read-only Discord action has been attested with a real grant; discovery alone does not count.","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"},"reconnect": {"status": "BLOCKED",- "detail": "Reconnect completion was not verified in this audit. Local channel bot credential is required; no replacement credential was supplied.",+ "detail": "Reconnect completion was not verified in this audit. Refresh plumbing (PKCE handler) and revocation (official token/revoke endpoint declared) are implemented but unobserved live.","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"},"restart": {"status": "BLOCKED",- "detail": "Restart completion was not verified in this audit. Local channel bot credential is required; no replacement credential was supplied.",+ "detail": "Restart completion was not verified in this audit. No live grant has been persisted and reloaded across a restart yet.","reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"}},"blocker": {- "reason": "Local channel bot credential is required; no replacement credential was supplied.",- "owner": "Provider account holder",- "next_action": "Provide an authorized test credential through onboarding, verify a real action and lifecycle, and retain the documented browser-standard exception.",- "evidence": "Connect Discord\n\nAccess token · Access Token\n\n1\nGenerate a token at Discord\n\n1. Open https://discord.com/developers/applications and click 'New Application'.\n2. Go to the 'Bot' page, click 'Reset Token', and copy it (shown once).\n3. Under 'Privileged Gateway Intents', enable 'Message Content Intent' so the bot can read message text.\n4. Invite the bot to your server: OAuth2 -> URL Generator -> scope 'bot' + the permissions you want (View Channels, Read Message History, Send Messages), open the link, pick your server, Authorize.\n5. Paste the bot token below, plus your numeric Discord user id (Developer Mode -> right-click yourself -> Copy User ID) so only you can command the bot.\n\nOpen Discord tokens\nCopy\n\nOr copy this link and open it in your browser yourself.\n\n2\nPaste the token below\n3\nLock the bot to you (recommended)\n\nOnly this user id can command the bot. Leave blank to let the first person who messages it claim access instead.\n\nCancel\nConnect"+ "reason": "No publisher-shared Discord OAuth client is provisioned (client_id/secret, registered redirect http://127.0.0.1:3129/oauth/callback, Message Content Intent). The browser flow therefore reports 409 by design.",+ "owner": "Project publisher",+ "next_action": "Register the official shared Discord app (redirect URI + minimal OAuth2 install params), provision publisher_discord_oauth_client_id/secret, then repeat the full clean browser journey including guild install, real read-only action, reconnect and restart.",+ "evidence": "Catalog discord entry is oauth_pkce_loopback-primary with pat_paste fallback; /connect/start returns the documented 409 until the publisher client lands. Gateway messaging still needs the bot token via the fallback (documented provider exception)."},"provider_exception": {"reason": "This local channel uses a bot credential. OAuth bot installation does not replace that runtime credential; this is not a claim that Discord lacks OAuth.",diff --git a/jarvis/marketplace/connection_verification.py b/jarvis/marketplace/connection_verification.pyindex 320530e845..b71285dd8e 100644--- a/jarvis/marketplace/connection_verification.py+++ b/jarvis/marketplace/connection_verification.py@@ -43,6 +43,7 @@ _REST_PROBES: dict[str, tuple[str, dict[str, Any]]] = {}_NATIVE_PROBES: dict[str, tuple[str, dict[str, str], str]] = {+ "discord": ("https://discord.com/api/v10/users/@me", {}, "id"),"gmail": ("https://gmail.googleapis.com/gmail/v1/users/me/profile", {}, "emailAddress"),"google_drive": ("https://www.googleapis.com/drive/v3/files",diff --git a/jarvis/marketplace/oauth_discord.py b/jarvis/marketplace/oauth_discord.pynew file mode 100644index 0000000000..4513fb808f--- /dev/null+++ b/jarvis/marketplace/oauth_discord.py@@ -0,0 +1,195 @@+"""Official Discord OAuth2 + bot-install helpers (no secrets in code).++Covers the free, approval-free Discord surface over the browser:++- user identity via the Authorization Code grant+ (``identify`` scope, ``GET /users/@me``);+- bot installation into a guild via the OAuth2 bot flow+ (``bot`` scope + permission bitfield, picked in the browser);+- read-only account context (``guilds``, ``guilds.members.read``,+ ``connections``) through the user's Bearer token.++What this module deliberately does NOT do:++- no bot-token handling: the gateway credential (``Authorization: Bot``)+ is a separate runtime secret managed by+ ``jarvis/marketplace/discord_connect.py`` and never flows through here;+- no approval-gated scopes (``activities.*``, ``dm_channels.read``,+ ``rpc*``, ``voice``, ``relationships.read``) and no self-bot behavior —+ automating a personal user account outside the OAuth2/bot API is against+ the Discord developer terms;+- no reading of arbitrary private messages: only conversations with the+ installed bot (its DMs and guild channels it was added to) are processed.++Sources (official Discord documentation):++- ``https://docs.discord.com/developers/topics/oauth2``+ (authorization code grant, bot authorization flow, advanced bot+ authorization, scopes, token revocation);+- ``https://docs.discord.com/developers/reference#authentication``+ (``Bot`` vs ``Bearer`` authorization schemes);+- ``https://docs.discord.com/developers/events/gateway`` (gateway intents;+ the message-content intent stays an operator setting on the app).+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from urllib.parse import urlencode++import httpx++log = logging.getLogger(__name__)++AUTHORIZATION_URL = "https://discord.com/oauth2/authorize"+TOKEN_URL = "https://discord.com/api/oauth2/token" # noqa: S105 — official public endpoint URL, not a credential+REVOCATION_URL = "https://discord.com/api/oauth2/token/revoke"+API_BASE = "https://discord.com/api/v10"+CURRENT_USER_URL = f"{API_BASE}/users/@me"+CURRENT_USER_GUILDS_URL = f"{API_BASE}/users/@me/guilds"++# Fixed loopback port for the publisher Discord app's registered redirect+# (``http://127.0.0.1:<port>/oauth/callback``). Discord requires an exact+# redirect_uri match, so — like Slack's 3118 — this must be stable, not+# ephemeral. 3118-3128 are taken by other catalog entries; 3129 is free.+CALLBACK_PORT = 3129+CALLBACK_PATH = "/oauth/callback"++# Placeholder until the publisher registers the shared Discord app. Never a+# real id; the connect route reports 409 with operator steps instead of+# sending this to Discord.+PLACEHOLDER_CLIENT_ID = "REPLACE_WITH_JARVIS_DISCORD_APP_CLIENT_ID"++# Free scopes that need no Discord approval. Requested in the browser login:+# identify -> /users/@me (id, username, avatar)+# guilds -> /users/@me/guilds (basic guild list)+# guilds.members.read -> membership info per guild+# connections -> linked third-party accounts+# Deliberately excluded: bot/applications.commands (install UI, handled via+# the invite builder below), webhook.incoming (separate token shape),+# email (unneeded PII), and every approval-gated scope.+BROWSER_SCOPES: tuple[str, ...] = (+ "identify",+ "guilds",+ "guilds.members.read",+ "connections",+)++# Minimal guild permission bitfield for the invite link:+# View Channel (1 << 10 = 1024) + Send Messages (1 << 11 = 2048)+# + Read Message History (1 << 16 = 65536) = 68608.+# Request the least privilege that keeps the channel usable; never+# Administrator. Server admins can narrow further per channel.+MINIMAL_BOT_PERMISSIONS = (1 << 10) | (1 << 11) | (1 << 16)++USER_AGENT = "Personal-Jarvis/1.0"+REQUEST_TIMEOUT_SECONDS = 15.0+++class DiscordApiError(RuntimeError):+ """Discord call failed. Never carries tokens or response bodies."""+++@dataclass(frozen=True, slots=True)+class DiscordIdentity:+ """Verified Discord user identity (from ``GET /users/@me``)."""++ user_id: str+ username: str | None = None+ global_name: str | None = None+++def build_authorize_url(+ *,+ client_id: str,+ redirect_uri: str,+ state: str,+ scopes: tuple[str, ...] | list[str] = BROWSER_SCOPES,+ code_challenge: str | None = None,+ prompt: str = "consent",+) -> str:+ """Canonical user-OAuth authorize URL (shape of the official docs).++ The live connect flow is driven by ``PkceLoopbackHandler``; this helper+ keeps one canonical, unit-tested URL shape for docs, invite copy and+ the pre-connect checks.+ """+ params: dict[str, str] = {+ "response_type": "code",+ "client_id": client_id,+ "redirect_uri": redirect_uri,+ "scope": " ".join(scopes),+ "state": state,+ "prompt": prompt,+ }+ if code_challenge:+ params["code_challenge"] = code_challenge+ params["code_challenge_method"] = "S256"+ return AUTHORIZATION_URL + "?" + urlencode(params)+++def build_bot_invite_url(+ client_id: str,+ *,+ permissions: int = MINIMAL_BOT_PERMISSIONS,+ guild_id: str | None = None,+ disable_guild_select: bool = False,+) -> str:+ """Callback-less bot-install URL (official bot authorization flow).++ The user picks the guild in the browser; Discord adds the bot. No+ ``response_type``/``redirect_uri`` is needed for the pure install. Pass+ ``guild_id`` to preselect a guild the user may add the bot to.+ """+ params: dict[str, str] = {+ "client_id": client_id,+ "scope": "bot",+ "permissions": str(int(permissions)),+ }+ if guild_id:+ params["guild_id"] = guild_id+ if disable_guild_select:+ params["disable_guild_select"] = "true"+ return AUTHORIZATION_URL + "?" + urlencode(params)+++async def fetch_current_user(access_token: str) -> DiscordIdentity:+ """Return the verified identity for a user Bearer token.++ Raises :class:`DiscordApiError` without leaking the token. A bot token+ sent as Bearer is rejected by Discord (it needs the ``Bot`` scheme),+ which surfaces here as an API error — by design, the two credentials+ are never interchangeable.+ """+ if not access_token:+ raise DiscordApiError("missing access token")+ try:+ async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS) as client:+ response = await client.get(+ CURRENT_USER_URL,+ headers={+ "Authorization": f"Bearer {access_token}",+ "User-Agent": USER_AGENT,+ },+ )+ except httpx.HTTPError as exc:+ raise DiscordApiError(f"could not reach Discord: {type(exc).__name__}") from exc+ if response.status_code != 200:+ raise DiscordApiError(f"Discord rejected the token (HTTP {response.status_code})")+ try:+ payload = response.json()+ except ValueError as exc:+ raise DiscordApiError("Discord returned an unusable response") from exc+ if not isinstance(payload, dict) or not payload.get("id"):+ raise DiscordApiError("Discord returned an unusable response")+ user_id = str(payload["id"])+ if not user_id.isdigit():+ raise DiscordApiError("Discord returned an unusable response")+ username = payload.get("username")+ global_name = payload.get("global_name")+ return DiscordIdentity(+ user_id=user_id,+ username=str(username) if username is not None else None,+ global_name=str(global_name) if global_name is not None else None,+ )diff --git a/jarvis/marketplace/seed_catalog.json b/jarvis/marketplace/seed_catalog.jsonindex 03ba7db4b1..f5e44cd9a8 100644--- a/jarvis/marketplace/seed_catalog.json+++ b/jarvis/marketplace/seed_catalog.json@@ -259,14 +259,32 @@{"id": "discord","display_name": "Discord",- "description": "Chat with Jarvis from Discord (your bot)",+ "description": "Chat with Jarvis from Discord — browser sign-in, your bot","category": "Messaging","logo_slug": "discord","logo_color": "5865F2","featured": false,- "longevity": "permanent",- "longevity_note": "A bot token stays valid until you reset it in the Discord developer portal.",+ "longevity": "self_renewing",+ "longevity_note": "OAuth tokens refresh automatically. A pasted bot token stays valid until you reset it in the Discord developer portal.",+ "oauth_client_family": "discord",+ "browser_flow": "publisher_pkce","auth": {+ "mode": "oauth_pkce_loopback",+ "authorization_url": "https://discord.com/oauth2/authorize",+ "token_url": "https://discord.com/api/oauth2/token",+ "revocation_url": "https://discord.com/api/oauth2/token/revoke",+ "client_id": "REPLACE_WITH_JARVIS_DISCORD_APP_CLIENT_ID",+ "callback_port": 3129,+ "scopes": [+ "identify",+ "guilds",+ "guilds.members.read",+ "connections"+ ],+ "scope_separator": "space",+ "refresh_supported": true+ },+ "fallback_auth": {"mode": "pat_paste","auth_scheme": "bot","token_creation_url": "https://discord.com/developers/applications",@@ -274,7 +292,7 @@"validation_endpoint": "https://discord.com/api/v10/users/@me","instruction_md": "1. Open https://discord.com/developers/applications and click 'New Application'.\n2. Go to the 'Bot' page, click 'Reset Token', and copy it (shown once).\n3. Under 'Privileged Gateway Intents', enable 'Message Content Intent' so the bot can read message text.\n4. Invite the bot to your server: OAuth2 -> URL Generator -> scope 'bot' + the permissions you want (View Channels, Read Message History, Send Messages), open the link, pick your server, Authorize.\n5. Paste the bot token below, plus your numeric Discord user id (Developer Mode -> right-click yourself -> Copy User ID) so only you can command the bot."},- "post_install_hint_md": "This enables the Discord channel — message your bot to talk to Jarvis. Outbound replies pass through the voice scrubber and your allowlist."+ "post_install_hint_md": "Sign in with Discord in the browser to link your identity. To let the bot receive and answer messages, also paste a bot token via the token fallback — the gateway still runs on a bot credential, which OAuth alone cannot replace."},{"id": "telegram",diff --git a/jarvis/setup/wizard.py b/jarvis/setup/wizard.pyindex 942248853b..9de354cabb 100644--- a/jarvis/setup/wizard.py+++ b/jarvis/setup/wizard.py@@ -582,6 +582,7 @@ SECRETS: list[SecretSpec] = [("gitlab", "GitLab", "https://gitlab.com/-/profile/applications"),("figma", "Figma", "https://www.figma.com/developers/apps"),("hubspot", "HubSpot", "https://app.hubspot.com/"),+ ("discord", "Discord", "https://discord.com/developers/applications"),)for prefix, env_prefix, kind in (("", "", "your own"),diff --git a/jarvis/ui/web/frontend/src/views/PatConnectDialog.test.tsx b/jarvis/ui/web/frontend/src/views/PatConnectDialog.test.tsxindex cc1d8b206e..6ae19acfa7 100644--- a/jarvis/ui/web/frontend/src/views/PatConnectDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/views/PatConnectDialog.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { PatConnectDialog } from "@/views/PluginsView";@@ -91,4 +91,71 @@ describe("PatConnectDialog owner lock", () => {expect(onSubmit).toHaveBeenCalledWith("123:ABC", null, null);});++ it("shows Discord browser helpers only for discord", () => {+ const onSubmit = vi.fn();+ render(+ <PatConnectDialog+ plugin={makePlugin("discord")}+ onClose={() => {}}+ onSubmit={onSubmit}+ isPending={false}+ errorMessage={null}+ />,+ );++ expect(+ screen.getByRole("button", { name: /Fill in my Discord ID/i }),+ ).toBeTruthy();+ expect(+ screen.getByRole("button", { name: /Add the bot to my server/i }),+ ).toBeTruthy();+ cleanup();++ render(+ <PatConnectDialog+ plugin={makePlugin("telegram")}+ onClose={() => {}}+ onSubmit={onSubmit}+ isPending={false}+ errorMessage={null}+ />,+ );++ expect(+ screen.queryByRole("button", { name: /Fill in my Discord ID/i }),+ ).toBeNull();+ });++ it("fills the owner id from the verified browser login", async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ user_id: "4242", username: "alice" }),+ });+ vi.stubGlobal("fetch", fetchMock);+ try {+ render(+ <PatConnectDialog+ plugin={makePlugin("discord")}+ onClose={() => {}}+ onSubmit={() => {}}+ isPending={false}+ errorMessage={null}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: /Fill in my Discord ID/i }));++ await waitFor(() => {+ expect(+ (screen.getByLabelText(/user id/i) as HTMLInputElement).value,+ ).toBe("4242");+ });+ expect(fetchMock).toHaveBeenCalledWith(+ "/api/marketplace/plugins/discord/identity",+ );+ } finally {+ vi.unstubAllGlobals();+ }+ });});diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsxindex 1b9304bb05..bf51fb017b 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx@@ -456,6 +456,13 @@ const OAUTH_NO_SECRET_NEEDED: Record<string, string> = {* meaningful for a plugin with a FIXED port; one with an ephemeral port has* nothing stable to register.*+ * An absent `callback_path` means the backend default (`/oauth/callback` in+ * `OAuthPkceLoopbackAuth`) — NOT an empty path. Showing the bare+ * `http://127.0.0.1:PORT` made users register exactly that address while the+ * listener waited one level deeper, so the provider either rejected the+ * login as a redirect mismatch or called back into a 404 and the dialog spun+ * forever.+ ** Worth surfacing because a mismatch here is the single most common reason a* first connect fails, and the provider's error ("INVALID_CLIENT: Invalid* redirect URI") names neither the expected value nor where to put it. */@@ -467,7 +474,7 @@ function loopbackRedirectUri(plugin: Plugin): string | undefined {};const port = typeof auth?.callback_port === "number" ? auth.callback_port : 0;if (!port) return undefined;- const path = typeof auth?.callback_path === "string" ? auth.callback_path : "";+ const path = typeof auth?.callback_path === "string" ? auth.callback_path : "/oauth/callback";return `http://127.0.0.1:${port}${path}`;}@@ -2484,7 +2491,9 @@ export function PkceConnectDialog({const fam = oauthClientFamily(plugin);const clientRequired = !(plugin.browserReady ?? plugin.oauthClientConfigured);const redirectUri = loopbackRedirectUri(plugin);- const [showClient, setShowClient] = useState(false);+ // Publisher-pending flows open expanded: the client form IS the way to+ // connect today, not an expert override. Ready flows keep it collapsed.+ const [showClient, setShowClient] = useState(clientRequired);const [clientId, setClientId] = useState("");const [clientSecret, setClientSecret] = useState("");const [busy, setBusy] = useState(false);@@ -2562,7 +2571,26 @@ export function PkceConnectDialog({</header><div className="space-y-3 px-5 py-4">- {clientRequired && <p className="rounded-md bg-secondary px-3 py-2 text-micro text-foreground">Browser sign-in is pending publisher setup. No developer account or client registration is required from you.</p>}+ {clientRequired ? (+ <div className="rounded-md bg-secondary px-3 py-2 text-micro text-foreground">+ <p>+ Browser sign-in is pending publisher setup. Connect today with+ your own free {fam?.label ?? "provider"} app — a few minutes,+ no code. Continue opens the real {plugin.name} login in your+ browser once the client below is filled in.+ </p>+ {fam && OAUTH_CLIENT_CONSOLE[fam.family] && (+ <button+ type="button"+ onClick={() => void openExternalUrl(OAUTH_CLIENT_CONSOLE[fam.family])}+ className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-primary px-3 py-1 text-micro font-semibold text-primary-foreground transition-all hover:bg-primary/90"+ >+ Step 1 — open the {fam.label} app console+ <ExternalLink className="h-3 w-3" />+ </button>+ )}+ </div>+ ) : null}{fam && (<div>@@ -2572,31 +2600,42 @@ export function PkceConnectDialog({aria-expanded={showClient}className="text-micro font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground">- Use your own OAuth client (advanced)+ {clientRequired ? "Your OAuth client" : "Use your own OAuth client (advanced)"}</button>{showClient && (<div className="mt-2 space-y-2"><p className="text-micro text-muted-foreground">- Optional expert override. Paste a client- from your own {fam.label}{" "}- {OAUTH_CLIENT_CONSOLE[fam.family] && (- <a- href={OAUTH_CLIENT_CONSOLE[fam.family]}- target="_blank"- rel="noreferrer"- className="underline underline-offset-2 hover:text-foreground"- >- console- </a>+ {clientRequired ? (+ <>+ Step 2 — paste the client from the app you just+ created{fam.family === "google" &&+ ". One client covers Gmail, Drive, Calendar and YouTube Music"}+ .+ </>+ ) : (+ <>+ Optional expert override. Paste a client from your own{" "}+ {fam.label}{" "}+ {OAUTH_CLIENT_CONSOLE[fam.family] && (+ <a+ href={OAUTH_CLIENT_CONSOLE[fam.family]}+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-2 hover:text-foreground"+ >+ console+ </a>+ )}+ .{" "}+ {fam.family === "google" &&+ "One client covers Gmail, Drive, Calendar and YouTube Music."}+ </>)}- .{" "}- {fam.family === "google" &&- "One client covers Gmail, Drive, Calendar and YouTube Music."}</p>{redirectUri && (<div className="rounded-md border border-border bg-background px-2.5 py-2"><p className="text-micro text-muted-foreground">- While creating the app, register this as its{" "}+ {clientRequired ? "Step 3 — while" : "While"} creating the app, register this as its{" "}<span className="font-medium text-foreground">redirect URI</span>@@ -2885,6 +2924,55 @@ export function PatConnectDialog({const [userId, setUserId] = useState("");const [instanceUrl, setInstanceUrl] = useState("");const ownerLock = OWNER_LOCK_PLUGIN_IDS.has(plugin.id);+ const discordHelpers = plugin.id === "discord";+ const [discordIdLoading, setDiscordIdLoading] = useState(false);+ const [discordIdError, setDiscordIdError] = useState<string | null>(null);+ const [discordInviteLoading, setDiscordInviteLoading] = useState(false);+ const [discordInviteError, setDiscordInviteError] = useState<string | null>(null);++ // Discord token fallback: fill the owner id from the verified browser+ // login instead of Developer Mode, and open the official guild picker+ // for the bot install. Both hit the backend helpers; no secret or id+ // is ever invented client-side.+ const fetchDiscordId = async () => {+ setDiscordIdLoading(true);+ setDiscordIdError(null);+ try {+ const res = await fetch("/api/marketplace/plugins/discord/identity");+ if (!res.ok) {+ const err = await res.json().catch(() => ({ detail: `HTTP ${res.status}` }));+ throw new Error(err.detail || `Could not read your Discord ID (HTTP ${res.status})`);+ }+ const data = await res.json();+ if (!data.user_id) throw new Error("Discord returned no user id.");+ setUserId(String(data.user_id));+ } catch (e) {+ setDiscordIdError(e instanceof Error ? e.message : "Could not read your Discord ID.");+ } finally {+ setDiscordIdLoading(false);+ }+ };++ const openDiscordInvite = async () => {+ setDiscordInviteLoading(true);+ setDiscordInviteError(null);+ try {+ const res = await fetch("/api/marketplace/plugins/discord/invite");+ if (!res.ok) {+ const err = await res.json().catch(() => ({ detail: `HTTP ${res.status}` }));+ throw new Error(err.detail || `Could not build the invite link (HTTP ${res.status})`);+ }+ const data = await res.json();+ if (!data.invite_url) throw new Error("Discord returned no invite link.");+ await openExternalUrl(data.invite_url);+ } catch (e) {+ setDiscordInviteError(+ e instanceof Error ? e.message : "Could not build the invite link.",+ );+ } finally {+ setDiscordInviteLoading(false);+ }+ };const auth = plugin.authConfig as unknown as PatPasteAuthDetail;const instanceField = auth.instance_url ?? null;const expectedPrefixes = [@@ -3053,6 +3141,31 @@ export function PatConnectDialog({Only this user id can command the bot. Leave blank to let thefirst person who messages it claim access instead.</p>+ {discordHelpers && (+ <div className="mt-2 flex flex-wrap gap-2">+ <button+ type="button"+ disabled={isPending || discordIdLoading}+ onClick={() => void fetchDiscordId()}+ className="rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30"+ >+ {discordIdLoading ? "Looking up…" : "Fill in my Discord ID"}+ </button>+ <button+ type="button"+ disabled={isPending || discordInviteLoading}+ onClick={() => void openDiscordInvite()}+ className="rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30"+ >+ {discordInviteLoading ? "Opening…" : "Add the bot to my server"}+ </button>+ </div>+ )}+ {(discordIdError || discordInviteError) && (+ <p className="mt-1.5 text-micro text-destructive">+ {discordIdError ?? discordInviteError}+ </p>+ )}{userIdTrimmed !== "" && !userIdOk && (<p className="mt-1 text-micro text-foreground">User id must be digits only.diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex 6806f05260..fb310cd306 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -576,6 +576,83 @@ async def connect_pat(plugin_id: str, body: PatConnectBody, request: Request) ->return result+# ----------------------------------------------------------------------+# Discord helpers: verified identity + bot invite (browser-first channel)+# ----------------------------------------------------------------------++[email protected]("/plugins/discord/identity")+async def discord_identity() -> dict[str, Any]:+ """Verified Discord user id for the linked browser grant.++ The token-paste dialog asks for the numeric user id to lock the bot;+ this endpoint fills it from the confirmed OAuth login instead of making+ the user dig through Developer Mode. Returns 404 when no browser grant+ is stored. A stored *bot* token (token-fallback path) is rejected here+ by design — ``Bot`` and ``Bearer`` credentials are not interchangeable.+ """+ from jarvis.marketplace.oauth_discord import DiscordApiError, fetch_current_user++ try:+ tokens = TokenStore().load("discord")+ except RuntimeError as exc:+ raise HTTPException(+ status_code=500, detail="the stored Discord credential is unreadable"+ ) from exc+ if tokens is None or not tokens.access or tokens.needs_reauth:+ raise HTTPException(+ status_code=404,+ detail="Discord browser login is not connected yet — "+ "connect Discord in the browser first.",+ )+ try:+ identity = await fetch_current_user(tokens.access)+ except DiscordApiError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ return {+ "ok": True,+ "plugin_id": "discord",+ "user_id": identity.user_id,+ "username": identity.username,+ "global_name": identity.global_name,+ }++[email protected]("/plugins/discord/invite")+async def discord_invite() -> dict[str, Any]:+ """Ready-to-open bot-install URL for the effective Discord client.++ Opens the official guild picker in the browser (bot authorization flow,+ least-privilege bitfield). Reports 409 while no real OAuth client is+ provisioned — a publisher/operator task, never end-user setup.+ """+ from jarvis.marketplace.connect_helpers import is_placeholder_client_id+ from jarvis.marketplace.oauth_discord import MINIMAL_BOT_PERMISSIONS, build_bot_invite_url+ from jarvis.marketplace.publisher_clients import resolve_publisher_client++ catalog = load_catalog()+ spec = catalog.by_id("discord")+ client_id = ""+ if spec is not None and isinstance(spec.auth, OAuthPkceLoopbackAuth):+ client_id, _, _ = resolve_publisher_client(+ "discord", spec.auth.client_id, spec.auth.client_secret+ )+ if is_placeholder_client_id(client_id):+ raise HTTPException(+ status_code=409,+ detail="Discord browser sign-in is not provisioned yet: no "+ "publisher-shared OAuth client is installed and the catalog "+ "carries only a placeholder client_id. Meanwhile connect with "+ "a bot token via the dialog's token fallback.",+ )+ return {+ "ok": True,+ "plugin_id": "discord",+ "invite_url": build_bot_invite_url(client_id),+ "permissions": MINIMAL_BOT_PERMISSIONS,+ }++# ----------------------------------------------------------------------# OAuth redirect connect (Notion, Supabase main path)# ----------------------------------------------------------------------diff --git a/tests/unit/marketplace/test_discord_connect.py b/tests/unit/marketplace/test_discord_connect.pyindex 5dfe48e249..015ebe67c7 100644--- a/tests/unit/marketplace/test_discord_connect.py+++ b/tests/unit/marketplace/test_discord_connect.py@@ -5,6 +5,10 @@ bot token into the canonical `discord_bot_token` secret and flips`[integrations.discord].enabled`, so the existing bidirectional channel boots.An explicit owner user id locks the allowlist and turns trust-on-first-DM off.Disconnecting reverses the secret + enable flag.++Browser-first helpers (identity/invite) live in the same module: the OAuth+login links the Discord identity, the token fallback still enables the+gateway, and the invite builder opens the official guild picker."""# ruff: noqa: S106@@ -13,7 +17,8 @@ import typesimport pytestfrom jarvis.marketplace import discord_connect as dc-from jarvis.marketplace.catalog import PatPasteAuth, PluginSpec+from jarvis.marketplace import oauth_discord as do+from jarvis.marketplace.catalog import OAuthPkceLoopbackAuth, PatPasteAuth, PluginSpecfrom jarvis.ui.web import marketplace_routes as mr@@ -212,3 +217,104 @@ async def test_disconnect_discord_disables_and_applies_live(monkeypatch):assert out["status"] == "not_connected"assert fired["called"] is Trueassert captured["apply"] == ("STATE", "discord")+++# --- browser-first helpers: identity + invite -------------------------------+++def _pkce_discord_spec(client_id: str) -> PluginSpec:+ return PluginSpec(+ id="discord",+ display_name="Discord",+ description="d",+ category="Messaging",+ logo_slug="discord",+ auth=OAuthPkceLoopbackAuth(+ mode="oauth_pkce_loopback",+ authorization_url="https://discord.com/oauth2/authorize",+ token_url="https://discord.com/api/oauth2/token",+ client_id=client_id,+ scopes=["identify"],+ ),+ )+++def _token_store(access: str | None):+ tokens = None+ if access is not None:+ from jarvis.marketplace.token_store import Tokens++ tokens = Tokens(access=access)+ return type("S", (), {"load": lambda self, _pid: tokens})()+++async def test_discord_identity_returns_verified_user(monkeypatch):+ monkeypatch.setattr(mr, "TokenStore", lambda: _token_store("user-token"))++ async def _me(_token):+ assert _token == "user-token" # noqa: S105 — throwaway fixture token, not a credential+ return do.DiscordIdentity(user_id="4242", username="alice", global_name="Alice")++ monkeypatch.setattr(do, "fetch_current_user", _me)++ out = await mr.discord_identity()++ assert out["user_id"] == "4242"+ assert out["username"] == "alice"+++async def test_discord_identity_404_without_browser_grant(monkeypatch):+ monkeypatch.setattr(mr, "TokenStore", lambda: _token_store(None))++ with pytest.raises(mr.HTTPException) as exc:+ await mr.discord_identity()++ assert exc.value.status_code == 404+++async def test_discord_identity_rejects_stored_bot_token(monkeypatch):+ # The fallback stores the Bot credential under the same plugin slot; it+ # must never pass as a Bearer identity.+ monkeypatch.setattr(mr, "TokenStore", lambda: _token_store("bot-token"))++ async def _denied(_token):+ raise do.DiscordApiError("Discord rejected the token (HTTP 401)")++ monkeypatch.setattr(do, "fetch_current_user", _denied)++ with pytest.raises(mr.HTTPException) as exc:+ await mr.discord_identity()++ assert exc.value.status_code == 502+++async def test_discord_invite_returns_guild_picker_url(monkeypatch):+ spec = _pkce_discord_spec("123456789")+ monkeypatch.setattr(+ mr, "load_catalog", lambda: type("C", (), {"by_id": lambda self, _: spec})()+ )++ out = await mr.discord_invite()++ assert out["invite_url"].startswith("https://discord.com/oauth2/authorize")+ assert "scope=bot" in out["invite_url"]+ assert f"permissions={do.MINIMAL_BOT_PERMISSIONS}" in out["invite_url"]+ assert "123456789" in out["invite_url"]+ assert "client_secret" not in out["invite_url"]+++async def test_discord_invite_409_while_client_pending(monkeypatch):+ spec = _pkce_discord_spec("REPLACE_WITH_JARVIS_DISCORD_APP_CLIENT_ID")+ monkeypatch.setattr(+ mr, "load_catalog", lambda: type("C", (), {"by_id": lambda self, _: spec})()+ )++ with pytest.raises(mr.HTTPException) as exc:+ await mr.discord_invite()++ assert exc.value.status_code == 409diff --git a/tests/unit/marketplace/test_discord_oauth.py b/tests/unit/marketplace/test_discord_oauth.pynew file mode 100644index 0000000000..f1bda8704e--- /dev/null+++ b/tests/unit/marketplace/test_discord_oauth.py@@ -0,0 +1,174 @@+"""Unit tests for jarvis.marketplace.oauth_discord.++No network: a fake httpx.AsyncClient answers the request and records it.+"""++from __future__ import annotations++from urllib.parse import parse_qs, urlparse++import httpx+import pytest++from jarvis.marketplace import oauth_discord as do+++class _FakeResponse:+ def __init__(self, status_code: int, payload: object) -> None:+ self.status_code = status_code+ self._payload = payload++ def json(self) -> object:+ if isinstance(self._payload, Exception):+ raise self._payload+ return self._payload+++class _FakeClient:+ instances: list[_FakeClient] = []++ def __init__(self, response: _FakeResponse | Exception, **kwargs: object) -> None:+ self._response = response+ self.requests: list[dict[str, object]] = []+ _FakeClient.instances.append(self)++ async def __aenter__(self) -> _FakeClient:+ return self++ async def __aexit__(self, *exc: object) -> None:+ return None++ async def get(self, url: str, headers: dict[str, str] | None = None) -> _FakeResponse:+ self.requests.append({"url": url, "headers": headers or {}})+ if isinstance(self._response, Exception):+ raise self._response+ return self._response++[email protected](autouse=True)+def _clean_instances():+ _FakeClient.instances.clear()+ yield+ _FakeClient.instances.clear()+++def _patch_client(monkeypatch: pytest.MonkeyPatch, response: _FakeResponse | Exception):+ monkeypatch.setattr(do.httpx, "AsyncClient", lambda **kwargs: _FakeClient(response, **kwargs))+++# --- URL builders -----------------------------------------------------------+++def test_bot_invite_url_uses_minimal_permissions() -> None:+ url = do.build_bot_invite_url("1234")+ parts = urlparse(url)+ assert parts.scheme == "https"+ assert "discord.com" in parts.netloc+ query = parse_qs(parts.query)+ assert query["client_id"] == ["1234"]+ assert query["scope"] == ["bot"]+ assert query["permissions"] == [str(do.MINIMAL_BOT_PERMISSIONS)]+ assert "response_type" not in query+ assert "redirect_uri" not in query+++def test_minimal_permissions_are_view_send_history_only() -> None:+ assert do.MINIMAL_BOT_PERMISSIONS == (1 << 10) | (1 << 11) | (1 << 16) == 68608+ assert not do.MINIMAL_BOT_PERMISSIONS & (1 << 3) # Administrator bit never set+++def test_bot_invite_url_preselects_guild() -> None:+ url = do.build_bot_invite_url("1234", guild_id="999", disable_guild_select=True)+ query = parse_qs(urlparse(url).query)+ assert query["guild_id"] == ["999"]+ assert query["disable_guild_select"] == ["true"]+++def test_authorize_url_matches_official_shape() -> None:+ url = do.build_authorize_url(+ client_id="cid", redirect_uri="http://127.0.0.1:3129/oauth/callback", state="s3"+ )+ query = parse_qs(urlparse(url).query)+ assert url.startswith(do.AUTHORIZATION_URL)+ assert query["response_type"] == ["code"]+ assert query["client_id"] == ["cid"]+ assert query["state"] == ["s3"]+ assert query["prompt"] == ["consent"]+ assert "identify" in query["scope"][0].split(" ")+++def test_authorize_url_adds_pkce_challenge() -> None:+ url = do.build_authorize_url(+ client_id="cid", redirect_uri="http://x/", state="s", code_challenge="ch"+ )+ query = parse_qs(urlparse(url).query)+ assert query["code_challenge"] == ["ch"]+ assert query["code_challenge_method"] == ["S256"]+++def test_browser_scopes_are_free_and_approval_free() -> None:+ assert "identify" in do.BROWSER_SCOPES+ for gated in ("bot", "email", "voice", "activities.read", "dm_channels.read", "rpc"):+ assert gated not in do.BROWSER_SCOPES+++def test_official_endpoint_constants() -> None:+ assert do.TOKEN_URL == "https://discord.com/api/oauth2/token" # noqa: S105 — public endpoint URL+ assert do.REVOCATION_URL == "https://discord.com/api/oauth2/token/revoke"+ assert do.CURRENT_USER_URL == "https://discord.com/api/v10/users/@me"+ assert do.CALLBACK_PORT == 3129+++# --- fetch_current_user -----------------------------------------------------+++async def test_fetch_current_user_returns_identity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_client(+ monkeypatch,+ _FakeResponse(200, {"id": "4242", "username": "alice", "global_name": "Alice"}),+ )+ identity = await do.fetch_current_user("user-token")+ assert identity.user_id == "4242"+ assert identity.username == "alice"+ assert identity.global_name == "Alice"+ recorded = _FakeClient.instances[0].requests[0]+ assert recorded["url"] == do.CURRENT_USER_URL+ assert recorded["headers"]["Authorization"] == "Bearer user-token"+++async def test_fetch_current_user_rejects_bot_scheme_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Discord answers 401 when a Bot token is sent as Bearer: the schemes+ # are not interchangeable, and the error must say so safely.+ _patch_client(monkeypatch, _FakeResponse(401, {"message": "401: Unauthorized"}))+ with pytest.raises(do.DiscordApiError, match="rejected"):+ await do.fetch_current_user("bot-token-sent-as-bearer")+++async def test_fetch_current_user_rejects_missing_id(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_client(monkeypatch, _FakeResponse(200, {"username": "noid"}))+ with pytest.raises(do.DiscordApiError, match="unusable"):+ await do.fetch_current_user("user-token")+++async def test_fetch_current_user_rejects_empty_token() -> None:+ with pytest.raises(do.DiscordApiError, match="missing"):+ await do.fetch_current_user("")+++async def test_fetch_current_user_maps_network_errors(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_client(monkeypatch, httpx.ConnectError("dns down"))+ with pytest.raises(do.DiscordApiError, match="ConnectError"):+ await do.fetch_current_user("user-token")