moon-iq 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1005 -0
- package/dist/index.js.map +1 -0
- package/package.json +24 -0
- package/src/auth.ts +325 -0
- package/src/client.ts +68 -0
- package/src/generated/client.ts +556 -0
- package/src/index.ts +307 -0
- package/tsconfig.json +10 -0
- package/tsup.config.ts +10 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/auth.ts","../src/generated/client.ts","../src/client.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command, Option } from \"commander\";\nimport {\n clearCredentials,\n getConfig,\n getConfigOrDefault,\n getCredentials,\n getValidToken,\n login,\n refreshCredentials,\n} from \"./auth\";\nimport { callToolWithAuth, TOOL_NAMES } from \"./client\";\nimport {\n TOOL_DEFINITIONS,\n type ToolDefinition,\n type ToolOption,\n} from \"./generated/client\";\n\nconst DEFAULT_BASE_URL = \"https://moon-iq.com\";\n\nconst program = new Command();\n\nprogram.name(\"mooniq\").description(\"Moon IQ CLI\").version(\"0.1.0\");\n\nprogram\n .command(\"login\")\n .description(\"Log in to Moon IQ via OAuth\")\n .option(\n \"-b, --base-url <url>\",\n \"Base URL (default: https://moon-iq.com or from ~/.mooniq/config.json)\",\n )\n .action(async (options) => {\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const config = getConfigOrDefault(baseUrl);\n\n try {\n await login({ ...config, baseUrl });\n console.log(\"Logged in successfully.\");\n } catch (error) {\n console.error(\"Login failed:\", (error as Error).message);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"logout\")\n .description(\"Log out and clear stored credentials\")\n .action(() => {\n clearCredentials();\n console.log(\"Logged out.\");\n });\n\nprogram\n .command(\"whoami\")\n .description(\"Show current user info\")\n .action(async () => {\n let token = await getValidToken();\n if (!token) {\n console.error(\"Not logged in. Run `mooniq login` first.\");\n process.exit(1);\n }\n\n const creds = getCredentials();\n const config = getConfig();\n const baseUrl =\n config?.baseUrl ?? creds?.baseUrl ?? DEFAULT_BASE_URL;\n\n let res = await fetch(`${baseUrl}/api/oauth/userinfo`, {\n headers: { Authorization: `Bearer ${token}` },\n });\n\n if (res.status === 401 && creds?.refreshToken && config && config.baseUrl === creds.baseUrl) {\n try {\n const newCreds = await refreshCredentials(creds, config);\n res = await fetch(`${baseUrl}/api/oauth/userinfo`, {\n headers: { Authorization: `Bearer ${newCreds.accessToken}` },\n });\n } catch {\n // Refresh failed, fall through\n }\n }\n\n if (!res.ok) {\n console.error(\"Failed to fetch user info:\", res.status);\n process.exit(1);\n }\n\n const userinfo = await res.json();\n console.log(JSON.stringify(userinfo, null, 2));\n });\n\nprogram\n .command(\"run <tool_name>\")\n .description(\"Run a tool by name. Use --input for JSON params.\")\n .option(\n \"-i, --input <json>\",\n \"Input parameters as JSON (omit for empty params)\",\n )\n .option(\n \"-b, --base-url <url>\",\n \"Base URL (default: from credentials or https://moon-iq.com)\",\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n mooniq run user_retrieve # no params\n mooniq run token_search --input '{\"query\":\"SOL\",\"chain\":\"solana\"}' # with params\n`,\n )\n .action(async (toolName: string, options) => {\n const toolNames = TOOL_NAMES as readonly string[];\n if (!toolNames.includes(toolName)) {\n console.error(`Unknown tool: ${toolName}`);\n console.error(`Available tools: ${toolNames.slice(0, 10).join(\", \")}...`);\n process.exit(1);\n }\n\n let params: Record<string, unknown> = {};\n if (options.input) {\n try {\n params = JSON.parse(options.input);\n } catch {\n console.error(\"Invalid JSON in --input\");\n process.exit(1);\n }\n }\n\n const creds = getCredentials();\n const config = getConfig();\n const baseUrl =\n options.baseUrl ?? config?.baseUrl ?? creds?.baseUrl ?? DEFAULT_BASE_URL;\n\n try {\n const result = await callToolWithAuth(baseUrl, toolName, params);\n console.log(JSON.stringify(result, null, 2));\n } catch (error) {\n console.error(\"Tool call failed:\", (error as Error).message);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"tools\")\n .description(\"List available tools\")\n .action(() => {\n TOOL_NAMES.forEach((name) => console.log(name));\n });\n\n/**\n * Build hierarchical subcommands from tool definitions.\n * e.g., token_balance_list -> mooniq token balance list --wallet <wallet> --chain <chain>\n */\nfunction buildToolCommands(program: Command): void {\n // Build a tree structure from tool names\n type CommandNode = {\n children: Map<string, CommandNode>;\n tool?: ToolDefinition;\n };\n\n const root: CommandNode = { children: new Map() };\n\n // Build the tree\n for (const tool of TOOL_DEFINITIONS) {\n const parts = tool.name.split(\"_\");\n let current = root;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (!current.children.has(part)) {\n current.children.set(part, { children: new Map() });\n }\n current = current.children.get(part)!;\n\n // If this is the last part, attach the tool\n if (i === parts.length - 1) {\n current.tool = tool;\n }\n }\n }\n\n // Recursively create Commander commands\n function createCommands(node: CommandNode, parent: Command, path: string[]) {\n for (const [name, child] of node.children) {\n const currentPath = [...path, name];\n\n if (child.tool) {\n // This is a leaf node with a tool\n const cmd = parent\n .command(name)\n .description(child.tool.description || `Run ${child.tool.name}`);\n\n // Add options from the tool schema\n for (const opt of child.tool.options) {\n const optionFlag = createOptionFlag(opt);\n const option = new Option(optionFlag, opt.description);\n\n if (opt.choices) {\n option.choices(opt.choices);\n }\n\n if (opt.required) {\n cmd.addOption(option);\n } else {\n cmd.addOption(option);\n }\n }\n\n // Add base-url option\n cmd.option(\n \"-b, --base-url <url>\",\n \"Base URL (default: from credentials or https://moon-iq.com)\",\n );\n\n // Add action handler\n const toolName = child.tool.name;\n cmd.action(async (options) => {\n const params = buildParams(child.tool!.options, options);\n\n const creds = getCredentials();\n const config = getConfig();\n const baseUrl =\n options.baseUrl ??\n config?.baseUrl ??\n creds?.baseUrl ??\n DEFAULT_BASE_URL;\n\n try {\n const result = await callToolWithAuth(baseUrl, toolName, params);\n console.log(JSON.stringify(result, null, 2));\n } catch (error) {\n console.error(\"Tool call failed:\", (error as Error).message);\n process.exit(1);\n }\n });\n\n // If there are more children, recurse\n if (child.children.size > 0) {\n createCommands(child, cmd, currentPath);\n }\n } else if (child.children.size > 0) {\n // This is an intermediate node\n const cmd = parent\n .command(name)\n .description(`${name} commands`);\n\n createCommands(child, cmd, currentPath);\n }\n }\n }\n\n createCommands(root, program, []);\n}\n\n/**\n * Create an option flag string for Commander\n */\nfunction createOptionFlag(opt: ToolOption): string {\n const kebabName = opt.name.replace(/([A-Z])/g, \"-$1\").toLowerCase();\n\n if (opt.type === \"boolean\") {\n return `--${kebabName}`;\n }\n\n const valuePlaceholder = `<${opt.name}>`;\n return `--${kebabName} ${valuePlaceholder}`;\n}\n\n/**\n * Build params object from options\n */\nfunction buildParams(\n toolOptions: ToolOption[],\n cmdOptions: Record<string, unknown>,\n): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n\n for (const opt of toolOptions) {\n // Convert kebab-case back to camelCase for lookup\n const kebabName = opt.name.replace(/([A-Z])/g, \"-$1\").toLowerCase();\n const camelName = kebabName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());\n\n // Commander converts --some-option to someOption\n const value = cmdOptions[camelName] ?? cmdOptions[opt.name];\n\n if (value !== undefined) {\n // Convert types as needed\n if (opt.type === \"number\" && typeof value === \"string\") {\n params[opt.name] = parseFloat(value);\n } else if (opt.type === \"boolean\") {\n params[opt.name] = value === true || value === \"true\";\n } else {\n params[opt.name] = value;\n }\n } else if (!opt.required) {\n // Set null for optional params that weren't provided\n params[opt.name] = null;\n }\n }\n\n return params;\n}\n\n// Build all tool commands\nbuildToolCommands(program);\n\nprogram.parse();\n","import { execSync } from \"child_process\";\nimport * as crypto from \"crypto\";\nimport * as fs from \"fs\";\nimport * as http from \"http\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nfunction generateCodeVerifier(): string {\n return crypto.randomBytes(32).toString(\"base64url\");\n}\n\nfunction generateCodeChallenge(verifier: string): string {\n return crypto.createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), \".mooniq\");\nconst CONFIG_PATH = path.join(CONFIG_DIR, \"config.json\");\nconst CREDENTIALS_PATH = path.join(CONFIG_DIR, \"credentials.json\");\nconst CALLBACK_PORT = 3847;\nconst CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`;\n\n/** Built-in config used when no ~/.mooniq/config.json exists. */\nexport const DEFAULT_CONFIG: Config = {\n baseUrl: \"https://moon-iq.com\",\n clientId: \"mooniq_zin3s5jz3olzkdfxpmbeaogv\",\n};\n\nexport type Config = {\n baseUrl: string;\n clientId: string;\n clientSecret?: string;\n};\n\nexport type Credentials = {\n accessToken: string;\n refreshToken: string | null;\n expiresAt: number;\n baseUrl: string;\n};\n\nfunction ensureConfigDir() {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n}\n\n/** Returns config from file, or null if missing/invalid. Use getConfigOrDefault() for login flow. */\nexport function getConfig(): Config | null {\n if (!fs.existsSync(CONFIG_PATH)) {\n return null;\n }\n try {\n const data = JSON.parse(fs.readFileSync(CONFIG_PATH, \"utf-8\"));\n if (!data.baseUrl || !data.clientId) {\n return null;\n }\n return data as Config;\n } catch {\n return null;\n }\n}\n\n/** Returns config from file, or DEFAULT_CONFIG if none exists. Creates config file on first use. */\nexport function getConfigOrDefault(baseUrl?: string): Config {\n const fromFile = getConfig();\n if (fromFile) return fromFile;\n\n const config: Config = {\n ...DEFAULT_CONFIG,\n baseUrl: baseUrl ?? DEFAULT_CONFIG.baseUrl,\n };\n saveConfig(config);\n return config;\n}\n\nexport function getCredentials(): Credentials | null {\n if (!fs.existsSync(CREDENTIALS_PATH)) {\n return null;\n }\n try {\n const data = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, \"utf-8\"));\n if (!data.accessToken || !data.baseUrl) {\n return null;\n }\n return data as Credentials;\n } catch {\n return null;\n }\n}\n\nexport function saveCredentials(creds: Credentials) {\n ensureConfigDir();\n fs.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2), \"utf-8\");\n}\n\nexport function saveConfig(config: Config) {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), \"utf-8\");\n}\n\nexport function clearCredentials() {\n if (fs.existsSync(CREDENTIALS_PATH)) {\n fs.unlinkSync(CREDENTIALS_PATH);\n }\n}\n\nfunction openBrowser(url: string) {\n const platform = process.platform;\n const command =\n platform === \"darwin\"\n ? `open \"${url}\"`\n : platform === \"win32\"\n ? `start \"\" \"${url}\"`\n : `xdg-open \"${url}\"`;\n execSync(command);\n}\n\nexport async function login(config: Config): Promise<Credentials> {\n const state = crypto.randomUUID();\n const usePkce = !config.clientSecret;\n\n let codeVerifier: string | undefined;\n if (usePkce) {\n codeVerifier = generateCodeVerifier();\n }\n\n let resolveCallback: (code: string) => void;\n const codePromise = new Promise<string>((resolve) => {\n resolveCallback = resolve;\n });\n\n let callbackSocket: import(\"net\").Socket | null = null;\n\n const server = http.createServer((req, res) => {\n const url = new URL(req.url ?? \"/\", `http://localhost:${CALLBACK_PORT}`);\n if (url.pathname === \"/callback\") {\n const code = url.searchParams.get(\"code\");\n const error = url.searchParams.get(\"error\");\n const errorDesc = url.searchParams.get(\"error_description\");\n\n if (error) {\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>OAuth Error</title></head><body style=\"font-family:system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:2rem;text-align:center;background:#fef2f2\"><h1 style=\"color:#b91c1c;margin:0 0 1rem\">OAuth Error</h1><p style=\"color:#991b1b;margin:0\">${error}: ${errorDesc ?? \"Unknown error\"}</p></body></html>`,\n );\n resolveCallback(\"\");\n setTimeout(() => server.close(), 2000);\n } else if (code) {\n callbackSocket = res.socket ?? (req.socket as import(\"net\").Socket);\n // Serve success page inline - don't redirect to app (it may not be running)\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Success</title></head><body style=\"font-family:system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:2rem;text-align:center;background:#f0fdf4\"><h1 style=\"color:#166534;margin:0 0 1rem;font-size:1.5rem\">✓ Success!</h1><p style=\"color:#15803d;margin:0;font-size:1.1rem\">You can close this page and return to the terminal.</p></body></html>`,\n );\n resolveCallback(code);\n } else {\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n `<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Error</title></head><body style=\"font-family:system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:2rem;text-align:center;background:#fef2f2\"><h1 style=\"color:#b91c1c;margin:0 0 1rem\">Error</h1><p style=\"color:#991b1b;margin:0\">No authorization code received.</p></body></html>`,\n );\n resolveCallback(\"\");\n setTimeout(() => server.close(), 2000);\n }\n } else {\n // Favicon etc - serve minimal response to avoid \"site can't be reached\"\n res.writeHead(204);\n res.end();\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n server.on(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\") {\n reject(\n new Error(\n `Port ${CALLBACK_PORT} is in use. Close the other process or run: lsof -i :${CALLBACK_PORT}`,\n ),\n );\n } else {\n reject(err);\n }\n });\n // Bind to all interfaces so both 127.0.0.1 and ::1 (localhost) can connect\n server.listen(CALLBACK_PORT, \"0.0.0.0\", () => resolve());\n });\n\n console.log(\n `Waiting for callback at http://localhost:${CALLBACK_PORT}/callback`,\n );\n\n const authorizeParams = new URLSearchParams({\n client_id: config.clientId,\n redirect_uri: CALLBACK_URL,\n response_type: \"code\",\n scope: \"profile email\",\n state,\n });\n if (usePkce && codeVerifier) {\n authorizeParams.set(\"code_challenge\", generateCodeChallenge(codeVerifier));\n authorizeParams.set(\"code_challenge_method\", \"S256\");\n }\n\n const authorizeUrl = `${config.baseUrl}/api/oauth/authorize?${authorizeParams.toString()}`;\n console.log(\"Opening browser for authorization...\");\n console.log(\"(Make sure you're logged in to Moon IQ in your browser)\\n\");\n openBrowser(authorizeUrl);\n\n const code = await codePromise;\n if (!code) {\n throw new Error(\"No authorization code received\");\n }\n\n const tokenParams: Record<string, string> = {\n grant_type: \"authorization_code\",\n code,\n client_id: config.clientId,\n redirect_uri: CALLBACK_URL,\n };\n if (config.clientSecret) {\n tokenParams.client_secret = config.clientSecret;\n }\n if (usePkce && codeVerifier) {\n tokenParams.code_verifier = codeVerifier;\n }\n\n const tokenResponse = await fetch(`${config.baseUrl}/api/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(tokenParams),\n });\n\n if (!tokenResponse.ok) {\n const err = (await tokenResponse.json().catch(() => ({}))) as {\n error?: string;\n error_description?: string;\n };\n const msg = err.error_description ?? err.error ?? tokenResponse.statusText;\n throw new Error(`Token exchange failed: ${msg}`);\n }\n\n const tokens = await tokenResponse.json();\n const expiresAt = Date.now() + (tokens.expires_in ?? 3600) * 1000;\n\n const creds: Credentials = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? null,\n expiresAt,\n baseUrl: config.baseUrl,\n };\n\n saveCredentials(creds);\n\n // Close callback server and connection so the process can exit (no hang after \"Logged in successfully.\")\n server.close();\n if (callbackSocket && \"destroy\" in callbackSocket) {\n (callbackSocket as { destroy: () => void }).destroy();\n }\n\n return creds;\n}\n\nexport async function refreshCredentials(\n creds: Credentials,\n config: Config,\n): Promise<Credentials> {\n if (!creds.refreshToken) {\n throw new Error(\"No refresh token available\");\n }\n\n const refreshParams: Record<string, string> = {\n grant_type: \"refresh_token\",\n refresh_token: creds.refreshToken,\n client_id: config.clientId,\n };\n if (config.clientSecret) {\n refreshParams.client_secret = config.clientSecret;\n }\n\n const tokenResponse = await fetch(`${config.baseUrl}/api/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(refreshParams),\n });\n\n if (!tokenResponse.ok) {\n throw new Error(\"Token refresh failed\");\n }\n\n const tokens = await tokenResponse.json();\n const expiresAt = Date.now() + (tokens.expires_in ?? 3600) * 1000;\n\n const newCreds: Credentials = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? creds.refreshToken,\n expiresAt,\n baseUrl: config.baseUrl,\n };\n\n saveCredentials(newCreds);\n return newCreds;\n}\n\nconst TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000; // 5 minutes\n\nexport async function getValidToken(): Promise<string | null> {\n const creds = getCredentials();\n if (!creds) return null;\n\n const config = getConfig();\n if (!config || config.baseUrl !== creds.baseUrl) return null;\n\n if (Date.now() >= creds.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n if (creds.refreshToken) {\n try {\n const newCreds = await refreshCredentials(creds, config);\n return newCreds.accessToken;\n } catch {\n return null;\n }\n }\n return null;\n }\n\n return creds.accessToken;\n}\n","// Generated by scripts/generate-cli-client.ts - do not edit\nexport const TOOL_NAMES = [\n \"iron_account_create\",\n \"iron_account_retrieve\",\n \"iron_offramp_create\",\n \"iron_offramp_initiate\",\n \"iron_offramp_list\",\n \"iron_offramp_retrieve\",\n \"iron_onramp_create\",\n \"iron_onramp_list\",\n \"iron_onramp_retrieve\",\n \"lending_account_retrieve\",\n \"lending_deposit\",\n \"lending_rate_retrieve\",\n \"lending_recommend\",\n \"lending_withdraw\",\n \"moonit_buy\",\n \"moonit_buy_recommend\",\n \"moonit_sell\",\n \"moonit_sell_recommend\",\n \"moonit_token_list\",\n \"moonpay_buy\",\n \"rhythm_token_list\",\n \"rhythm_token_trending_list\",\n \"rhythm_trade_list\",\n \"token_balance_list\",\n \"token_balance_retrieve\",\n \"token_buy\",\n \"token_digest_retrieve\",\n \"token_limit_buy\",\n \"token_limit_buy_recommend\",\n \"token_limit_order_list\",\n \"token_limit_recommend\",\n \"token_limit_sell\",\n \"token_limit_sell_recommend\",\n \"token_recurring_buy\",\n \"token_recurring_order_list\",\n \"token_recurring_recommend\",\n \"token_recurring_sell\",\n \"token_retrieve\",\n \"token_search\",\n \"token_sell\",\n \"token_swap\",\n \"token_swap_recommend\",\n \"token_trending_list\",\n \"user_retrieve\",\n \"user_update\"\n] as const;\n\nexport type ToolOption = {\n name: string;\n type: \"string\" | \"number\" | \"boolean\";\n description: string;\n required: boolean;\n choices?: string[];\n};\n\nexport type ToolDefinition = {\n name: string;\n description: string;\n options: ToolOption[];\n};\n\nexport const TOOL_DEFINITIONS: ToolDefinition[] = [\n {\n \"name\": \"iron_account_create\",\n \"description\": \"Create a new Iron account for the user.\",\n \"options\": []\n },\n {\n \"name\": \"iron_account_retrieve\",\n \"description\": \"Get the user's Iron account information.\",\n \"options\": []\n },\n {\n \"name\": \"iron_offramp_create\",\n \"description\": \"Create a new offramp for the user to convert crypto to fiat\",\n \"options\": [\n {\n \"name\": \"name\",\n \"type\": \"string\",\n \"description\": \"The name of the offramp\",\n \"required\": true\n },\n {\n \"name\": \"fiat\",\n \"type\": \"string\",\n \"description\": \"The fiat currency to convert to\",\n \"required\": true\n },\n {\n \"name\": \"stablecoin\",\n \"type\": \"string\",\n \"description\": \"The stablecoin token to convert from\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"iron_offramp_initiate\",\n \"description\": \"Initiate an offramp by sending stablecoin to the offramp's deposit account. The stablecoin will be converted to fiat and deposited into your registered bank account. This process is asynchronous and may take some time for funds to appear in your bank account.\",\n \"options\": []\n },\n {\n \"name\": \"iron_offramp_list\",\n \"description\": \"Get all offramps for the user\",\n \"options\": []\n },\n {\n \"name\": \"iron_offramp_retrieve\",\n \"description\": \"Get an offramp for the user\",\n \"options\": [\n {\n \"name\": \"offrampId\",\n \"type\": \"string\",\n \"description\": \"The ID of the offramp to retrieve\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"iron_onramp_create\",\n \"description\": \"Create an onramp to convert fiat currency to a stablecoin\",\n \"options\": [\n {\n \"name\": \"name\",\n \"type\": \"string\",\n \"description\": \"The name of the onramp\",\n \"required\": true\n },\n {\n \"name\": \"fiat\",\n \"type\": \"string\",\n \"description\": \"The fiat currency to convert from\",\n \"required\": true\n },\n {\n \"name\": \"stablecoin\",\n \"type\": \"string\",\n \"description\": \"The stablecoin token to convert to\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"iron_onramp_list\",\n \"description\": \"Get all onramps for the user\",\n \"options\": [\n {\n \"name\": \"status\",\n \"type\": \"string\",\n \"description\": \"Status of the onramps to get\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"iron_onramp_retrieve\",\n \"description\": \"Get an onramp for the user\",\n \"options\": [\n {\n \"name\": \"onrampId\",\n \"type\": \"string\",\n \"description\": \"The ID of the onramp to retrieve\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"lending_account_retrieve\",\n \"description\": \"Get account details for a lending account by wallet address, including balances, interest earned, and withdrawal limits\",\n \"options\": []\n },\n {\n \"name\": \"lending_deposit\",\n \"description\": \"Deposit USDC into your lending account to earn interest.\",\n \"options\": []\n },\n {\n \"name\": \"lending_rate_retrieve\",\n \"description\": \"Get current and historical interest rates for lending USDC\",\n \"options\": []\n },\n {\n \"name\": \"lending_recommend\",\n \"description\": \"Analyze user's lending account and wallet balances to recommend either a deposit or withdraw action with appropriate parameters. Understands queries like 'should I deposit more?', 'recommend a withdrawal', or 'what should I do with my lending account?'.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language query about lending recommendations. Examples: 'should I deposit more?', 'recommend a withdrawal', 'what should I do with my lending account?'.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"lending_withdraw\",\n \"description\": \"Withdraw USDC from your lending account.\",\n \"options\": []\n },\n {\n \"name\": \"moonit_buy\",\n \"description\": \"Buy tokens on Moonit platform using bonding curve. This tool converts USDC to SOL, then uses the SOL as collateral to buy Moonit tokens. It builds, signs, and executes the transaction. Note: This tool requires SOL for transaction fees.\",\n \"options\": []\n },\n {\n \"name\": \"moonit_buy_recommend\",\n \"description\": \"Parse natural language queries into structured buy parameters for Moonit on Solana. Understands queries like 'buy 100 USDC worth of Moonit token', 'buy $50 worth of token ABC', or 'buy all my USDC worth of Moonit token XYZ'. Returns the recommended buy parameters ready to use with moonit_buy.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired buy transaction on Moonit. Examples: 'buy 100 USDC worth of Moonit token', 'buy $50 worth of token ABC', 'buy all my USDC worth of Moonit token XYZ'. The agent will parse token and amount from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"moonit_sell\",\n \"description\": \"Sell tokens on Moonit platform using bonding curve. This tool sells Moonit tokens to get SOL, then converts SOL to USDC. It builds, signs, and executes the transaction. Note: This tool requires SOL for transaction fees.\",\n \"options\": []\n },\n {\n \"name\": \"moonit_sell_recommend\",\n \"description\": \"Parse natural language queries into structured sell parameters for Moonit on Solana. Understands queries like 'sell 100 SANTAMOON tokens', 'sell all my Moonit tokens', or 'sell 50% of my token ABC'. Returns the recommended sell parameters ready to use with moonit_sell.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired sell transaction on Moonit. Examples: 'sell 100 SANTAMOON tokens', 'sell all my Moonit tokens', 'sell 50% of my token ABC'. The agent will parse token and amount from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"moonit_token_list\",\n \"description\": \"Get the most popular Moonit tokens sorted by market capitalization. Moonit is a token launch platform by DEX Screener x Helio offering bonding curve mechanics, daily LP rewards, and graduation to Raydium/Meteora DEXs.\",\n \"options\": []\n },\n {\n \"name\": \"moonpay_buy\",\n \"description\": \"Buy a token using Moonpay. Specify either from.amount (USD to spend) or to.amount (tokens to buy), not both.\",\n \"options\": [\n {\n \"name\": \"from\",\n \"type\": \"string\",\n \"description\": \"Payment currency and amount to spend\",\n \"required\": true\n },\n {\n \"name\": \"to\",\n \"type\": \"string\",\n \"description\": \"Destination chain, currency, and token amount\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"rhythm_token_list\",\n \"description\": \"List tokens from Rhythm\",\n \"options\": []\n },\n {\n \"name\": \"rhythm_token_trending_list\",\n \"description\": \"Get trending tokens from Rhythm\",\n \"options\": [\n {\n \"name\": \"type\",\n \"type\": \"string\",\n \"description\": \"Type of trending tokens to get\",\n \"required\": true,\n \"choices\": [\n \"holding_strong\",\n \"survivor\",\n \"legacies\"\n ]\n }\n ]\n },\n {\n \"name\": \"rhythm_trade_list\",\n \"description\": \"Get whale trades from Rhythm discover\",\n \"options\": []\n },\n {\n \"name\": \"token_balance_list\",\n \"description\": \"List all token balances held in a wallet, including amount owned, current value in USD, and token details. Shows the complete token portfolio.\",\n \"options\": [\n {\n \"name\": \"wallet\",\n \"type\": \"string\",\n \"description\": \"Wallet address to check token balances for\",\n \"required\": true\n },\n {\n \"name\": \"chain\",\n \"type\": \"string\",\n \"description\": \"Blockchain to check balances on (e.g. 'solana', 'ethereum', 'base')\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_balance_retrieve\",\n \"description\": \"Get the balance of a specific token in a wallet, including the amount owned, current USD value, and token price. Returns zero balance if token is not held.\",\n \"options\": [\n {\n \"name\": \"wallet\",\n \"type\": \"string\",\n \"description\": \"Wallet address to check the balance for\",\n \"required\": true\n },\n {\n \"name\": \"token\",\n \"type\": \"string\",\n \"description\": \"Token address to check the balance of\",\n \"required\": true\n },\n {\n \"name\": \"chain\",\n \"type\": \"string\",\n \"description\": \"Blockchain where the token and wallet exist\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_buy\",\n \"description\": \"Swap the specified amount of USDC for a token.\",\n \"options\": []\n },\n {\n \"name\": \"token_digest_retrieve\",\n \"description\": \"Retrieve a token digest by token and chain.\",\n \"options\": [\n {\n \"name\": \"token\",\n \"type\": \"string\",\n \"description\": \"Token address\",\n \"required\": true\n },\n {\n \"name\": \"chain\",\n \"type\": \"string\",\n \"description\": \"Blockchain network where the token exists\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_limit_buy\",\n \"description\": \"Create a limit buy order to swap USDC for a token at a specific price.\",\n \"options\": []\n },\n {\n \"name\": \"token_limit_buy_recommend\",\n \"description\": \"Parse natural language queries into structured limit buy parameters. Understands queries like 'buy BONK at $0.00001', 'limit buy 100 USDC worth of SOL when price reaches $150', or 'buy BONK at $0.00001 with 50 USDC'. Returns the recommended limit buy parameters ready to use with token_limit_buy.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired limit buy order. Examples: 'buy BONK at $0.00001', 'limit buy 100 USDC worth of SOL when price reaches $150', 'buy BONK at $0.00001 with 50 USDC'. The agent will parse token, amount, and price from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_limit_order_list\",\n \"description\": \"Get limit orders for the authenticated user.\",\n \"options\": []\n },\n {\n \"name\": \"token_limit_recommend\",\n \"description\": \"Parse natural language queries into structured limit order parameters (buy or sell). Understands queries like 'buy BONK at $0.00001', 'sell BONK at $0.00002', 'limit buy 100 USDC worth of SOL when price reaches $150', or 'sell all my BONK at $0.00002'. Automatically determines if the request is a buy or sell order and returns the appropriate parameters ready to use with token_limit_buy or token_limit_sell.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired limit order (buy or sell). Examples: 'buy BONK at $0.00001', 'sell BONK at $0.00002', 'limit buy 100 USDC worth of SOL when price reaches $150', 'sell all my BONK at $0.00002'. The agent will parse the order type (buy/sell), token, amount, and price from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_limit_sell\",\n \"description\": \"Create a limit sell order to swap a token for USDC at a specific price.\",\n \"options\": []\n },\n {\n \"name\": \"token_limit_sell_recommend\",\n \"description\": \"Parse natural language queries into structured limit sell parameters. Understands queries like 'sell BONK at $0.00002', 'limit sell 100 SOL when price reaches $200', or 'sell all my BONK at $0.00002'. Returns the recommended limit sell parameters ready to use with token_limit_sell.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired limit sell order. Examples: 'sell BONK at $0.00002', 'limit sell 100 SOL when price reaches $200', 'sell all my BONK at $0.00002'. The agent will parse token, amount, and price from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_recurring_buy\",\n \"description\": \"Create a recurring buy order (DCA) to swap USDC for a token at regular intervals.\",\n \"options\": []\n },\n {\n \"name\": \"token_recurring_order_list\",\n \"description\": \"Get recurring orders.\",\n \"options\": []\n },\n {\n \"name\": \"token_recurring_recommend\",\n \"description\": \"Parse natural language queries into structured recurring order (DCA) parameters (buy or sell). Understands queries like 'buy BONK daily with 50 USDC for 10 days', 'sell BONK daily, 100 tokens per order for 10 days', 'DCA 100 USDC into SOL weekly for a month', or 'recurring sell SOL every day, 0.5 SOL, 20 orders'. Automatically determines if the request is a buy or sell order and returns the appropriate parameters ready to use with token_recurring_buy or token_recurring_sell.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired recurring order (buy or sell). Examples: 'buy BONK daily with 50 USDC for 10 days', 'sell BONK daily, 100 tokens per order for 10 days', 'DCA 100 USDC into SOL weekly for a month', 'recurring sell SOL every day, 0.5 SOL, 20 orders'. The agent will parse the order type (buy/sell), token, amount, interval, and numberOfOrders from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_recurring_sell\",\n \"description\": \"Create a recurring sell order (DCA) to swap a token for USDC at regular intervals.\",\n \"options\": []\n },\n {\n \"name\": \"token_retrieve\",\n \"description\": \"Get detailed token information including market data, price changes, volume, trades, and holder statistics by token address\",\n \"options\": [\n {\n \"name\": \"token\",\n \"type\": \"string\",\n \"description\": \"Address of the token to retrieve\",\n \"required\": true\n },\n {\n \"name\": \"chain\",\n \"type\": \"string\",\n \"description\": \"Blockchain network where the token exists\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_search\",\n \"description\": \"Search for tokens by name, symbol, or address. Returns matching tokens with their market data including price, volume, and liquidity.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Search term - can be token name (e.g. 'Bitcoin'), symbol (e.g. 'BTC'), or partial match\",\n \"required\": true\n },\n {\n \"name\": \"chain\",\n \"type\": \"string\",\n \"description\": \"Blockchain to search on (e.g. 'solana', 'ethereum', 'base')\",\n \"required\": true\n },\n {\n \"name\": \"limit\",\n \"type\": \"number\",\n \"description\": \"Maximum number of results to return (optional, defaults to 5)\",\n \"required\": false\n }\n ]\n },\n {\n \"name\": \"token_sell\",\n \"description\": \"Swap the specified amount of tokens for USDC.\",\n \"options\": []\n },\n {\n \"name\": \"token_swap\",\n \"description\": \"Swap the specified amount of input token for output token.\",\n \"options\": []\n },\n {\n \"name\": \"token_swap_recommend\",\n \"description\": \"Parse natural language queries into structured swap parameters for swapping tokens on Solana. Understands queries like 'swap 100 USDC for SOL', 'swap all my USDC for BONK', or '50 SOL to USDC'. Returns the recommended swap parameters ready to use with token_swap.\",\n \"options\": [\n {\n \"name\": \"query\",\n \"type\": \"string\",\n \"description\": \"Natural language description of the desired swap on Solana. Examples: 'swap 100 USDC for SOL', 'swap all my USDC for BONK', '50 SOL to USDC', 'convert my SOL to USDC'. The agent will parse tokens and amounts from this query.\",\n \"required\": true\n }\n ]\n },\n {\n \"name\": \"token_trending_list\",\n \"description\": \"Get currently trending tokens on a blockchain, sorted by popularity rank, trading volume, or liquidity. Perfect for discovering what's hot right now.\",\n \"options\": []\n },\n {\n \"name\": \"user_retrieve\",\n \"description\": \"Retrieve the currently authenticated user from the session context.\",\n \"options\": []\n },\n {\n \"name\": \"user_update\",\n \"description\": \"Update user fields in the database. This is a PUT-style update requiring all updatable fields (developer, firstName, lastName, username) to be sent. You must first call user_retrieve to get the current user state, then update with all four fields.\",\n \"options\": [\n {\n \"name\": \"developer\",\n \"type\": \"boolean\",\n \"description\": \"Whether the user is a developer\",\n \"required\": true\n },\n {\n \"name\": \"firstName\",\n \"type\": \"string\",\n \"description\": \"The user's first name, or null to clear it\",\n \"required\": false\n },\n {\n \"name\": \"lastName\",\n \"type\": \"string\",\n \"description\": \"The user's last name, or null to clear it\",\n \"required\": false\n },\n {\n \"name\": \"username\",\n \"type\": \"string\",\n \"description\": \"The user's username (3-20 lowercase letters, numbers, and underscores, must start with a letter), or null to clear it\",\n \"required\": false\n }\n ]\n }\n];\n\nexport async function callTool(\n baseUrl: string,\n token: string,\n toolName: string,\n params: Record<string, unknown>\n): Promise<unknown> {\n const res = await fetch(`${baseUrl}/api/tools/${toolName}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(params),\n });\n\n const data = await res.json();\n\n if (!res.ok) {\n throw new Error(data.error ?? \"Tool call failed\");\n }\n\n return data;\n}\n","import {\n getConfig,\n getCredentials,\n getValidToken,\n refreshCredentials,\n} from \"./auth\";\nimport { TOOL_NAMES } from \"./generated/client\";\n\nexport { TOOL_NAMES } from \"./generated/client\";\n\nasync function callToolWithToken(\n baseUrl: string,\n token: string,\n toolName: string,\n params: Record<string, unknown>\n): Promise<{ data: unknown; status: number }> {\n const res = await fetch(`${baseUrl}/api/tools/${toolName}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(params),\n });\n\n const data = await res.json();\n return { data, status: res.status };\n}\n\nexport async function callToolWithAuth(\n baseUrl: string,\n toolName: string,\n params: Record<string, unknown>\n): Promise<unknown> {\n let token = await getValidToken();\n if (!token) {\n throw new Error(\n \"Not logged in. Run `mooniq login` first and ensure ~/.mooniq/config.json has baseUrl and clientId.\"\n );\n }\n\n let result = await callToolWithToken(baseUrl, token, toolName, params);\n\n if (result.status === 401) {\n const creds = getCredentials();\n const config = getConfig();\n if (creds?.refreshToken && config && config.baseUrl === creds.baseUrl) {\n try {\n const newCreds = await refreshCredentials(creds, config);\n result = await callToolWithToken(\n baseUrl,\n newCreds.accessToken,\n toolName,\n params\n );\n } catch {\n // Refresh failed, fall through and throw the original 401\n }\n }\n }\n\n if (result.status < 200 || result.status >= 300) {\n const err = result.data as { error?: string };\n throw new Error(err?.error ?? \"Tool call failed\");\n }\n\n return result.data;\n}\n"],"mappings":";;;AACA,SAAS,SAAS,cAAc;;;ACDhC,SAAS,gBAAgB;AACzB,YAAY,YAAY;AACxB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,QAAQ;AACpB,YAAY,UAAU;AAEtB,SAAS,uBAA+B;AACtC,SAAc,mBAAY,EAAE,EAAE,SAAS,WAAW;AACpD;AAEA,SAAS,sBAAsB,UAA0B;AACvD,SAAc,kBAAW,QAAQ,EAAE,OAAO,QAAQ,EAAE,OAAO,WAAW;AACxE;AAEA,IAAM,aAAkB,UAAQ,WAAQ,GAAG,SAAS;AACpD,IAAM,cAAmB,UAAK,YAAY,aAAa;AACvD,IAAM,mBAAwB,UAAK,YAAY,kBAAkB;AACjE,IAAM,gBAAgB;AACtB,IAAM,eAAe,oBAAoB,aAAa;AAG/C,IAAM,iBAAyB;AAAA,EACpC,SAAS;AAAA,EACT,UAAU;AACZ;AAeA,SAAS,kBAAkB;AACzB,MAAI,CAAI,cAAW,UAAU,GAAG;AAC9B,IAAG,aAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAAA,EAC9C;AACF;AAGO,SAAS,YAA2B;AACzC,MAAI,CAAI,cAAW,WAAW,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,OAAO,KAAK,MAAS,gBAAa,aAAa,OAAO,CAAC;AAC7D,QAAI,CAAC,KAAK,WAAW,CAAC,KAAK,UAAU;AACnC,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,mBAAmB,SAA0B;AAC3D,QAAM,WAAW,UAAU;AA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K,QAAQ,YAAY,KAAK,EAAE,YAAY;AAClE,UAAM,YAAY,UAAU,QAAQ,aAAa,CAAC,GAAG,MAAM,EAAE,YAAY,CAAC;AAG1E,UAAM,QAAQ,WAAW,SAAS,KAAK,WAAW,IAAI,IAAI;AAE1D,QAAI,UAAU,QAAW;AAEvB,UAAI,IAAI,SAAS,YAAY,OAAO,UAAU,UAAU;AACtD,eAAO,IAAI,IAAI,IAAI,WAAW,KAAK;AAAA,MACrC,WAAW,IAAI,SAAS,WAAW;AACjC,eAAO,IAAI,IAAI,IAAI,UAAU,QAAQ,UAAU;AAAA,MACjD,OAAO;AACL,eAAO,IAAI,IAAI,IAAI;AAAA,MACrB;AAAA,IACF,WAAW,CAAC,IAAI,UAAU;AAExB,aAAO,IAAI,IAAI,IAAI;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AACT;AAGA,kBAAkB,OAAO;AAEzB,QAAQ,MAAM;","names":["code","program","path"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "moon-iq",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"bin": {
|
|
6
|
+
"mooniq": "dist/index.js",
|
|
7
|
+
"miq": "dist/index.js",
|
|
8
|
+
"moon-iq": "dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsup",
|
|
12
|
+
"dev": "tsx src/index.ts"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"commander": "^12.1.0",
|
|
16
|
+
"zod": "^3.25.76"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/node": "^20",
|
|
20
|
+
"tsup": "^8.3.5",
|
|
21
|
+
"tsx": "^4.19.2",
|
|
22
|
+
"typescript": "^5"
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { execSync } from "child_process";
|
|
2
|
+
import * as crypto from "crypto";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import * as http from "http";
|
|
5
|
+
import * as os from "os";
|
|
6
|
+
import * as path from "path";
|
|
7
|
+
|
|
8
|
+
function generateCodeVerifier(): string {
|
|
9
|
+
return crypto.randomBytes(32).toString("base64url");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function generateCodeChallenge(verifier: string): string {
|
|
13
|
+
return crypto.createHash("sha256").update(verifier).digest("base64url");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const CONFIG_DIR = path.join(os.homedir(), ".mooniq");
|
|
17
|
+
const CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
|
|
18
|
+
const CREDENTIALS_PATH = path.join(CONFIG_DIR, "credentials.json");
|
|
19
|
+
const CALLBACK_PORT = 3847;
|
|
20
|
+
const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`;
|
|
21
|
+
|
|
22
|
+
/** Built-in config used when no ~/.mooniq/config.json exists. */
|
|
23
|
+
export const DEFAULT_CONFIG: Config = {
|
|
24
|
+
baseUrl: "https://moon-iq.com",
|
|
25
|
+
clientId: "mooniq_zin3s5jz3olzkdfxpmbeaogv",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type Config = {
|
|
29
|
+
baseUrl: string;
|
|
30
|
+
clientId: string;
|
|
31
|
+
clientSecret?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type Credentials = {
|
|
35
|
+
accessToken: string;
|
|
36
|
+
refreshToken: string | null;
|
|
37
|
+
expiresAt: number;
|
|
38
|
+
baseUrl: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
function ensureConfigDir() {
|
|
42
|
+
if (!fs.existsSync(CONFIG_DIR)) {
|
|
43
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Returns config from file, or null if missing/invalid. Use getConfigOrDefault() for login flow. */
|
|
48
|
+
export function getConfig(): Config | null {
|
|
49
|
+
if (!fs.existsSync(CONFIG_PATH)) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const data = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
|
|
54
|
+
if (!data.baseUrl || !data.clientId) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
return data as Config;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Returns config from file, or DEFAULT_CONFIG if none exists. Creates config file on first use. */
|
|
64
|
+
export function getConfigOrDefault(baseUrl?: string): Config {
|
|
65
|
+
const fromFile = getConfig();
|
|
66
|
+
if (fromFile) return fromFile;
|
|
67
|
+
|
|
68
|
+
const config: Config = {
|
|
69
|
+
...DEFAULT_CONFIG,
|
|
70
|
+
baseUrl: baseUrl ?? DEFAULT_CONFIG.baseUrl,
|
|
71
|
+
};
|
|
72
|
+
saveConfig(config);
|
|
73
|
+
return config;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function getCredentials(): Credentials | null {
|
|
77
|
+
if (!fs.existsSync(CREDENTIALS_PATH)) {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const data = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, "utf-8"));
|
|
82
|
+
if (!data.accessToken || !data.baseUrl) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return data as Credentials;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function saveCredentials(creds: Credentials) {
|
|
92
|
+
ensureConfigDir();
|
|
93
|
+
fs.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2), "utf-8");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function saveConfig(config: Config) {
|
|
97
|
+
ensureConfigDir();
|
|
98
|
+
fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function clearCredentials() {
|
|
102
|
+
if (fs.existsSync(CREDENTIALS_PATH)) {
|
|
103
|
+
fs.unlinkSync(CREDENTIALS_PATH);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function openBrowser(url: string) {
|
|
108
|
+
const platform = process.platform;
|
|
109
|
+
const command =
|
|
110
|
+
platform === "darwin"
|
|
111
|
+
? `open "${url}"`
|
|
112
|
+
: platform === "win32"
|
|
113
|
+
? `start "" "${url}"`
|
|
114
|
+
: `xdg-open "${url}"`;
|
|
115
|
+
execSync(command);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function login(config: Config): Promise<Credentials> {
|
|
119
|
+
const state = crypto.randomUUID();
|
|
120
|
+
const usePkce = !config.clientSecret;
|
|
121
|
+
|
|
122
|
+
let codeVerifier: string | undefined;
|
|
123
|
+
if (usePkce) {
|
|
124
|
+
codeVerifier = generateCodeVerifier();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let resolveCallback: (code: string) => void;
|
|
128
|
+
const codePromise = new Promise<string>((resolve) => {
|
|
129
|
+
resolveCallback = resolve;
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
let callbackSocket: import("net").Socket | null = null;
|
|
133
|
+
|
|
134
|
+
const server = http.createServer((req, res) => {
|
|
135
|
+
const url = new URL(req.url ?? "/", `http://localhost:${CALLBACK_PORT}`);
|
|
136
|
+
if (url.pathname === "/callback") {
|
|
137
|
+
const code = url.searchParams.get("code");
|
|
138
|
+
const error = url.searchParams.get("error");
|
|
139
|
+
const errorDesc = url.searchParams.get("error_description");
|
|
140
|
+
|
|
141
|
+
if (error) {
|
|
142
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
143
|
+
res.end(
|
|
144
|
+
`<!DOCTYPE html><html><head><meta charset="utf-8"><title>OAuth Error</title></head><body style="font-family:system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:2rem;text-align:center;background:#fef2f2"><h1 style="color:#b91c1c;margin:0 0 1rem">OAuth Error</h1><p style="color:#991b1b;margin:0">${error}: ${errorDesc ?? "Unknown error"}</p></body></html>`,
|
|
145
|
+
);
|
|
146
|
+
resolveCallback("");
|
|
147
|
+
setTimeout(() => server.close(), 2000);
|
|
148
|
+
} else if (code) {
|
|
149
|
+
callbackSocket = res.socket ?? (req.socket as import("net").Socket);
|
|
150
|
+
// Serve success page inline - don't redirect to app (it may not be running)
|
|
151
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
152
|
+
res.end(
|
|
153
|
+
`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Success</title></head><body style="font-family:system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:2rem;text-align:center;background:#f0fdf4"><h1 style="color:#166534;margin:0 0 1rem;font-size:1.5rem">✓ Success!</h1><p style="color:#15803d;margin:0;font-size:1.1rem">You can close this page and return to the terminal.</p></body></html>`,
|
|
154
|
+
);
|
|
155
|
+
resolveCallback(code);
|
|
156
|
+
} else {
|
|
157
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
158
|
+
res.end(
|
|
159
|
+
`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Error</title></head><body style="font-family:system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:2rem;text-align:center;background:#fef2f2"><h1 style="color:#b91c1c;margin:0 0 1rem">Error</h1><p style="color:#991b1b;margin:0">No authorization code received.</p></body></html>`,
|
|
160
|
+
);
|
|
161
|
+
resolveCallback("");
|
|
162
|
+
setTimeout(() => server.close(), 2000);
|
|
163
|
+
}
|
|
164
|
+
} else {
|
|
165
|
+
// Favicon etc - serve minimal response to avoid "site can't be reached"
|
|
166
|
+
res.writeHead(204);
|
|
167
|
+
res.end();
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
await new Promise<void>((resolve, reject) => {
|
|
172
|
+
server.on("error", (err: NodeJS.ErrnoException) => {
|
|
173
|
+
if (err.code === "EADDRINUSE") {
|
|
174
|
+
reject(
|
|
175
|
+
new Error(
|
|
176
|
+
`Port ${CALLBACK_PORT} is in use. Close the other process or run: lsof -i :${CALLBACK_PORT}`,
|
|
177
|
+
),
|
|
178
|
+
);
|
|
179
|
+
} else {
|
|
180
|
+
reject(err);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
// Bind to all interfaces so both 127.0.0.1 and ::1 (localhost) can connect
|
|
184
|
+
server.listen(CALLBACK_PORT, "0.0.0.0", () => resolve());
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
console.log(
|
|
188
|
+
`Waiting for callback at http://localhost:${CALLBACK_PORT}/callback`,
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
const authorizeParams = new URLSearchParams({
|
|
192
|
+
client_id: config.clientId,
|
|
193
|
+
redirect_uri: CALLBACK_URL,
|
|
194
|
+
response_type: "code",
|
|
195
|
+
scope: "profile email",
|
|
196
|
+
state,
|
|
197
|
+
});
|
|
198
|
+
if (usePkce && codeVerifier) {
|
|
199
|
+
authorizeParams.set("code_challenge", generateCodeChallenge(codeVerifier));
|
|
200
|
+
authorizeParams.set("code_challenge_method", "S256");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const authorizeUrl = `${config.baseUrl}/api/oauth/authorize?${authorizeParams.toString()}`;
|
|
204
|
+
console.log("Opening browser for authorization...");
|
|
205
|
+
console.log("(Make sure you're logged in to Moon IQ in your browser)\n");
|
|
206
|
+
openBrowser(authorizeUrl);
|
|
207
|
+
|
|
208
|
+
const code = await codePromise;
|
|
209
|
+
if (!code) {
|
|
210
|
+
throw new Error("No authorization code received");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const tokenParams: Record<string, string> = {
|
|
214
|
+
grant_type: "authorization_code",
|
|
215
|
+
code,
|
|
216
|
+
client_id: config.clientId,
|
|
217
|
+
redirect_uri: CALLBACK_URL,
|
|
218
|
+
};
|
|
219
|
+
if (config.clientSecret) {
|
|
220
|
+
tokenParams.client_secret = config.clientSecret;
|
|
221
|
+
}
|
|
222
|
+
if (usePkce && codeVerifier) {
|
|
223
|
+
tokenParams.code_verifier = codeVerifier;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const tokenResponse = await fetch(`${config.baseUrl}/api/oauth/token`, {
|
|
227
|
+
method: "POST",
|
|
228
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
229
|
+
body: new URLSearchParams(tokenParams),
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
if (!tokenResponse.ok) {
|
|
233
|
+
const err = (await tokenResponse.json().catch(() => ({}))) as {
|
|
234
|
+
error?: string;
|
|
235
|
+
error_description?: string;
|
|
236
|
+
};
|
|
237
|
+
const msg = err.error_description ?? err.error ?? tokenResponse.statusText;
|
|
238
|
+
throw new Error(`Token exchange failed: ${msg}`);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const tokens = await tokenResponse.json();
|
|
242
|
+
const expiresAt = Date.now() + (tokens.expires_in ?? 3600) * 1000;
|
|
243
|
+
|
|
244
|
+
const creds: Credentials = {
|
|
245
|
+
accessToken: tokens.access_token,
|
|
246
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
247
|
+
expiresAt,
|
|
248
|
+
baseUrl: config.baseUrl,
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
saveCredentials(creds);
|
|
252
|
+
|
|
253
|
+
// Close callback server and connection so the process can exit (no hang after "Logged in successfully.")
|
|
254
|
+
server.close();
|
|
255
|
+
if (callbackSocket && "destroy" in callbackSocket) {
|
|
256
|
+
(callbackSocket as { destroy: () => void }).destroy();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return creds;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export async function refreshCredentials(
|
|
263
|
+
creds: Credentials,
|
|
264
|
+
config: Config,
|
|
265
|
+
): Promise<Credentials> {
|
|
266
|
+
if (!creds.refreshToken) {
|
|
267
|
+
throw new Error("No refresh token available");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const refreshParams: Record<string, string> = {
|
|
271
|
+
grant_type: "refresh_token",
|
|
272
|
+
refresh_token: creds.refreshToken,
|
|
273
|
+
client_id: config.clientId,
|
|
274
|
+
};
|
|
275
|
+
if (config.clientSecret) {
|
|
276
|
+
refreshParams.client_secret = config.clientSecret;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const tokenResponse = await fetch(`${config.baseUrl}/api/oauth/token`, {
|
|
280
|
+
method: "POST",
|
|
281
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
282
|
+
body: new URLSearchParams(refreshParams),
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
if (!tokenResponse.ok) {
|
|
286
|
+
throw new Error("Token refresh failed");
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const tokens = await tokenResponse.json();
|
|
290
|
+
const expiresAt = Date.now() + (tokens.expires_in ?? 3600) * 1000;
|
|
291
|
+
|
|
292
|
+
const newCreds: Credentials = {
|
|
293
|
+
accessToken: tokens.access_token,
|
|
294
|
+
refreshToken: tokens.refresh_token ?? creds.refreshToken,
|
|
295
|
+
expiresAt,
|
|
296
|
+
baseUrl: config.baseUrl,
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
saveCredentials(newCreds);
|
|
300
|
+
return newCreds;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000; // 5 minutes
|
|
304
|
+
|
|
305
|
+
export async function getValidToken(): Promise<string | null> {
|
|
306
|
+
const creds = getCredentials();
|
|
307
|
+
if (!creds) return null;
|
|
308
|
+
|
|
309
|
+
const config = getConfig();
|
|
310
|
+
if (!config || config.baseUrl !== creds.baseUrl) return null;
|
|
311
|
+
|
|
312
|
+
if (Date.now() >= creds.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {
|
|
313
|
+
if (creds.refreshToken) {
|
|
314
|
+
try {
|
|
315
|
+
const newCreds = await refreshCredentials(creds, config);
|
|
316
|
+
return newCreds.accessToken;
|
|
317
|
+
} catch {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return creds.accessToken;
|
|
325
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getConfig,
|
|
3
|
+
getCredentials,
|
|
4
|
+
getValidToken,
|
|
5
|
+
refreshCredentials,
|
|
6
|
+
} from "./auth";
|
|
7
|
+
import { TOOL_NAMES } from "./generated/client";
|
|
8
|
+
|
|
9
|
+
export { TOOL_NAMES } from "./generated/client";
|
|
10
|
+
|
|
11
|
+
async function callToolWithToken(
|
|
12
|
+
baseUrl: string,
|
|
13
|
+
token: string,
|
|
14
|
+
toolName: string,
|
|
15
|
+
params: Record<string, unknown>
|
|
16
|
+
): Promise<{ data: unknown; status: number }> {
|
|
17
|
+
const res = await fetch(`${baseUrl}/api/tools/${toolName}`, {
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers: {
|
|
20
|
+
"Content-Type": "application/json",
|
|
21
|
+
Authorization: `Bearer ${token}`,
|
|
22
|
+
},
|
|
23
|
+
body: JSON.stringify(params),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const data = await res.json();
|
|
27
|
+
return { data, status: res.status };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function callToolWithAuth(
|
|
31
|
+
baseUrl: string,
|
|
32
|
+
toolName: string,
|
|
33
|
+
params: Record<string, unknown>
|
|
34
|
+
): Promise<unknown> {
|
|
35
|
+
let token = await getValidToken();
|
|
36
|
+
if (!token) {
|
|
37
|
+
throw new Error(
|
|
38
|
+
"Not logged in. Run `mooniq login` first and ensure ~/.mooniq/config.json has baseUrl and clientId."
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let result = await callToolWithToken(baseUrl, token, toolName, params);
|
|
43
|
+
|
|
44
|
+
if (result.status === 401) {
|
|
45
|
+
const creds = getCredentials();
|
|
46
|
+
const config = getConfig();
|
|
47
|
+
if (creds?.refreshToken && config && config.baseUrl === creds.baseUrl) {
|
|
48
|
+
try {
|
|
49
|
+
const newCreds = await refreshCredentials(creds, config);
|
|
50
|
+
result = await callToolWithToken(
|
|
51
|
+
baseUrl,
|
|
52
|
+
newCreds.accessToken,
|
|
53
|
+
toolName,
|
|
54
|
+
params
|
|
55
|
+
);
|
|
56
|
+
} catch {
|
|
57
|
+
// Refresh failed, fall through and throw the original 401
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (result.status < 200 || result.status >= 300) {
|
|
63
|
+
const err = result.data as { error?: string };
|
|
64
|
+
throw new Error(err?.error ?? "Tool call failed");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return result.data;
|
|
68
|
+
}
|